Completed
Branch FET-10486-add-timestamp-checki... (786b14)
by
unknown
79:06 queued 65:28
created
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +19 added lines, -17 removed lines patch added patch discarded remove patch
@@ -961,7 +961,7 @@  discard block
 block discarded – undo
961 961
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
962 962
      * foreign key to the WP_User table)
963 963
      *
964
-     * @return string|boolean string on success, boolean false when there is no
964
+     * @return string|false string on success, boolean false when there is no
965 965
      * foreign key to the WP_User table
966 966
      */
967 967
     public function wp_user_field_name()
@@ -1067,7 +1067,7 @@  discard block
 block discarded – undo
1067 1067
      *
1068 1068
      * @param array  $query_params      like EEM_Base::get_all's $query_params
1069 1069
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1070
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
1071 1071
      *                                  fields on the model, and the models we joined to in the query. However, you can
1072 1072
      *                                  override this and set the select to "*", or a specific column name, like
1073 1073
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1459,7 +1459,7 @@  discard block
 block discarded – undo
1459 1459
      * @param string $field_name The name of the field the formats are being retrieved for.
1460 1460
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1461 1461
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1462
-     * @return array formats in an array with the date format first, and the time format last.
1462
+     * @return string[] formats in an array with the date format first, and the time format last.
1463 1463
      */
1464 1464
     public function get_formats_for($field_name, $pretty = false)
1465 1465
     {
@@ -1492,7 +1492,7 @@  discard block
 block discarded – undo
1492 1492
      *                                 be returned.
1493 1493
      * @param string $what             Whether to return the string in just the time format, the date format, or both.
1494 1494
      * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1495
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1495
+     * @return string|null  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1496 1496
      *                                 exception is triggered.
1497 1497
      */
1498 1498
     public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
@@ -1532,7 +1532,7 @@  discard block
 block discarded – undo
1532 1532
      *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1533 1533
      *                                format is
1534 1534
      *                                'U', this is ignored.
1535
-     * @return DateTime
1535
+     * @return string
1536 1536
      * @throws \EE_Error
1537 1537
      */
1538 1538
     public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
@@ -1830,7 +1830,7 @@  discard block
 block discarded – undo
1830 1830
      * Wrapper for EEM_Base::delete_permanently()
1831 1831
      *
1832 1832
      * @param mixed $id
1833
-     * @return boolean whether the row got deleted or not
1833
+     * @return integer whether the row got deleted or not
1834 1834
      * @throws \EE_Error
1835 1835
      */
1836 1836
     public function delete_permanently_by_ID($id)
@@ -1850,7 +1850,7 @@  discard block
 block discarded – undo
1850 1850
      * Wrapper for EEM_Base::delete()
1851 1851
      *
1852 1852
      * @param mixed $id
1853
-     * @return boolean whether the row got deleted or not
1853
+     * @return integer whether the row got deleted or not
1854 1854
      * @throws \EE_Error
1855 1855
      */
1856 1856
     public function delete_by_ID($id)
@@ -2300,7 +2300,7 @@  discard block
 block discarded – undo
2300 2300
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2301 2301
      * EEM_Base::$_db_verification_level
2302 2302
      *
2303
-     * @param $wpdb_method
2303
+     * @param string $wpdb_method
2304 2304
      * @param $arguments_to_provide
2305 2305
      * @return string
2306 2306
      */
@@ -2424,6 +2424,7 @@  discard block
 block discarded – undo
2424 2424
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2425 2425
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2426 2426
      *                             because these will be inserted in any new rows created as well.
2427
+     * @param EE_Base_Class $id_or_obj
2427 2428
      */
2428 2429
     public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2429 2430
     {
@@ -2434,7 +2435,7 @@  discard block
 block discarded – undo
2434 2435
 
2435 2436
 
2436 2437
     /**
2437
-     * @param mixed           $id_or_obj
2438
+     * @param EE_Base_Class           $id_or_obj
2438 2439
      * @param string          $relationName
2439 2440
      * @param array           $where_query_params
2440 2441
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2475,7 +2476,7 @@  discard block
 block discarded – undo
2475 2476
      * However, if the model objects can't be deleted because of blocking related model objects, then
2476 2477
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2477 2478
      *
2478
-     * @param EE_Base_Class|int|string $id_or_obj
2479
+     * @param EE_Base_Class $id_or_obj
2479 2480
      * @param string                   $model_name
2480 2481
      * @param array                    $query_params
2481 2482
      * @return int how many deleted
@@ -2496,7 +2497,7 @@  discard block
 block discarded – undo
2496 2497
      * the model objects can't be hard deleted because of blocking related model objects,
2497 2498
      * just does a soft-delete on them instead.
2498 2499
      *
2499
-     * @param EE_Base_Class|int|string $id_or_obj
2500
+     * @param EE_Base_Class $id_or_obj
2500 2501
      * @param string                   $model_name
2501 2502
      * @param array                    $query_params
2502 2503
      * @return int how many deleted
@@ -2553,6 +2554,7 @@  discard block
 block discarded – undo
2553 2554
      * @param string $model_name   like 'Event', or 'Registration'
2554 2555
      * @param array  $query_params like EEM_Base::get_all's
2555 2556
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2557
+     * @param EE_Base_Class $id_or_obj
2556 2558
      * @return float
2557 2559
      * @throws \EE_Error
2558 2560
      */
@@ -3023,7 +3025,7 @@  discard block
 block discarded – undo
3023 3025
      * Finds all the fields that correspond to the given table
3024 3026
      *
3025 3027
      * @param string $table_alias , array key in EEM_Base::_tables
3026
-     * @return EE_Model_Field_Base[]
3028
+     * @return EE_Model_Field_Base
3027 3029
      */
3028 3030
     public function _get_fields_for_table($table_alias)
3029 3031
     {
@@ -3508,7 +3510,7 @@  discard block
 block discarded – undo
3508 3510
      * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3509 3511
      * We should use default where conditions on related models when they requested to use default where conditions
3510 3512
      * on all models, or specifically just on other related models
3511
-     * @param      $default_where_conditions_value
3513
+     * @param      string $default_where_conditions_value
3512 3514
      * @param bool $for_this_model false means this is for OTHER related models
3513 3515
      * @return bool
3514 3516
      */
@@ -3546,7 +3548,7 @@  discard block
 block discarded – undo
3546 3548
      * where conditions.
3547 3549
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3548 3550
      * on this model or others
3549
-     * @param      $default_where_conditions_value
3551
+     * @param      string $default_where_conditions_value
3550 3552
      * @param bool $for_this_model false means this is for OTHER related models
3551 3553
      * @return bool
3552 3554
      */
@@ -4536,7 +4538,7 @@  discard block
 block discarded – undo
4536 4538
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4537 4539
      * Eg, on EE_Answer that would be ANS_ID field object
4538 4540
      *
4539
-     * @param $field_obj
4541
+     * @param EE_Model_Field_Base $field_obj
4540 4542
      * @return boolean
4541 4543
      */
4542 4544
     public function is_primary_key_field($field_obj)
@@ -4647,7 +4649,7 @@  discard block
 block discarded – undo
4647 4649
      * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4648 4650
      *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4649 4651
      *                            Either one works
4650
-     * @return EE_Table_Base
4652
+     * @return string
4651 4653
      */
4652 4654
     public function get_table_for_alias($table_alias)
4653 4655
     {
@@ -5258,7 +5260,7 @@  discard block
 block discarded – undo
5258 5260
     /**
5259 5261
      * Read comments for assume_values_already_prepared_by_model_object()
5260 5262
      *
5261
-     * @return int
5263
+     * @return boolean
5262 5264
      */
5263 5265
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5264 5266
     {
Please login to merge, or discard this patch.
Indentation   +5817 added lines, -5817 removed lines patch added patch discarded remove patch
@@ -29,5825 +29,5825 @@
 block discarded – undo
29 29
 abstract class EEM_Base extends EE_Base
30 30
 {
31 31
 
32
-    //admin posty
33
-    //basic -> grants access to mine -> if they don't have it, select none
34
-    //*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
35
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
36
-    //*_published -> grants access to published -> if they dont have it, select non-published
37
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
38
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
39
-    //frontend posty
40
-    //by default has access to published
41
-    //basic -> grants access to mine that arent published, and all published
42
-    //*_others ->grants access to others that arent private, all mine
43
-    //*_private -> grants full access
44
-    //frontend non-posty
45
-    //like admin posty
46
-    //category-y
47
-    //assign -> grants access to join-table
48
-    //(delete, edit)
49
-    //payment-method-y
50
-    //for each registered payment method,
51
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
52
-    /**
53
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
54
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
55
-     * They almost always WILL NOT, but it's not necessarily a requirement.
56
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
57
-     *
58
-     * @var boolean
59
-     */
60
-    private $_values_already_prepared_by_model_object = 0;
61
-
62
-    /**
63
-     * when $_values_already_prepared_by_model_object equals this, we assume
64
-     * the data is just like form input that needs to have the model fields'
65
-     * prepare_for_set and prepare_for_use_in_db called on it
66
-     */
67
-    const not_prepared_by_model_object = 0;
68
-
69
-    /**
70
-     * when $_values_already_prepared_by_model_object equals this, we
71
-     * assume this value is coming from a model object and doesn't need to have
72
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
73
-     */
74
-    const prepared_by_model_object = 1;
75
-
76
-    /**
77
-     * when $_values_already_prepared_by_model_object equals this, we assume
78
-     * the values are already to be used in the database (ie no processing is done
79
-     * on them by the model's fields)
80
-     */
81
-    const prepared_for_use_in_db = 2;
82
-
83
-
84
-    protected $singular_item = 'Item';
85
-
86
-    protected $plural_item   = 'Items';
87
-
88
-    /**
89
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
90
-     */
91
-    protected $_tables;
92
-
93
-    /**
94
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
95
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
96
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
97
-     *
98
-     * @var \EE_Model_Field_Base[] $_fields
99
-     */
100
-    protected $_fields;
101
-
102
-    /**
103
-     * array of different kinds of relations
104
-     *
105
-     * @var \EE_Model_Relation_Base[] $_model_relations
106
-     */
107
-    protected $_model_relations;
108
-
109
-    /**
110
-     * @var \EE_Index[] $_indexes
111
-     */
112
-    protected $_indexes = array();
113
-
114
-    /**
115
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
116
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
117
-     * by setting the same columns as used in these queries in the query yourself.
118
-     *
119
-     * @var EE_Default_Where_Conditions
120
-     */
121
-    protected $_default_where_conditions_strategy;
122
-
123
-    /**
124
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
125
-     * This is particularly useful when you want something between 'none' and 'default'
126
-     *
127
-     * @var EE_Default_Where_Conditions
128
-     */
129
-    protected $_minimum_where_conditions_strategy;
130
-
131
-    /**
132
-     * String describing how to find the "owner" of this model's objects.
133
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
134
-     * But when there isn't, this indicates which related model, or transiently-related model,
135
-     * has the foreign key to the wp_users table.
136
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
137
-     * related to events, and events have a foreign key to wp_users.
138
-     * On EEM_Transaction, this would be 'Transaction.Event'
139
-     *
140
-     * @var string
141
-     */
142
-    protected $_model_chain_to_wp_user = '';
143
-
144
-    /**
145
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
146
-     * don't need it (particularly CPT models)
147
-     *
148
-     * @var bool
149
-     */
150
-    protected $_ignore_where_strategy = false;
151
-
152
-    /**
153
-     * String used in caps relating to this model. Eg, if the caps relating to this
154
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
155
-     *
156
-     * @var string. If null it hasn't been initialized yet. If false then we
157
-     * have indicated capabilities don't apply to this
158
-     */
159
-    protected $_caps_slug = null;
160
-
161
-    /**
162
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
163
-     * and next-level keys are capability names, and each's value is a
164
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
165
-     * they specify which context to use (ie, frontend, backend, edit or delete)
166
-     * and then each capability in the corresponding sub-array that they're missing
167
-     * adds the where conditions onto the query.
168
-     *
169
-     * @var array
170
-     */
171
-    protected $_cap_restrictions = array(
172
-        self::caps_read       => array(),
173
-        self::caps_read_admin => array(),
174
-        self::caps_edit       => array(),
175
-        self::caps_delete     => array(),
176
-    );
177
-
178
-    /**
179
-     * Array defining which cap restriction generators to use to create default
180
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
181
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
182
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
183
-     * automatically set this to false (not just null).
184
-     *
185
-     * @var EE_Restriction_Generator_Base[]
186
-     */
187
-    protected $_cap_restriction_generators = array();
188
-
189
-    /**
190
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
191
-     */
192
-    const caps_read       = 'read';
193
-
194
-    const caps_read_admin = 'read_admin';
195
-
196
-    const caps_edit       = 'edit';
197
-
198
-    const caps_delete     = 'delete';
199
-
200
-    /**
201
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
202
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
203
-     * maps to 'read' because when looking for relevant permissions we're going to use
204
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
205
-     *
206
-     * @var array
207
-     */
208
-    protected $_cap_contexts_to_cap_action_map = array(
209
-        self::caps_read       => 'read',
210
-        self::caps_read_admin => 'read',
211
-        self::caps_edit       => 'edit',
212
-        self::caps_delete     => 'delete',
213
-    );
214
-
215
-    /**
216
-     * Timezone
217
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
218
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
219
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
220
-     * EE_Datetime_Field data type will have access to it.
221
-     *
222
-     * @var string
223
-     */
224
-    protected $_timezone;
225
-
226
-
227
-    /**
228
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
229
-     * multisite.
230
-     *
231
-     * @var int
232
-     */
233
-    protected static $_model_query_blog_id;
234
-
235
-    /**
236
-     * A copy of _fields, except the array keys are the model names pointed to by
237
-     * the field
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cache_foreign_key_to_fields = array();
242
-
243
-    /**
244
-     * Cached list of all the fields on the model, indexed by their name
245
-     *
246
-     * @var EE_Model_Field_Base[]
247
-     */
248
-    private $_cached_fields = null;
249
-
250
-    /**
251
-     * Cached list of all the fields on the model, except those that are
252
-     * marked as only pertinent to the database
253
-     *
254
-     * @var EE_Model_Field_Base[]
255
-     */
256
-    private $_cached_fields_non_db_only = null;
257
-
258
-    /**
259
-     * A cached reference to the primary key for quick lookup
260
-     *
261
-     * @var EE_Model_Field_Base
262
-     */
263
-    private $_primary_key_field = null;
264
-
265
-    /**
266
-     * Flag indicating whether this model has a primary key or not
267
-     *
268
-     * @var boolean
269
-     */
270
-    protected $_has_primary_key_field = null;
271
-
272
-    /**
273
-     * Whether or not this model is based off a table in WP core only (CPTs should set
274
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
275
-     *
276
-     * @var boolean
277
-     */
278
-    protected $_wp_core_model = false;
279
-
280
-    /**
281
-     *    List of valid operators that can be used for querying.
282
-     * The keys are all operators we'll accept, the values are the real SQL
283
-     * operators used
284
-     *
285
-     * @var array
286
-     */
287
-    protected $_valid_operators = array(
288
-        '='           => '=',
289
-        '<='          => '<=',
290
-        '<'           => '<',
291
-        '>='          => '>=',
292
-        '>'           => '>',
293
-        '!='          => '!=',
294
-        'LIKE'        => 'LIKE',
295
-        'like'        => 'LIKE',
296
-        'NOT_LIKE'    => 'NOT LIKE',
297
-        'not_like'    => 'NOT LIKE',
298
-        'NOT LIKE'    => 'NOT LIKE',
299
-        'not like'    => 'NOT LIKE',
300
-        'IN'          => 'IN',
301
-        'in'          => 'IN',
302
-        'NOT_IN'      => 'NOT IN',
303
-        'not_in'      => 'NOT IN',
304
-        'NOT IN'      => 'NOT IN',
305
-        'not in'      => 'NOT IN',
306
-        'between'     => 'BETWEEN',
307
-        'BETWEEN'     => 'BETWEEN',
308
-        'IS_NOT_NULL' => 'IS NOT NULL',
309
-        'is_not_null' => 'IS NOT NULL',
310
-        'IS NOT NULL' => 'IS NOT NULL',
311
-        'is not null' => 'IS NOT NULL',
312
-        'IS_NULL'     => 'IS NULL',
313
-        'is_null'     => 'IS NULL',
314
-        'IS NULL'     => 'IS NULL',
315
-        'is null'     => 'IS NULL',
316
-        'REGEXP'      => 'REGEXP',
317
-        'regexp'      => 'REGEXP',
318
-        'NOT_REGEXP'  => 'NOT REGEXP',
319
-        'not_regexp'  => 'NOT REGEXP',
320
-        'NOT REGEXP'  => 'NOT REGEXP',
321
-        'not regexp'  => 'NOT REGEXP',
322
-    );
323
-
324
-    /**
325
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
326
-     *
327
-     * @var array
328
-     */
329
-    protected $_in_style_operators = array('IN', 'NOT IN');
330
-
331
-    /**
332
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
333
-     * '12-31-2012'"
334
-     *
335
-     * @var array
336
-     */
337
-    protected $_between_style_operators = array('BETWEEN');
338
-
339
-    /**
340
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
341
-     * on a join table.
342
-     *
343
-     * @var array
344
-     */
345
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
346
-
347
-    /**
348
-     * Allowed values for $query_params['order'] for ordering in queries
349
-     *
350
-     * @var array
351
-     */
352
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
353
-
354
-    /**
355
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
356
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
357
-     *
358
-     * @var array
359
-     */
360
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
361
-
362
-    /**
363
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
364
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
365
-     *
366
-     * @var array
367
-     */
368
-    private $_allowed_query_params = array(
369
-        0,
370
-        'limit',
371
-        'order_by',
372
-        'group_by',
373
-        'having',
374
-        'force_join',
375
-        'order',
376
-        'on_join_limit',
377
-        'default_where_conditions',
378
-        'caps',
379
-    );
380
-
381
-    /**
382
-     * All the data types that can be used in $wpdb->prepare statements.
383
-     *
384
-     * @var array
385
-     */
386
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
387
-
388
-    /**
389
-     *    EE_Registry Object
390
-     *
391
-     * @var    object
392
-     * @access    protected
393
-     */
394
-    protected $EE = null;
395
-
396
-
397
-    /**
398
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
399
-     *
400
-     * @var int
401
-     */
402
-    protected $_show_next_x_db_queries = 0;
403
-
404
-    /**
405
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
406
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
407
-     *
408
-     * @var array
409
-     */
410
-    protected $_custom_selections = array();
411
-
412
-    /**
413
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
414
-     * caches every model object we've fetched from the DB on this request
415
-     *
416
-     * @var array
417
-     */
418
-    protected $_entity_map;
419
-
420
-    /**
421
-     * constant used to show EEM_Base has not yet verified the db on this http request
422
-     */
423
-    const db_verified_none = 0;
424
-
425
-    /**
426
-     * constant used to show EEM_Base has verified the EE core db on this http request,
427
-     * but not the addons' dbs
428
-     */
429
-    const db_verified_core = 1;
430
-
431
-    /**
432
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
433
-     * the EE core db too)
434
-     */
435
-    const db_verified_addons = 2;
436
-
437
-    /**
438
-     * indicates whether an EEM_Base child has already re-verified the DB
439
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
440
-     * looking like EEM_Base::db_verified_*
441
-     *
442
-     * @var int - 0 = none, 1 = core, 2 = addons
443
-     */
444
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
445
-
446
-    /**
447
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
448
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
449
-     *        registrations for non-trashed tickets for non-trashed datetimes)
450
-     */
451
-    const default_where_conditions_all = 'all';
452
-
453
-    /**
454
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
455
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
456
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
457
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
458
-     *        models which share tables with other models, this can return data for the wrong model.
459
-     */
460
-    const default_where_conditions_this_only = 'this_model_only';
461
-
462
-    /**
463
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
464
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
465
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
466
-     */
467
-    const default_where_conditions_others_only = 'other_models_only';
468
-
469
-    /**
470
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
471
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
472
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
473
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
474
-     *        (regardless of whether those events and venues are trashed)
475
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
476
-     *        events.
477
-     */
478
-    const default_where_conditions_minimum_all = 'minimum';
479
-
480
-    /**
481
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
482
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
483
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
484
-     *        not)
485
-     */
486
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
487
-
488
-    /**
489
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
490
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
491
-     *        it's possible it will return table entries for other models. You should use
492
-     *        EEM_Base::default_where_conditions_minimum_all instead.
493
-     */
494
-    const default_where_conditions_none = 'none';
495
-
496
-
497
-
498
-    /**
499
-     * About all child constructors:
500
-     * they should define the _tables, _fields and _model_relations arrays.
501
-     * Should ALWAYS be called after child constructor.
502
-     * In order to make the child constructors to be as simple as possible, this parent constructor
503
-     * finalizes constructing all the object's attributes.
504
-     * Generally, rather than requiring a child to code
505
-     * $this->_tables = array(
506
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
507
-     *        ...);
508
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
509
-     * each EE_Table has a function to set the table's alias after the constructor, using
510
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
511
-     * do something similar.
512
-     *
513
-     * @param null $timezone
514
-     * @throws \EE_Error
515
-     */
516
-    protected function __construct($timezone = null)
517
-    {
518
-        // check that the model has not been loaded too soon
519
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
520
-            throw new EE_Error (
521
-                sprintf(
522
-                    __('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.',
523
-                        'event_espresso'),
524
-                    get_class($this)
525
-                )
526
-            );
527
-        }
528
-        /**
529
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
530
-         */
531
-        if (empty(EEM_Base::$_model_query_blog_id)) {
532
-            EEM_Base::set_model_query_blog_id();
533
-        }
534
-        /**
535
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
536
-         * just use EE_Register_Model_Extension
537
-         *
538
-         * @var EE_Table_Base[] $_tables
539
-         */
540
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
541
-        foreach ($this->_tables as $table_alias => $table_obj) {
542
-            /** @var $table_obj EE_Table_Base */
543
-            $table_obj->_construct_finalize_with_alias($table_alias);
544
-            if ($table_obj instanceof EE_Secondary_Table) {
545
-                /** @var $table_obj EE_Secondary_Table */
546
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
547
-            }
548
-        }
549
-        /**
550
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
551
-         * EE_Register_Model_Extension
552
-         *
553
-         * @param EE_Model_Field_Base[] $_fields
554
-         */
555
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
556
-        $this->_invalidate_field_caches();
557
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
558
-            if (! array_key_exists($table_alias, $this->_tables)) {
559
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
560
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
561
-            }
562
-            foreach ($fields_for_table as $field_name => $field_obj) {
563
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
564
-                //primary key field base has a slightly different _construct_finalize
565
-                /** @var $field_obj EE_Model_Field_Base */
566
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
567
-            }
568
-        }
569
-        // everything is related to Extra_Meta
570
-        if (get_class($this) !== 'EEM_Extra_Meta') {
571
-            //make extra meta related to everything, but don't block deleting things just
572
-            //because they have related extra meta info. For now just orphan those extra meta
573
-            //in the future we should automatically delete them
574
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
575
-        }
576
-        //and change logs
577
-        if (get_class($this) !== 'EEM_Change_Log') {
578
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
579
-        }
580
-        /**
581
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
582
-         * EE_Register_Model_Extension
583
-         *
584
-         * @param EE_Model_Relation_Base[] $_model_relations
585
-         */
586
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
587
-            $this->_model_relations);
588
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
589
-            /** @var $relation_obj EE_Model_Relation_Base */
590
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
591
-        }
592
-        foreach ($this->_indexes as $index_name => $index_obj) {
593
-            /** @var $index_obj EE_Index */
594
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
595
-        }
596
-        $this->set_timezone($timezone);
597
-        //finalize default where condition strategy, or set default
598
-        if (! $this->_default_where_conditions_strategy) {
599
-            //nothing was set during child constructor, so set default
600
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
601
-        }
602
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
603
-        if (! $this->_minimum_where_conditions_strategy) {
604
-            //nothing was set during child constructor, so set default
605
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
606
-        }
607
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
608
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
609
-        //to indicate to NOT set it, set it to the logical default
610
-        if ($this->_caps_slug === null) {
611
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
612
-        }
613
-        //initialize the standard cap restriction generators if none were specified by the child constructor
614
-        if ($this->_cap_restriction_generators !== false) {
615
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
616
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
617
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
618
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
619
-                        new EE_Restriction_Generator_Protected(),
620
-                        $cap_context,
621
-                        $this
622
-                    );
623
-                }
624
-            }
625
-        }
626
-        //if there are cap restriction generators, use them to make the default cap restrictions
627
-        if ($this->_cap_restriction_generators !== false) {
628
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
629
-                if (! $generator_object) {
630
-                    continue;
631
-                }
632
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
633
-                    throw new EE_Error(
634
-                        sprintf(
635
-                            __('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.',
636
-                                'event_espresso'),
637
-                            $context,
638
-                            $this->get_this_model_name()
639
-                        )
640
-                    );
641
-                }
642
-                $action = $this->cap_action_for_context($context);
643
-                if (! $generator_object->construction_finalized()) {
644
-                    $generator_object->_construct_finalize($this, $action);
645
-                }
646
-            }
647
-        }
648
-        do_action('AHEE__' . get_class($this) . '__construct__end');
649
-    }
650
-
651
-
652
-
653
-    /**
654
-     * Generates the cap restrictions for the given context, or if they were
655
-     * already generated just gets what's cached
656
-     *
657
-     * @param string $context one of EEM_Base::valid_cap_contexts()
658
-     * @return EE_Default_Where_Conditions[]
659
-     */
660
-    protected function _generate_cap_restrictions($context)
661
-    {
662
-        if (isset($this->_cap_restriction_generators[$context])
663
-            && $this->_cap_restriction_generators[$context]
664
-               instanceof
665
-               EE_Restriction_Generator_Base
666
-        ) {
667
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
668
-        } else {
669
-            return array();
670
-        }
671
-    }
672
-
673
-
674
-
675
-    /**
676
-     * Used to set the $_model_query_blog_id static property.
677
-     *
678
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
679
-     *                      value for get_current_blog_id() will be used.
680
-     */
681
-    public static function set_model_query_blog_id($blog_id = 0)
682
-    {
683
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
684
-    }
685
-
686
-
687
-
688
-    /**
689
-     * Returns whatever is set as the internal $model_query_blog_id.
690
-     *
691
-     * @return int
692
-     */
693
-    public static function get_model_query_blog_id()
694
-    {
695
-        return EEM_Base::$_model_query_blog_id;
696
-    }
697
-
698
-
699
-
700
-    /**
701
-     *        This function is a singleton method used to instantiate the Espresso_model object
702
-     *
703
-     * @access public
704
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
705
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
706
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
707
-     *                         timezone in the 'timezone_string' wp option)
708
-     * @return static (as in the concrete child class)
709
-     */
710
-    public static function instance($timezone = null)
711
-    {
712
-        // check if instance of Espresso_model already exists
713
-        if (! static::$_instance instanceof static) {
714
-            // instantiate Espresso_model
715
-            static::$_instance = new static($timezone);
716
-        }
717
-        //we might have a timezone set, let set_timezone decide what to do with it
718
-        static::$_instance->set_timezone($timezone);
719
-        // Espresso_model object
720
-        return static::$_instance;
721
-    }
722
-
723
-
724
-
725
-    /**
726
-     * resets the model and returns it
727
-     *
728
-     * @param null | string $timezone
729
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
730
-     * all its properties reset; if it wasn't instantiated, returns null)
731
-     */
732
-    public static function reset($timezone = null)
733
-    {
734
-        if (static::$_instance instanceof EEM_Base) {
735
-            //let's try to NOT swap out the current instance for a new one
736
-            //because if someone has a reference to it, we can't remove their reference
737
-            //so it's best to keep using the same reference, but change the original object
738
-            //reset all its properties to their original values as defined in the class
739
-            $r = new ReflectionClass(get_class(static::$_instance));
740
-            $static_properties = $r->getStaticProperties();
741
-            foreach ($r->getDefaultProperties() as $property => $value) {
742
-                //don't set instance to null like it was originally,
743
-                //but it's static anyways, and we're ignoring static properties (for now at least)
744
-                if (! isset($static_properties[$property])) {
745
-                    static::$_instance->{$property} = $value;
746
-                }
747
-            }
748
-            //and then directly call its constructor again, like we would if we
749
-            //were creating a new one
750
-            static::$_instance->__construct($timezone);
751
-            return self::instance();
752
-        }
753
-        return null;
754
-    }
755
-
756
-
757
-
758
-    /**
759
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
760
-     *
761
-     * @param  boolean $translated return localized strings or JUST the array.
762
-     * @return array
763
-     * @throws \EE_Error
764
-     */
765
-    public function status_array($translated = false)
766
-    {
767
-        if (! array_key_exists('Status', $this->_model_relations)) {
768
-            return array();
769
-        }
770
-        $model_name = $this->get_this_model_name();
771
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
772
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
773
-        $status_array = array();
774
-        foreach ($stati as $status) {
775
-            $status_array[$status->ID()] = $status->get('STS_code');
776
-        }
777
-        return $translated
778
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
779
-            : $status_array;
780
-    }
781
-
782
-
783
-
784
-    /**
785
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
786
-     *
787
-     * @param array $query_params             {
788
-     * @var array $0 (where) array {
789
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
790
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
791
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
792
-     *                                        conditions based on related models (and even
793
-     *                                        models-related-to-related-models) prepend the model's name onto the field
794
-     *                                        name. Eg,
795
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
796
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
797
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
798
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
799
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
800
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
801
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
802
-     *                                        to Venues (even when each of those models actually consisted of two
803
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
804
-     *                                        just having
805
-     *                                        "Venue.VNU_ID", you could have
806
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
807
-     *                                        events are related to Registrations, which are related to Attendees). You
808
-     *                                        can take it even further with
809
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
810
-     *                                        (from the default of '='), change the value to an numerically-indexed
811
-     *                                        array, where the first item in the list is the operator. eg: array(
812
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
813
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
814
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
815
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
816
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
817
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
818
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
819
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
820
-     *                                        the value is a field, simply provide a third array item (true) to the
821
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
822
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
823
-     *                                        Note: you can also use related model field names like you would any other
824
-     *                                        field name. eg:
825
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
826
-     *                                        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__>' =>
827
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
828
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
829
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
830
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
831
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
832
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
833
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
834
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
835
-     *                                        "stick" until you specify an AND. eg
836
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
837
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
838
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
839
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
840
-     *                                        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 >>
841
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
842
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
843
-     *                                        too, eg:
844
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
845
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
846
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
847
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
848
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
849
-     *                                        the OFFSET, the 2nd is the LIMIT
850
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
851
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
852
-     *                                        following format array('on_join_limit'
853
-     *                                        => array( 'table_alias', array(1,2) ) ).
854
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
855
-     *                                        values are either 'ASC' or 'DESC'.
856
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
857
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
858
-     *                                        DESC..." respectively. Like the
859
-     *                                        'where' conditions, these fields can be on related models. Eg
860
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
861
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
862
-     *                                        Attendee, Price, Datetime, etc.)
863
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
864
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
865
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
866
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
867
-     *                                        order by the primary key. Eg,
868
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
869
-     *                                        //(will join with the Datetime model's table(s) and order by its field
870
-     *                                        DTT_EVT_start) or
871
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
872
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
873
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
874
-     *                                        'group_by'=>'VNU_ID', or
875
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
876
-     *                                        if no
877
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
878
-     *                                        model's primary key (or combined primary keys). This avoids some
879
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
880
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
881
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
882
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
883
-     *                                        results)
884
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
885
-     *                                        array where values are models to be joined in the query.Eg
886
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
887
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
888
-     *                                        probably only want to do this in hopes of increasing efficiency, as
889
-     *                                        related models which belongs to the current model
890
-     *                                        (ie, the current model has a foreign key to them, like how Registration
891
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
892
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
893
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
894
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
895
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
896
-     *                                        default where conditions set it to 'other_models_only'. If you only want
897
-     *                                        this model's default where conditions added to the query, use
898
-     *                                        'this_model_only'. If you want to use all default where conditions
899
-     *                                        (default), set to 'all'.
900
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
901
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
902
-     *                                        everything? Or should we only show the current user items they should be
903
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
904
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
905
-     *                                        }
906
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
907
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
908
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
909
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
910
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
911
-     *                                        array( array(
912
-     *                                        'OR'=>array(
913
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
914
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
915
-     *                                        )
916
-     *                                        ),
917
-     *                                        'limit'=>10,
918
-     *                                        'group_by'=>'TXN_ID'
919
-     *                                        ));
920
-     *                                        get all the answers to the question titled "shirt size" for event with id
921
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
922
-     *                                        'Question.QST_display_text'=>'shirt size',
923
-     *                                        'Registration.Event.EVT_ID'=>12
924
-     *                                        ),
925
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
926
-     *                                        ));
927
-     * @throws \EE_Error
928
-     */
929
-    public function get_all($query_params = array())
930
-    {
931
-        if (isset($query_params['limit'])
932
-            && ! isset($query_params['group_by'])
933
-        ) {
934
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
935
-        }
936
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
937
-    }
938
-
939
-
940
-
941
-    /**
942
-     * Modifies the query parameters so we only get back model objects
943
-     * that "belong" to the current user
944
-     *
945
-     * @param array $query_params @see EEM_Base::get_all()
946
-     * @return array like EEM_Base::get_all
947
-     */
948
-    public function alter_query_params_to_only_include_mine($query_params = array())
949
-    {
950
-        $wp_user_field_name = $this->wp_user_field_name();
951
-        if ($wp_user_field_name) {
952
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
953
-        }
954
-        return $query_params;
955
-    }
956
-
957
-
958
-
959
-    /**
960
-     * Returns the name of the field's name that points to the WP_User table
961
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
962
-     * foreign key to the WP_User table)
963
-     *
964
-     * @return string|boolean string on success, boolean false when there is no
965
-     * foreign key to the WP_User table
966
-     */
967
-    public function wp_user_field_name()
968
-    {
969
-        try {
970
-            if (! empty($this->_model_chain_to_wp_user)) {
971
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
972
-                $last_model_name = end($models_to_follow_to_wp_users);
973
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
974
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
975
-            } else {
976
-                $model_with_fk_to_wp_users = $this;
977
-                $model_chain_to_wp_user = '';
978
-            }
979
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
980
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
981
-        } catch (EE_Error $e) {
982
-            return false;
983
-        }
984
-    }
985
-
986
-
987
-
988
-    /**
989
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
990
-     * (or transiently-related model) has a foreign key to the wp_users table;
991
-     * useful for finding if model objects of this type are 'owned' by the current user.
992
-     * This is an empty string when the foreign key is on this model and when it isn't,
993
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
994
-     * (or transiently-related model)
995
-     *
996
-     * @return string
997
-     */
998
-    public function model_chain_to_wp_user()
999
-    {
1000
-        return $this->_model_chain_to_wp_user;
1001
-    }
1002
-
1003
-
1004
-
1005
-    /**
1006
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1007
-     * like how registrations don't have a foreign key to wp_users, but the
1008
-     * events they are for are), or is unrelated to wp users.
1009
-     * generally available
1010
-     *
1011
-     * @return boolean
1012
-     */
1013
-    public function is_owned()
1014
-    {
1015
-        if ($this->model_chain_to_wp_user()) {
1016
-            return true;
1017
-        } else {
1018
-            try {
1019
-                $this->get_foreign_key_to('WP_User');
1020
-                return true;
1021
-            } catch (EE_Error $e) {
1022
-                return false;
1023
-            }
1024
-        }
1025
-    }
1026
-
1027
-
1028
-
1029
-    /**
1030
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1031
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1032
-     * the model)
1033
-     *
1034
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1035
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1037
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1038
-     *                                  override this and set the select to "*", or a specific column name, like
1039
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
-     *                                  the aliases used to refer to this selection, and values are to be
1042
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
-     * @throws \EE_Error
1046
-     */
1047
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1048
-    {
1049
-        // remember the custom selections, if any, and type cast as array
1050
-        // (unless $columns_to_select is an object, then just set as an empty array)
1051
-        // Note: (array) 'some string' === array( 'some string' )
1052
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1053
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1054
-        $select_expressions = $columns_to_select !== null
1055
-            ? $this->_construct_select_from_input($columns_to_select)
1056
-            : $this->_construct_default_select_sql($model_query_info);
1057
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1058
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1059
-    }
1060
-
1061
-
1062
-
1063
-    /**
1064
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1065
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1066
-     * take care of joins, field preparation etc.
1067
-     *
1068
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1069
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1070
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1071
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1072
-     *                                  override this and set the select to "*", or a specific column name, like
1073
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1074
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1075
-     *                                  the aliases used to refer to this selection, and values are to be
1076
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1077
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1078
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1079
-     * @throws \EE_Error
1080
-     */
1081
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1082
-    {
1083
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1084
-    }
1085
-
1086
-
1087
-
1088
-    /**
1089
-     * For creating a custom select statement
1090
-     *
1091
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1092
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1093
-     *                                 SQL, and 1=>is the datatype
1094
-     * @throws EE_Error
1095
-     * @return string
1096
-     */
1097
-    private function _construct_select_from_input($columns_to_select)
1098
-    {
1099
-        if (is_array($columns_to_select)) {
1100
-            $select_sql_array = array();
1101
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1102
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1103
-                    throw new EE_Error(
1104
-                        sprintf(
1105
-                            __(
1106
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1107
-                                "event_espresso"
1108
-                            ),
1109
-                            $selection_and_datatype,
1110
-                            $alias
1111
-                        )
1112
-                    );
1113
-                }
1114
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1115
-                    throw new EE_Error(
1116
-                        sprintf(
1117
-                            __(
1118
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1119
-                                "event_espresso"
1120
-                            ),
1121
-                            $selection_and_datatype[1],
1122
-                            $selection_and_datatype[0],
1123
-                            $alias,
1124
-                            implode(",", $this->_valid_wpdb_data_types)
1125
-                        )
1126
-                    );
1127
-                }
1128
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1129
-            }
1130
-            $columns_to_select_string = implode(", ", $select_sql_array);
1131
-        } else {
1132
-            $columns_to_select_string = $columns_to_select;
1133
-        }
1134
-        return $columns_to_select_string;
1135
-    }
1136
-
1137
-
1138
-
1139
-    /**
1140
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1141
-     *
1142
-     * @return string
1143
-     * @throws \EE_Error
1144
-     */
1145
-    public function primary_key_name()
1146
-    {
1147
-        return $this->get_primary_key_field()->get_name();
1148
-    }
1149
-
1150
-
1151
-
1152
-    /**
1153
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1154
-     * If there is no primary key on this model, $id is treated as primary key string
1155
-     *
1156
-     * @param mixed $id int or string, depending on the type of the model's primary key
1157
-     * @return EE_Base_Class
1158
-     */
1159
-    public function get_one_by_ID($id)
1160
-    {
1161
-        if ($this->get_from_entity_map($id)) {
1162
-            return $this->get_from_entity_map($id);
1163
-        }
1164
-        return $this->get_one(
1165
-            $this->alter_query_params_to_restrict_by_ID(
1166
-                $id,
1167
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1168
-            )
1169
-        );
1170
-    }
1171
-
1172
-
1173
-
1174
-    /**
1175
-     * Alters query parameters to only get items with this ID are returned.
1176
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1177
-     * or could just be a simple primary key ID
1178
-     *
1179
-     * @param int   $id
1180
-     * @param array $query_params
1181
-     * @return array of normal query params, @see EEM_Base::get_all
1182
-     * @throws \EE_Error
1183
-     */
1184
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1185
-    {
1186
-        if (! isset($query_params[0])) {
1187
-            $query_params[0] = array();
1188
-        }
1189
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1190
-        if ($conditions_from_id === null) {
1191
-            $query_params[0][$this->primary_key_name()] = $id;
1192
-        } else {
1193
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1194
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1195
-        }
1196
-        return $query_params;
1197
-    }
1198
-
1199
-
1200
-
1201
-    /**
1202
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1203
-     * array. If no item is found, null is returned.
1204
-     *
1205
-     * @param array $query_params like EEM_Base's $query_params variable.
1206
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1207
-     * @throws \EE_Error
1208
-     */
1209
-    public function get_one($query_params = array())
1210
-    {
1211
-        if (! is_array($query_params)) {
1212
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1213
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1214
-                    gettype($query_params)), '4.6.0');
1215
-            $query_params = array();
1216
-        }
1217
-        $query_params['limit'] = 1;
1218
-        $items = $this->get_all($query_params);
1219
-        if (empty($items)) {
1220
-            return null;
1221
-        } else {
1222
-            return array_shift($items);
1223
-        }
1224
-    }
1225
-
1226
-
1227
-
1228
-    /**
1229
-     * Returns the next x number of items in sequence from the given value as
1230
-     * found in the database matching the given query conditions.
1231
-     *
1232
-     * @param mixed $current_field_value    Value used for the reference point.
1233
-     * @param null  $field_to_order_by      What field is used for the
1234
-     *                                      reference point.
1235
-     * @param int   $limit                  How many to return.
1236
-     * @param array $query_params           Extra conditions on the query.
1237
-     * @param null  $columns_to_select      If left null, then an array of
1238
-     *                                      EE_Base_Class objects is returned,
1239
-     *                                      otherwise you can indicate just the
1240
-     *                                      columns you want returned.
1241
-     * @return EE_Base_Class[]|array
1242
-     * @throws \EE_Error
1243
-     */
1244
-    public function next_x(
1245
-        $current_field_value,
1246
-        $field_to_order_by = null,
1247
-        $limit = 1,
1248
-        $query_params = array(),
1249
-        $columns_to_select = null
1250
-    ) {
1251
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1252
-            $columns_to_select);
1253
-    }
1254
-
1255
-
1256
-
1257
-    /**
1258
-     * Returns the previous x number of items in sequence from the given value
1259
-     * as found in the database matching the given query conditions.
1260
-     *
1261
-     * @param mixed $current_field_value    Value used for the reference point.
1262
-     * @param null  $field_to_order_by      What field is used for the
1263
-     *                                      reference point.
1264
-     * @param int   $limit                  How many to return.
1265
-     * @param array $query_params           Extra conditions on the query.
1266
-     * @param null  $columns_to_select      If left null, then an array of
1267
-     *                                      EE_Base_Class objects is returned,
1268
-     *                                      otherwise you can indicate just the
1269
-     *                                      columns you want returned.
1270
-     * @return EE_Base_Class[]|array
1271
-     * @throws \EE_Error
1272
-     */
1273
-    public function previous_x(
1274
-        $current_field_value,
1275
-        $field_to_order_by = null,
1276
-        $limit = 1,
1277
-        $query_params = array(),
1278
-        $columns_to_select = null
1279
-    ) {
1280
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1281
-            $columns_to_select);
1282
-    }
1283
-
1284
-
1285
-
1286
-    /**
1287
-     * Returns the next item in sequence from the given value as found in the
1288
-     * database matching the given query conditions.
1289
-     *
1290
-     * @param mixed $current_field_value    Value used for the reference point.
1291
-     * @param null  $field_to_order_by      What field is used for the
1292
-     *                                      reference point.
1293
-     * @param array $query_params           Extra conditions on the query.
1294
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1295
-     *                                      object is returned, otherwise you
1296
-     *                                      can indicate just the columns you
1297
-     *                                      want and a single array indexed by
1298
-     *                                      the columns will be returned.
1299
-     * @return EE_Base_Class|null|array()
1300
-     * @throws \EE_Error
1301
-     */
1302
-    public function next(
1303
-        $current_field_value,
1304
-        $field_to_order_by = null,
1305
-        $query_params = array(),
1306
-        $columns_to_select = null
1307
-    ) {
1308
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1309
-            $columns_to_select);
1310
-        return empty($results) ? null : reset($results);
1311
-    }
1312
-
1313
-
1314
-
1315
-    /**
1316
-     * Returns the previous item in sequence from the given value as found in
1317
-     * the database matching the given query conditions.
1318
-     *
1319
-     * @param mixed $current_field_value    Value used for the reference point.
1320
-     * @param null  $field_to_order_by      What field is used for the
1321
-     *                                      reference point.
1322
-     * @param array $query_params           Extra conditions on the query.
1323
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1324
-     *                                      object is returned, otherwise you
1325
-     *                                      can indicate just the columns you
1326
-     *                                      want and a single array indexed by
1327
-     *                                      the columns will be returned.
1328
-     * @return EE_Base_Class|null|array()
1329
-     * @throws EE_Error
1330
-     */
1331
-    public function previous(
1332
-        $current_field_value,
1333
-        $field_to_order_by = null,
1334
-        $query_params = array(),
1335
-        $columns_to_select = null
1336
-    ) {
1337
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1338
-            $columns_to_select);
1339
-        return empty($results) ? null : reset($results);
1340
-    }
1341
-
1342
-
1343
-
1344
-    /**
1345
-     * Returns the a consecutive number of items in sequence from the given
1346
-     * value as found in the database matching the given query conditions.
1347
-     *
1348
-     * @param mixed  $current_field_value   Value used for the reference point.
1349
-     * @param string $operand               What operand is used for the sequence.
1350
-     * @param string $field_to_order_by     What field is used for the reference point.
1351
-     * @param int    $limit                 How many to return.
1352
-     * @param array  $query_params          Extra conditions on the query.
1353
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1354
-     *                                      otherwise you can indicate just the columns you want returned.
1355
-     * @return EE_Base_Class[]|array
1356
-     * @throws EE_Error
1357
-     */
1358
-    protected function _get_consecutive(
1359
-        $current_field_value,
1360
-        $operand = '>',
1361
-        $field_to_order_by = null,
1362
-        $limit = 1,
1363
-        $query_params = array(),
1364
-        $columns_to_select = null
1365
-    ) {
1366
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1367
-        if (empty($field_to_order_by)) {
1368
-            if ($this->has_primary_key_field()) {
1369
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1370
-            } else {
1371
-                if (WP_DEBUG) {
1372
-                    throw new EE_Error(__('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).',
1373
-                        'event_espresso'));
1374
-                }
1375
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1376
-                return array();
1377
-            }
1378
-        }
1379
-        if (! is_array($query_params)) {
1380
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1381
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1382
-                    gettype($query_params)), '4.6.0');
1383
-            $query_params = array();
1384
-        }
1385
-        //let's add the where query param for consecutive look up.
1386
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1387
-        $query_params['limit'] = $limit;
1388
-        //set direction
1389
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1390
-        $query_params['order_by'] = $operand === '>'
1391
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1392
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1393
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1394
-        if (empty($columns_to_select)) {
1395
-            return $this->get_all($query_params);
1396
-        } else {
1397
-            //getting just the fields
1398
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1399
-        }
1400
-    }
1401
-
1402
-
1403
-
1404
-    /**
1405
-     * This sets the _timezone property after model object has been instantiated.
1406
-     *
1407
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1408
-     */
1409
-    public function set_timezone($timezone)
1410
-    {
1411
-        if ($timezone !== null) {
1412
-            $this->_timezone = $timezone;
1413
-        }
1414
-        //note we need to loop through relations and set the timezone on those objects as well.
1415
-        foreach ($this->_model_relations as $relation) {
1416
-            $relation->set_timezone($timezone);
1417
-        }
1418
-        //and finally we do the same for any datetime fields
1419
-        foreach ($this->_fields as $field) {
1420
-            if ($field instanceof EE_Datetime_Field) {
1421
-                $field->set_timezone($timezone);
1422
-            }
1423
-        }
1424
-    }
1425
-
1426
-
1427
-
1428
-    /**
1429
-     * This just returns whatever is set for the current timezone.
1430
-     *
1431
-     * @access public
1432
-     * @return string
1433
-     */
1434
-    public function get_timezone()
1435
-    {
1436
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1437
-        if (empty($this->_timezone)) {
1438
-            foreach ($this->_fields as $field) {
1439
-                if ($field instanceof EE_Datetime_Field) {
1440
-                    $this->set_timezone($field->get_timezone());
1441
-                    break;
1442
-                }
1443
-            }
1444
-        }
1445
-        //if timezone STILL empty then return the default timezone for the site.
1446
-        if (empty($this->_timezone)) {
1447
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1448
-        }
1449
-        return $this->_timezone;
1450
-    }
1451
-
1452
-
1453
-
1454
-    /**
1455
-     * This returns the date formats set for the given field name and also ensures that
1456
-     * $this->_timezone property is set correctly.
1457
-     *
1458
-     * @since 4.6.x
1459
-     * @param string $field_name The name of the field the formats are being retrieved for.
1460
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1461
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1462
-     * @return array formats in an array with the date format first, and the time format last.
1463
-     */
1464
-    public function get_formats_for($field_name, $pretty = false)
1465
-    {
1466
-        $field_settings = $this->field_settings_for($field_name);
1467
-        //if not a valid EE_Datetime_Field then throw error
1468
-        if (! $field_settings instanceof EE_Datetime_Field) {
1469
-            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.',
1470
-                'event_espresso'), $field_name));
1471
-        }
1472
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1473
-        //the field.
1474
-        $this->_timezone = $field_settings->get_timezone();
1475
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1476
-    }
1477
-
1478
-
1479
-
1480
-    /**
1481
-     * This returns the current time in a format setup for a query on this model.
1482
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1483
-     * it will return:
1484
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1485
-     *  NOW
1486
-     *  - or a unix timestamp (equivalent to time())
1487
-     *
1488
-     * @since 4.6.x
1489
-     * @param string $field_name       The field the current time is needed for.
1490
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1491
-     *                                 formatted string matching the set format for the field in the set timezone will
1492
-     *                                 be returned.
1493
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1494
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1495
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1496
-     *                                 exception is triggered.
1497
-     */
1498
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1499
-    {
1500
-        $formats = $this->get_formats_for($field_name);
1501
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1502
-        if ($timestamp) {
1503
-            return $DateTime->format('U');
1504
-        }
1505
-        //not returning timestamp, so return formatted string in timezone.
1506
-        switch ($what) {
1507
-            case 'time' :
1508
-                return $DateTime->format($formats[1]);
1509
-                break;
1510
-            case 'date' :
1511
-                return $DateTime->format($formats[0]);
1512
-                break;
1513
-            default :
1514
-                return $DateTime->format(implode(' ', $formats));
1515
-                break;
1516
-        }
1517
-    }
1518
-
1519
-
1520
-
1521
-    /**
1522
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1523
-     * for the model are.  Returns a DateTime object.
1524
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1525
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1526
-     * ignored.
1527
-     *
1528
-     * @param string $field_name      The field being setup.
1529
-     * @param string $timestring      The date time string being used.
1530
-     * @param string $incoming_format The format for the time string.
1531
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1532
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1533
-     *                                format is
1534
-     *                                'U', this is ignored.
1535
-     * @return DateTime
1536
-     * @throws \EE_Error
1537
-     */
1538
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1539
-    {
1540
-        //just using this to ensure the timezone is set correctly internally
1541
-        $this->get_formats_for($field_name);
1542
-        //load EEH_DTT_Helper
1543
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1544
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1545
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1546
-    }
1547
-
1548
-
1549
-
1550
-    /**
1551
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1552
-     *
1553
-     * @return EE_Table_Base[]
1554
-     */
1555
-    public function get_tables()
1556
-    {
1557
-        return $this->_tables;
1558
-    }
1559
-
1560
-
1561
-
1562
-    /**
1563
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1564
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1565
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1566
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1567
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1568
-     * model object with EVT_ID = 1
1569
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1570
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1571
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1572
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1573
-     * are not specified)
1574
-     *
1575
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1576
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1577
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1578
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1579
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1580
-     *                                         ID=34, we'd use this method as follows:
1581
-     *                                         EEM_Transaction::instance()->update(
1582
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1583
-     *                                         array(array('TXN_ID'=>34)));
1584
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1585
-     *                                         in client code into what's expected to be stored on each field. Eg,
1586
-     *                                         consider updating Question's QST_admin_label field is of type
1587
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1588
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1589
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1590
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1591
-     *                                         TRUE, it is assumed that you've already called
1592
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1593
-     *                                         malicious javascript. However, if
1594
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1595
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1596
-     *                                         and every other field, before insertion. We provide this parameter
1597
-     *                                         because model objects perform their prepare_for_set function on all
1598
-     *                                         their values, and so don't need to be called again (and in many cases,
1599
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1600
-     *                                         prepare_for_set method...)
1601
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1602
-     *                                         in this model's entity map according to $fields_n_values that match
1603
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1604
-     *                                         by setting this to FALSE, but be aware that model objects being used
1605
-     *                                         could get out-of-sync with the database
1606
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1607
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1608
-     *                                         bad)
1609
-     * @throws \EE_Error
1610
-     */
1611
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1612
-    {
1613
-        if (! is_array($query_params)) {
1614
-            EE_Error::doing_it_wrong('EEM_Base::update',
1615
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1616
-                    gettype($query_params)), '4.6.0');
1617
-            $query_params = array();
1618
-        }
1619
-        /**
1620
-         * Action called before a model update call has been made.
1621
-         *
1622
-         * @param EEM_Base $model
1623
-         * @param array    $fields_n_values the updated fields and their new values
1624
-         * @param array    $query_params    @see EEM_Base::get_all()
1625
-         */
1626
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1627
-        /**
1628
-         * Filters the fields about to be updated given the query parameters. You can provide the
1629
-         * $query_params to $this->get_all() to find exactly which records will be updated
1630
-         *
1631
-         * @param array    $fields_n_values fields and their new values
1632
-         * @param EEM_Base $model           the model being queried
1633
-         * @param array    $query_params    see EEM_Base::get_all()
1634
-         */
1635
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1636
-            $query_params);
1637
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1638
-        //to do that, for each table, verify that it's PK isn't null.
1639
-        $tables = $this->get_tables();
1640
-        //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
1641
-        //NOTE: we should make this code more efficient by NOT querying twice
1642
-        //before the real update, but that needs to first go through ALPHA testing
1643
-        //as it's dangerous. says Mike August 8 2014
1644
-        //we want to make sure the default_where strategy is ignored
1645
-        $this->_ignore_where_strategy = true;
1646
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1647
-        foreach ($wpdb_select_results as $wpdb_result) {
1648
-            // type cast stdClass as array
1649
-            $wpdb_result = (array)$wpdb_result;
1650
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1651
-            if ($this->has_primary_key_field()) {
1652
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1653
-            } else {
1654
-                //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)
1655
-                $main_table_pk_value = null;
1656
-            }
1657
-            //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
1658
-            //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
1659
-            if (count($tables) > 1) {
1660
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1661
-                //in that table, and so we'll want to insert one
1662
-                foreach ($tables as $table_obj) {
1663
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1664
-                    //if there is no private key for this table on the results, it means there's no entry
1665
-                    //in this table, right? so insert a row in the current table, using any fields available
1666
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1667
-                           && $wpdb_result[$this_table_pk_column])
1668
-                    ) {
1669
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1670
-                            $main_table_pk_value);
1671
-                        //if we died here, report the error
1672
-                        if (! $success) {
1673
-                            return false;
1674
-                        }
1675
-                    }
1676
-                }
1677
-            }
1678
-            //				//and now check that if we have cached any models by that ID on the model, that
1679
-            //				//they also get updated properly
1680
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1681
-            //				if( $model_object ){
1682
-            //					foreach( $fields_n_values as $field => $value ){
1683
-            //						$model_object->set($field, $value);
1684
-            //let's make sure default_where strategy is followed now
1685
-            $this->_ignore_where_strategy = false;
1686
-        }
1687
-        //if we want to keep model objects in sync, AND
1688
-        //if this wasn't called from a model object (to update itself)
1689
-        //then we want to make sure we keep all the existing
1690
-        //model objects in sync with the db
1691
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1692
-            if ($this->has_primary_key_field()) {
1693
-                $model_objs_affected_ids = $this->get_col($query_params);
1694
-            } else {
1695
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1696
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1697
-                $model_objs_affected_ids = array();
1698
-                foreach ($models_affected_key_columns as $row) {
1699
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1700
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1701
-                }
1702
-            }
1703
-            if (! $model_objs_affected_ids) {
1704
-                //wait wait wait- if nothing was affected let's stop here
1705
-                return 0;
1706
-            }
1707
-            foreach ($model_objs_affected_ids as $id) {
1708
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1709
-                if ($model_obj_in_entity_map) {
1710
-                    foreach ($fields_n_values as $field => $new_value) {
1711
-                        $model_obj_in_entity_map->set($field, $new_value);
1712
-                    }
1713
-                }
1714
-            }
1715
-            //if there is a primary key on this model, we can now do a slight optimization
1716
-            if ($this->has_primary_key_field()) {
1717
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1718
-                $query_params = array(
1719
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1720
-                    'limit'                    => count($model_objs_affected_ids),
1721
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1722
-                );
1723
-            }
1724
-        }
1725
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1726
-        $SQL = "UPDATE "
1727
-               . $model_query_info->get_full_join_sql()
1728
-               . " SET "
1729
-               . $this->_construct_update_sql($fields_n_values)
1730
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1731
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1732
-        /**
1733
-         * Action called after a model update call has been made.
1734
-         *
1735
-         * @param EEM_Base $model
1736
-         * @param array    $fields_n_values the updated fields and their new values
1737
-         * @param array    $query_params    @see EEM_Base::get_all()
1738
-         * @param int      $rows_affected
1739
-         */
1740
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1741
-        return $rows_affected;//how many supposedly got updated
1742
-    }
1743
-
1744
-
1745
-
1746
-    /**
1747
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1748
-     * are teh values of the field specified (or by default the primary key field)
1749
-     * that matched the query params. Note that you should pass the name of the
1750
-     * model FIELD, not the database table's column name.
1751
-     *
1752
-     * @param array  $query_params @see EEM_Base::get_all()
1753
-     * @param string $field_to_select
1754
-     * @return array just like $wpdb->get_col()
1755
-     * @throws \EE_Error
1756
-     */
1757
-    public function get_col($query_params = array(), $field_to_select = null)
1758
-    {
1759
-        if ($field_to_select) {
1760
-            $field = $this->field_settings_for($field_to_select);
1761
-        } elseif ($this->has_primary_key_field()) {
1762
-            $field = $this->get_primary_key_field();
1763
-        } else {
1764
-            //no primary key, just grab the first column
1765
-            $field = reset($this->field_settings());
1766
-        }
1767
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1768
-        $select_expressions = $field->get_qualified_column();
1769
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1770
-        return $this->_do_wpdb_query('get_col', array($SQL));
1771
-    }
1772
-
1773
-
1774
-
1775
-    /**
1776
-     * Returns a single column value for a single row from the database
1777
-     *
1778
-     * @param array  $query_params    @see EEM_Base::get_all()
1779
-     * @param string $field_to_select @see EEM_Base::get_col()
1780
-     * @return string
1781
-     * @throws \EE_Error
1782
-     */
1783
-    public function get_var($query_params = array(), $field_to_select = null)
1784
-    {
1785
-        $query_params['limit'] = 1;
1786
-        $col = $this->get_col($query_params, $field_to_select);
1787
-        if (! empty($col)) {
1788
-            return reset($col);
1789
-        } else {
1790
-            return null;
1791
-        }
1792
-    }
1793
-
1794
-
1795
-
1796
-    /**
1797
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1798
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1799
-     * injection, but currently no further filtering is done
1800
-     *
1801
-     * @global      $wpdb
1802
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1803
-     *                               be updated to in the DB
1804
-     * @return string of SQL
1805
-     * @throws \EE_Error
1806
-     */
1807
-    public function _construct_update_sql($fields_n_values)
1808
-    {
1809
-        /** @type WPDB $wpdb */
1810
-        global $wpdb;
1811
-        $cols_n_values = array();
1812
-        foreach ($fields_n_values as $field_name => $value) {
1813
-            $field_obj = $this->field_settings_for($field_name);
1814
-            //if the value is NULL, we want to assign the value to that.
1815
-            //wpdb->prepare doesn't really handle that properly
1816
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1817
-            $value_sql = $prepared_value === null ? 'NULL'
1818
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1819
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1820
-        }
1821
-        return implode(",", $cols_n_values);
1822
-    }
1823
-
1824
-
1825
-
1826
-    /**
1827
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1828
-     * Performs a HARD delete, meaning the database row should always be removed,
1829
-     * not just have a flag field on it switched
1830
-     * Wrapper for EEM_Base::delete_permanently()
1831
-     *
1832
-     * @param mixed $id
1833
-     * @return boolean whether the row got deleted or not
1834
-     * @throws \EE_Error
1835
-     */
1836
-    public function delete_permanently_by_ID($id)
1837
-    {
1838
-        return $this->delete_permanently(
1839
-            array(
1840
-                array($this->get_primary_key_field()->get_name() => $id),
1841
-                'limit' => 1,
1842
-            )
1843
-        );
1844
-    }
1845
-
1846
-
1847
-
1848
-    /**
1849
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1850
-     * Wrapper for EEM_Base::delete()
1851
-     *
1852
-     * @param mixed $id
1853
-     * @return boolean whether the row got deleted or not
1854
-     * @throws \EE_Error
1855
-     */
1856
-    public function delete_by_ID($id)
1857
-    {
1858
-        return $this->delete(
1859
-            array(
1860
-                array($this->get_primary_key_field()->get_name() => $id),
1861
-                'limit' => 1,
1862
-            )
1863
-        );
1864
-    }
1865
-
1866
-
1867
-
1868
-    /**
1869
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1870
-     * meaning if the model has a field that indicates its been "trashed" or
1871
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1872
-     *
1873
-     * @see EEM_Base::delete_permanently
1874
-     * @param array   $query_params
1875
-     * @param boolean $allow_blocking
1876
-     * @return int how many rows got deleted
1877
-     * @throws \EE_Error
1878
-     */
1879
-    public function delete($query_params, $allow_blocking = true)
1880
-    {
1881
-        return $this->delete_permanently($query_params, $allow_blocking);
1882
-    }
1883
-
1884
-
1885
-
1886
-    /**
1887
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1888
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1889
-     * as archived, not actually deleted
1890
-     *
1891
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1892
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1893
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1894
-     *                                deletes regardless of other objects which may depend on it. Its generally
1895
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1896
-     *                                DB
1897
-     * @return int how many rows got deleted
1898
-     * @throws \EE_Error
1899
-     */
1900
-    public function delete_permanently($query_params, $allow_blocking = true)
1901
-    {
1902
-        /**
1903
-         * Action called just before performing a real deletion query. You can use the
1904
-         * model and its $query_params to find exactly which items will be deleted
1905
-         *
1906
-         * @param EEM_Base $model
1907
-         * @param array    $query_params   @see EEM_Base::get_all()
1908
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1909
-         *                                 to block (prevent) this deletion
1910
-         */
1911
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1912
-        //some MySQL databases may be running safe mode, which may restrict
1913
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1914
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1915
-        //to delete them
1916
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1917
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1918
-        if ($deletion_where) {
1919
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1920
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1921
-            $table_aliases = array_keys($this->_tables);
1922
-            $SQL = "DELETE "
1923
-                   . implode(", ", $table_aliases)
1924
-                   . " FROM "
1925
-                   . $model_query_info->get_full_join_sql()
1926
-                   . " WHERE "
1927
-                   . $deletion_where;
1928
-            //		/echo "delete sql:$SQL";
1929
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1930
-        } else {
1931
-            $rows_deleted = 0;
1932
-        }
1933
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1934
-        if ($this->has_primary_key_field()) {
1935
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1936
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1937
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1938
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1939
-                }
1940
-            }
1941
-        }
1942
-        /**
1943
-         * Action called just after performing a real deletion query. Although at this point the
1944
-         * items should have been deleted
1945
-         *
1946
-         * @param EEM_Base $model
1947
-         * @param array    $query_params @see EEM_Base::get_all()
1948
-         * @param int      $rows_deleted
1949
-         */
1950
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1951
-        return $rows_deleted;//how many supposedly got deleted
1952
-    }
1953
-
1954
-
1955
-
1956
-    /**
1957
-     * Checks all the relations that throw error messages when there are blocking related objects
1958
-     * for related model objects. If there are any related model objects on those relations,
1959
-     * adds an EE_Error, and return true
1960
-     *
1961
-     * @param EE_Base_Class|int $this_model_obj_or_id
1962
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1963
-     *                                                 should be ignored when determining whether there are related
1964
-     *                                                 model objects which block this model object's deletion. Useful
1965
-     *                                                 if you know A is related to B and are considering deleting A,
1966
-     *                                                 but want to see if A has any other objects blocking its deletion
1967
-     *                                                 before removing the relation between A and B
1968
-     * @return boolean
1969
-     * @throws \EE_Error
1970
-     */
1971
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1972
-    {
1973
-        //first, if $ignore_this_model_obj was supplied, get its model
1974
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1975
-            $ignored_model = $ignore_this_model_obj->get_model();
1976
-        } else {
1977
-            $ignored_model = null;
1978
-        }
1979
-        //now check all the relations of $this_model_obj_or_id and see if there
1980
-        //are any related model objects blocking it?
1981
-        $is_blocked = false;
1982
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
1983
-            if ($relation_obj->block_delete_if_related_models_exist()) {
1984
-                //if $ignore_this_model_obj was supplied, then for the query
1985
-                //on that model needs to be told to ignore $ignore_this_model_obj
1986
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1987
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1988
-                        array(
1989
-                            $ignored_model->get_primary_key_field()->get_name() => array(
1990
-                                '!=',
1991
-                                $ignore_this_model_obj->ID(),
1992
-                            ),
1993
-                        ),
1994
-                    ));
1995
-                } else {
1996
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1997
-                }
1998
-                if ($related_model_objects) {
1999
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2000
-                    $is_blocked = true;
2001
-                }
2002
-            }
2003
-        }
2004
-        return $is_blocked;
2005
-    }
2006
-
2007
-
2008
-
2009
-    /**
2010
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2011
-     * well.
2012
-     *
2013
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2014
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2015
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
2016
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
2017
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
2018
-     *                                      easily corrupt your DB
2019
-     * @throws EE_Error
2020
-     * @return string    everything that comes after the WHERE statement.
2021
-     */
2022
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2023
-    {
2024
-        if ($this->has_primary_key_field()) {
2025
-            $primary_table = $this->_get_main_table();
2026
-            $other_tables = $this->_get_other_tables();
2027
-            $deletes = $query = array();
2028
-            foreach ($objects_for_deletion as $delete_object) {
2029
-                //before we mark this object for deletion,
2030
-                //make sure there's no related objects blocking its deletion (if we're checking)
2031
-                if (
2032
-                    $allow_blocking
2033
-                    && $this->delete_is_blocked_by_related_models(
2034
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
2035
-                    )
2036
-                ) {
2037
-                    continue;
2038
-                }
2039
-                //primary table deletes
2040
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2041
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2042
-                }
2043
-                //other tables
2044
-                if (! empty($other_tables)) {
2045
-                    foreach ($other_tables as $ot) {
2046
-                        //first check if we've got the foreign key column here.
2047
-                        if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2048
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2049
-                        }
2050
-                        // wait! it's entirely possible that we'll have a the primary key
2051
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
2052
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2053
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2054
-                        }
2055
-                        // finally, it is possible that the fk for this table is found
2056
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
2057
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2058
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2059
-                        }
2060
-                    }
2061
-                }
2062
-            }
2063
-            //we should have deletes now, so let's just go through and setup the where statement
2064
-            foreach ($deletes as $column => $values) {
2065
-                //make sure we have unique $values;
2066
-                $values = array_unique($values);
2067
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2068
-            }
2069
-            return ! empty($query) ? implode(' AND ', $query) : '';
2070
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2071
-            $ways_to_identify_a_row = array();
2072
-            $fields = $this->get_combined_primary_key_fields();
2073
-            //note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2074
-            foreach ($objects_for_deletion as $delete_object) {
2075
-                $values_for_each_cpk_for_a_row = array();
2076
-                foreach ($fields as $cpk_field) {
2077
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2078
-                        $values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2079
-                                                           . "="
2080
-                                                           . $delete_object[$cpk_field->get_qualified_column()];
2081
-                    }
2082
-                }
2083
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2084
-            }
2085
-            return implode(" OR ", $ways_to_identify_a_row);
2086
-        } else {
2087
-            //so there's no primary key and no combined key...
2088
-            //sorry, can't help you
2089
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2090
-                "event_espresso"), get_class($this)));
2091
-        }
2092
-    }
2093
-
2094
-
2095
-
2096
-    /**
2097
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2098
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2099
-     * column
2100
-     *
2101
-     * @param array  $query_params   like EEM_Base::get_all's
2102
-     * @param string $field_to_count field on model to count by (not column name)
2103
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2104
-     *                               that by the setting $distinct to TRUE;
2105
-     * @return int
2106
-     * @throws \EE_Error
2107
-     */
2108
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2109
-    {
2110
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2111
-        if ($field_to_count) {
2112
-            $field_obj = $this->field_settings_for($field_to_count);
2113
-            $column_to_count = $field_obj->get_qualified_column();
2114
-        } elseif ($this->has_primary_key_field()) {
2115
-            $pk_field_obj = $this->get_primary_key_field();
2116
-            $column_to_count = $pk_field_obj->get_qualified_column();
2117
-        } else {
2118
-            //there's no primary key
2119
-            //if we're counting distinct items, and there's no primary key,
2120
-            //we need to list out the columns for distinction;
2121
-            //otherwise we can just use star
2122
-            if ($distinct) {
2123
-                $columns_to_use = array();
2124
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2125
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2126
-                }
2127
-                $column_to_count = implode(',', $columns_to_use);
2128
-            } else {
2129
-                $column_to_count = '*';
2130
-            }
2131
-        }
2132
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2133
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2134
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2135
-    }
2136
-
2137
-
2138
-
2139
-    /**
2140
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2141
-     *
2142
-     * @param array  $query_params like EEM_Base::get_all
2143
-     * @param string $field_to_sum name of field (array key in $_fields array)
2144
-     * @return float
2145
-     * @throws \EE_Error
2146
-     */
2147
-    public function sum($query_params, $field_to_sum = null)
2148
-    {
2149
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2150
-        if ($field_to_sum) {
2151
-            $field_obj = $this->field_settings_for($field_to_sum);
2152
-        } else {
2153
-            $field_obj = $this->get_primary_key_field();
2154
-        }
2155
-        $column_to_count = $field_obj->get_qualified_column();
2156
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2157
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2158
-        $data_type = $field_obj->get_wpdb_data_type();
2159
-        if ($data_type === '%d' || $data_type === '%s') {
2160
-            return (float)$return_value;
2161
-        } else {//must be %f
2162
-            return (float)$return_value;
2163
-        }
2164
-    }
2165
-
2166
-
2167
-
2168
-    /**
2169
-     * Just calls the specified method on $wpdb with the given arguments
2170
-     * Consolidates a little extra error handling code
2171
-     *
2172
-     * @param string $wpdb_method
2173
-     * @param array  $arguments_to_provide
2174
-     * @throws EE_Error
2175
-     * @global wpdb  $wpdb
2176
-     * @return mixed
2177
-     */
2178
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2179
-    {
2180
-        //if we're in maintenance mode level 2, DON'T run any queries
2181
-        //because level 2 indicates the database needs updating and
2182
-        //is probably out of sync with the code
2183
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2184
-            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.",
2185
-                "event_espresso")));
2186
-        }
2187
-        /** @type WPDB $wpdb */
2188
-        global $wpdb;
2189
-        if (! method_exists($wpdb, $wpdb_method)) {
2190
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2191
-                'event_espresso'), $wpdb_method));
2192
-        }
2193
-        if (WP_DEBUG) {
2194
-            $old_show_errors_value = $wpdb->show_errors;
2195
-            $wpdb->show_errors(false);
2196
-        }
2197
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2198
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2199
-        if (WP_DEBUG) {
2200
-            $wpdb->show_errors($old_show_errors_value);
2201
-            if (! empty($wpdb->last_error)) {
2202
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2203
-            } elseif ($result === false) {
2204
-                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"',
2205
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2206
-            }
2207
-        } elseif ($result === false) {
2208
-            EE_Error::add_error(
2209
-                sprintf(
2210
-                    __('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"',
2211
-                        'event_espresso'),
2212
-                    $wpdb_method,
2213
-                    var_export($arguments_to_provide, true),
2214
-                    $wpdb->last_error
2215
-                ),
2216
-                __FILE__,
2217
-                __FUNCTION__,
2218
-                __LINE__
2219
-            );
2220
-        }
2221
-        return $result;
2222
-    }
2223
-
2224
-
2225
-
2226
-    /**
2227
-     * Attempts to run the indicated WPDB method with the provided arguments,
2228
-     * and if there's an error tries to verify the DB is correct. Uses
2229
-     * the static property EEM_Base::$_db_verification_level to determine whether
2230
-     * we should try to fix the EE core db, the addons, or just give up
2231
-     *
2232
-     * @param string $wpdb_method
2233
-     * @param array  $arguments_to_provide
2234
-     * @return mixed
2235
-     */
2236
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2237
-    {
2238
-        /** @type WPDB $wpdb */
2239
-        global $wpdb;
2240
-        $wpdb->last_error = null;
2241
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2242
-        // was there an error running the query? but we don't care on new activations
2243
-        // (we're going to setup the DB anyway on new activations)
2244
-        if (($result === false || ! empty($wpdb->last_error))
2245
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2246
-        ) {
2247
-            switch (EEM_Base::$_db_verification_level) {
2248
-                case EEM_Base::db_verified_none :
2249
-                    // let's double-check core's DB
2250
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2251
-                    break;
2252
-                case EEM_Base::db_verified_core :
2253
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2254
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2255
-                    break;
2256
-                case EEM_Base::db_verified_addons :
2257
-                    // ummmm... you in trouble
2258
-                    return $result;
2259
-                    break;
2260
-            }
2261
-            if (! empty($error_message)) {
2262
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2263
-                trigger_error($error_message);
2264
-            }
2265
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2266
-        }
2267
-        return $result;
2268
-    }
2269
-
2270
-
2271
-
2272
-    /**
2273
-     * Verifies the EE core database is up-to-date and records that we've done it on
2274
-     * EEM_Base::$_db_verification_level
2275
-     *
2276
-     * @param string $wpdb_method
2277
-     * @param array  $arguments_to_provide
2278
-     * @return string
2279
-     */
2280
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2281
-    {
2282
-        /** @type WPDB $wpdb */
2283
-        global $wpdb;
2284
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2285
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2286
-        $error_message = sprintf(
2287
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2288
-                'event_espresso'),
2289
-            $wpdb->last_error,
2290
-            $wpdb_method,
2291
-            wp_json_encode($arguments_to_provide)
2292
-        );
2293
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2294
-        return $error_message;
2295
-    }
2296
-
2297
-
2298
-
2299
-    /**
2300
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2301
-     * EEM_Base::$_db_verification_level
2302
-     *
2303
-     * @param $wpdb_method
2304
-     * @param $arguments_to_provide
2305
-     * @return string
2306
-     */
2307
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2308
-    {
2309
-        /** @type WPDB $wpdb */
2310
-        global $wpdb;
2311
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2312
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2313
-        $error_message = sprintf(
2314
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2315
-                'event_espresso'),
2316
-            $wpdb->last_error,
2317
-            $wpdb_method,
2318
-            wp_json_encode($arguments_to_provide)
2319
-        );
2320
-        EE_System::instance()->initialize_addons();
2321
-        return $error_message;
2322
-    }
2323
-
2324
-
2325
-
2326
-    /**
2327
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2328
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2329
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2330
-     * ..."
2331
-     *
2332
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2333
-     * @return string
2334
-     */
2335
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2336
-    {
2337
-        return " FROM " . $model_query_info->get_full_join_sql() .
2338
-               $model_query_info->get_where_sql() .
2339
-               $model_query_info->get_group_by_sql() .
2340
-               $model_query_info->get_having_sql() .
2341
-               $model_query_info->get_order_by_sql() .
2342
-               $model_query_info->get_limit_sql();
2343
-    }
2344
-
2345
-
2346
-
2347
-    /**
2348
-     * Set to easily debug the next X queries ran from this model.
2349
-     *
2350
-     * @param int $count
2351
-     */
2352
-    public function show_next_x_db_queries($count = 1)
2353
-    {
2354
-        $this->_show_next_x_db_queries = $count;
2355
-    }
2356
-
2357
-
2358
-
2359
-    /**
2360
-     * @param $sql_query
2361
-     */
2362
-    public function show_db_query_if_previously_requested($sql_query)
2363
-    {
2364
-        if ($this->_show_next_x_db_queries > 0) {
2365
-            echo $sql_query;
2366
-            $this->_show_next_x_db_queries--;
2367
-        }
2368
-    }
2369
-
2370
-
2371
-
2372
-    /**
2373
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2374
-     * There are the 3 cases:
2375
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2376
-     * $otherModelObject has no ID, it is first saved.
2377
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2378
-     * has no ID, it is first saved.
2379
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2380
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2381
-     * join table
2382
-     *
2383
-     * @param        EE_Base_Class                     /int $thisModelObject
2384
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2385
-     * @param string $relationName                     , key in EEM_Base::_relations
2386
-     *                                                 an attendee to a group, you also want to specify which role they
2387
-     *                                                 will have in that group. So you would use this parameter to
2388
-     *                                                 specify array('role-column-name'=>'role-id')
2389
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2390
-     *                                                 to for relation to methods that allow you to further specify
2391
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2392
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2393
-     *                                                 because these will be inserted in any new rows created as well.
2394
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2395
-     * @throws \EE_Error
2396
-     */
2397
-    public function add_relationship_to(
2398
-        $id_or_obj,
2399
-        $other_model_id_or_obj,
2400
-        $relationName,
2401
-        $extra_join_model_fields_n_values = array()
2402
-    ) {
2403
-        $relation_obj = $this->related_settings_for($relationName);
2404
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2405
-    }
2406
-
2407
-
2408
-
2409
-    /**
2410
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2411
-     * There are the 3 cases:
2412
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2413
-     * error
2414
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2415
-     * an error
2416
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2417
-     *
2418
-     * @param        EE_Base_Class /int $id_or_obj
2419
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2420
-     * @param string $relationName key in EEM_Base::_relations
2421
-     * @return boolean of success
2422
-     * @throws \EE_Error
2423
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2424
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2425
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2426
-     *                             because these will be inserted in any new rows created as well.
2427
-     */
2428
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2429
-    {
2430
-        $relation_obj = $this->related_settings_for($relationName);
2431
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2432
-    }
2433
-
2434
-
2435
-
2436
-    /**
2437
-     * @param mixed           $id_or_obj
2438
-     * @param string          $relationName
2439
-     * @param array           $where_query_params
2440
-     * @param EE_Base_Class[] objects to which relations were removed
2441
-     * @return \EE_Base_Class[]
2442
-     * @throws \EE_Error
2443
-     */
2444
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2445
-    {
2446
-        $relation_obj = $this->related_settings_for($relationName);
2447
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2448
-    }
2449
-
2450
-
2451
-
2452
-    /**
2453
-     * Gets all the related items of the specified $model_name, using $query_params.
2454
-     * Note: by default, we remove the "default query params"
2455
-     * because we want to get even deleted items etc.
2456
-     *
2457
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2458
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2459
-     * @param array  $query_params like EEM_Base::get_all
2460
-     * @return EE_Base_Class[]
2461
-     * @throws \EE_Error
2462
-     */
2463
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2464
-    {
2465
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2466
-        $relation_settings = $this->related_settings_for($model_name);
2467
-        return $relation_settings->get_all_related($model_obj, $query_params);
2468
-    }
2469
-
2470
-
2471
-
2472
-    /**
2473
-     * Deletes all the model objects across the relation indicated by $model_name
2474
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2475
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2476
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2477
-     *
2478
-     * @param EE_Base_Class|int|string $id_or_obj
2479
-     * @param string                   $model_name
2480
-     * @param array                    $query_params
2481
-     * @return int how many deleted
2482
-     * @throws \EE_Error
2483
-     */
2484
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2485
-    {
2486
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2487
-        $relation_settings = $this->related_settings_for($model_name);
2488
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2489
-    }
2490
-
2491
-
2492
-
2493
-    /**
2494
-     * Hard deletes all the model objects across the relation indicated by $model_name
2495
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2496
-     * the model objects can't be hard deleted because of blocking related model objects,
2497
-     * just does a soft-delete on them instead.
2498
-     *
2499
-     * @param EE_Base_Class|int|string $id_or_obj
2500
-     * @param string                   $model_name
2501
-     * @param array                    $query_params
2502
-     * @return int how many deleted
2503
-     * @throws \EE_Error
2504
-     */
2505
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2506
-    {
2507
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2508
-        $relation_settings = $this->related_settings_for($model_name);
2509
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2510
-    }
2511
-
2512
-
2513
-
2514
-    /**
2515
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2516
-     * unless otherwise specified in the $query_params
2517
-     *
2518
-     * @param        int             /EE_Base_Class $id_or_obj
2519
-     * @param string $model_name     like 'Event', or 'Registration'
2520
-     * @param array  $query_params   like EEM_Base::get_all's
2521
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2522
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2523
-     *                               that by the setting $distinct to TRUE;
2524
-     * @return int
2525
-     * @throws \EE_Error
2526
-     */
2527
-    public function count_related(
2528
-        $id_or_obj,
2529
-        $model_name,
2530
-        $query_params = array(),
2531
-        $field_to_count = null,
2532
-        $distinct = false
2533
-    ) {
2534
-        $related_model = $this->get_related_model_obj($model_name);
2535
-        //we're just going to use the query params on the related model's normal get_all query,
2536
-        //except add a condition to say to match the current mod
2537
-        if (! isset($query_params['default_where_conditions'])) {
2538
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2539
-        }
2540
-        $this_model_name = $this->get_this_model_name();
2541
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2542
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2543
-        return $related_model->count($query_params, $field_to_count, $distinct);
2544
-    }
2545
-
2546
-
2547
-
2548
-    /**
2549
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2550
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2551
-     *
2552
-     * @param        int           /EE_Base_Class $id_or_obj
2553
-     * @param string $model_name   like 'Event', or 'Registration'
2554
-     * @param array  $query_params like EEM_Base::get_all's
2555
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2556
-     * @return float
2557
-     * @throws \EE_Error
2558
-     */
2559
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2560
-    {
2561
-        $related_model = $this->get_related_model_obj($model_name);
2562
-        if (! is_array($query_params)) {
2563
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2564
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2565
-                    gettype($query_params)), '4.6.0');
2566
-            $query_params = array();
2567
-        }
2568
-        //we're just going to use the query params on the related model's normal get_all query,
2569
-        //except add a condition to say to match the current mod
2570
-        if (! isset($query_params['default_where_conditions'])) {
2571
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2572
-        }
2573
-        $this_model_name = $this->get_this_model_name();
2574
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2575
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2576
-        return $related_model->sum($query_params, $field_to_sum);
2577
-    }
2578
-
2579
-
2580
-
2581
-    /**
2582
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2583
-     * $modelObject
2584
-     *
2585
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2586
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2587
-     * @param array               $query_params     like EEM_Base::get_all's
2588
-     * @return EE_Base_Class
2589
-     * @throws \EE_Error
2590
-     */
2591
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2592
-    {
2593
-        $query_params['limit'] = 1;
2594
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2595
-        if ($results) {
2596
-            return array_shift($results);
2597
-        } else {
2598
-            return null;
2599
-        }
2600
-    }
2601
-
2602
-
2603
-
2604
-    /**
2605
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2606
-     *
2607
-     * @return string
2608
-     */
2609
-    public function get_this_model_name()
2610
-    {
2611
-        return str_replace("EEM_", "", get_class($this));
2612
-    }
2613
-
2614
-
2615
-
2616
-    /**
2617
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2618
-     *
2619
-     * @return EE_Any_Foreign_Model_Name_Field
2620
-     * @throws EE_Error
2621
-     */
2622
-    public function get_field_containing_related_model_name()
2623
-    {
2624
-        foreach ($this->field_settings(true) as $field) {
2625
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2626
-                $field_with_model_name = $field;
2627
-            }
2628
-        }
2629
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2630
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2631
-                $this->get_this_model_name()));
2632
-        }
2633
-        return $field_with_model_name;
2634
-    }
2635
-
2636
-
2637
-
2638
-    /**
2639
-     * Inserts a new entry into the database, for each table.
2640
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2641
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2642
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2643
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2644
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2645
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2646
-     *
2647
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2648
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2649
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2650
-     *                              of EEM_Base)
2651
-     * @return int new primary key on main table that got inserted
2652
-     * @throws EE_Error
2653
-     */
2654
-    public function insert($field_n_values)
2655
-    {
2656
-        /**
2657
-         * Filters the fields and their values before inserting an item using the models
2658
-         *
2659
-         * @param array    $fields_n_values keys are the fields and values are their new values
2660
-         * @param EEM_Base $model           the model used
2661
-         */
2662
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2663
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2664
-            $main_table = $this->_get_main_table();
2665
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2666
-            if ($new_id !== false) {
2667
-                foreach ($this->_get_other_tables() as $other_table) {
2668
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2669
-                }
2670
-            }
2671
-            /**
2672
-             * Done just after attempting to insert a new model object
2673
-             *
2674
-             * @param EEM_Base   $model           used
2675
-             * @param array      $fields_n_values fields and their values
2676
-             * @param int|string the              ID of the newly-inserted model object
2677
-             */
2678
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2679
-            return $new_id;
2680
-        } else {
2681
-            return false;
2682
-        }
2683
-    }
2684
-
2685
-
2686
-
2687
-    /**
2688
-     * Checks that the result would satisfy the unique indexes on this model
2689
-     *
2690
-     * @param array  $field_n_values
2691
-     * @param string $action
2692
-     * @return boolean
2693
-     * @throws \EE_Error
2694
-     */
2695
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2696
-    {
2697
-        foreach ($this->unique_indexes() as $index_name => $index) {
2698
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2699
-            if ($this->exists(array($uniqueness_where_params))) {
2700
-                EE_Error::add_error(
2701
-                    sprintf(
2702
-                        __(
2703
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2704
-                            "event_espresso"
2705
-                        ),
2706
-                        $action,
2707
-                        $this->_get_class_name(),
2708
-                        $index_name,
2709
-                        implode(",", $index->field_names()),
2710
-                        http_build_query($uniqueness_where_params)
2711
-                    ),
2712
-                    __FILE__,
2713
-                    __FUNCTION__,
2714
-                    __LINE__
2715
-                );
2716
-                return false;
2717
-            }
2718
-        }
2719
-        return true;
2720
-    }
2721
-
2722
-
2723
-
2724
-    /**
2725
-     * Checks the database for an item that conflicts (ie, if this item were
2726
-     * saved to the DB would break some uniqueness requirement, like a primary key
2727
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2728
-     * can be either an EE_Base_Class or an array of fields n values
2729
-     *
2730
-     * @param EE_Base_Class|array $obj_or_fields_array
2731
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2732
-     *                                                 when looking for conflicts
2733
-     *                                                 (ie, if false, we ignore the model object's primary key
2734
-     *                                                 when finding "conflicts". If true, it's also considered).
2735
-     *                                                 Only works for INT primary key,
2736
-     *                                                 STRING primary keys cannot be ignored
2737
-     * @throws EE_Error
2738
-     * @return EE_Base_Class|array
2739
-     */
2740
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2741
-    {
2742
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2743
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2744
-        } elseif (is_array($obj_or_fields_array)) {
2745
-            $fields_n_values = $obj_or_fields_array;
2746
-        } else {
2747
-            throw new EE_Error(
2748
-                sprintf(
2749
-                    __(
2750
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2751
-                        "event_espresso"
2752
-                    ),
2753
-                    get_class($this),
2754
-                    $obj_or_fields_array
2755
-                )
2756
-            );
2757
-        }
2758
-        $query_params = array();
2759
-        if ($this->has_primary_key_field()
2760
-            && ($include_primary_key
2761
-                || $this->get_primary_key_field()
2762
-                   instanceof
2763
-                   EE_Primary_Key_String_Field)
2764
-            && isset($fields_n_values[$this->primary_key_name()])
2765
-        ) {
2766
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2767
-        }
2768
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2769
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2770
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2771
-        }
2772
-        //if there is nothing to base this search on, then we shouldn't find anything
2773
-        if (empty($query_params)) {
2774
-            return array();
2775
-        } else {
2776
-            return $this->get_one($query_params);
2777
-        }
2778
-    }
2779
-
2780
-
2781
-
2782
-    /**
2783
-     * Like count, but is optimized and returns a boolean instead of an int
2784
-     *
2785
-     * @param array $query_params
2786
-     * @return boolean
2787
-     * @throws \EE_Error
2788
-     */
2789
-    public function exists($query_params)
2790
-    {
2791
-        $query_params['limit'] = 1;
2792
-        return $this->count($query_params) > 0;
2793
-    }
2794
-
2795
-
2796
-
2797
-    /**
2798
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2799
-     *
2800
-     * @param int|string $id
2801
-     * @return boolean
2802
-     * @throws \EE_Error
2803
-     */
2804
-    public function exists_by_ID($id)
2805
-    {
2806
-        return $this->exists(
2807
-            array(
2808
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2809
-                array(
2810
-                    $this->primary_key_name() => $id,
2811
-                ),
2812
-            )
2813
-        );
2814
-    }
2815
-
2816
-
2817
-
2818
-    /**
2819
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2820
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2821
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2822
-     * on the main table)
2823
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2824
-     * cases where we want to call it directly rather than via insert().
2825
-     *
2826
-     * @access   protected
2827
-     * @param EE_Table_Base $table
2828
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2829
-     *                                       float
2830
-     * @param int           $new_id          for now we assume only int keys
2831
-     * @throws EE_Error
2832
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2833
-     * @return int ID of new row inserted, or FALSE on failure
2834
-     */
2835
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2836
-    {
2837
-        global $wpdb;
2838
-        $insertion_col_n_values = array();
2839
-        $format_for_insertion = array();
2840
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2841
-        foreach ($fields_on_table as $field_name => $field_obj) {
2842
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2843
-            if ($field_obj->is_auto_increment()) {
2844
-                continue;
2845
-            }
2846
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2847
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2848
-            if ($prepared_value !== null) {
2849
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2850
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2851
-            }
2852
-        }
2853
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2854
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2855
-            //so add the fk to the main table as a column
2856
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2857
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2858
-        }
2859
-        //insert the new entry
2860
-        $result = $this->_do_wpdb_query('insert',
2861
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2862
-        if ($result === false) {
2863
-            return false;
2864
-        }
2865
-        //ok, now what do we return for the ID of the newly-inserted thing?
2866
-        if ($this->has_primary_key_field()) {
2867
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2868
-                return $wpdb->insert_id;
2869
-            } else {
2870
-                //it's not an auto-increment primary key, so
2871
-                //it must have been supplied
2872
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2873
-            }
2874
-        } else {
2875
-            //we can't return a  primary key because there is none. instead return
2876
-            //a unique string indicating this model
2877
-            return $this->get_index_primary_key_string($fields_n_values);
2878
-        }
2879
-    }
2880
-
2881
-
2882
-
2883
-    /**
2884
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2885
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2886
-     * and there is no default, we pass it along. WPDB will take care of it)
2887
-     *
2888
-     * @param EE_Model_Field_Base $field_obj
2889
-     * @param array               $fields_n_values
2890
-     * @return mixed string|int|float depending on what the table column will be expecting
2891
-     * @throws \EE_Error
2892
-     */
2893
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2894
-    {
2895
-        //if this field doesn't allow nullable, don't allow it
2896
-        if (! $field_obj->is_nullable()
2897
-            && (
2898
-                ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2899
-        ) {
2900
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2901
-        }
2902
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2903
-            : null;
2904
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2905
-    }
2906
-
2907
-
2908
-
2909
-    /**
2910
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2911
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2912
-     * the field's prepare_for_set() method.
2913
-     *
2914
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2915
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2916
-     *                                   top of file)
2917
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2918
-     *                                   $value is a custom selection
2919
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2920
-     */
2921
-    private function _prepare_value_for_use_in_db($value, $field)
2922
-    {
2923
-        if ($field && $field instanceof EE_Model_Field_Base) {
2924
-            switch ($this->_values_already_prepared_by_model_object) {
2925
-                /** @noinspection PhpMissingBreakStatementInspection */
2926
-                case self::not_prepared_by_model_object:
2927
-                    $value = $field->prepare_for_set($value);
2928
-                //purposefully left out "return"
2929
-                case self::prepared_by_model_object:
2930
-                    $value = $field->prepare_for_use_in_db($value);
2931
-                case self::prepared_for_use_in_db:
2932
-                    //leave the value alone
2933
-            }
2934
-            return $value;
2935
-        } else {
2936
-            return $value;
2937
-        }
2938
-    }
2939
-
2940
-
2941
-
2942
-    /**
2943
-     * Returns the main table on this model
2944
-     *
2945
-     * @return EE_Primary_Table
2946
-     * @throws EE_Error
2947
-     */
2948
-    protected function _get_main_table()
2949
-    {
2950
-        foreach ($this->_tables as $table) {
2951
-            if ($table instanceof EE_Primary_Table) {
2952
-                return $table;
2953
-            }
2954
-        }
2955
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2956
-            'event_espresso'), get_class($this)));
2957
-    }
2958
-
2959
-
2960
-
2961
-    /**
2962
-     * table
2963
-     * returns EE_Primary_Table table name
2964
-     *
2965
-     * @return string
2966
-     * @throws \EE_Error
2967
-     */
2968
-    public function table()
2969
-    {
2970
-        return $this->_get_main_table()->get_table_name();
2971
-    }
2972
-
2973
-
2974
-
2975
-    /**
2976
-     * table
2977
-     * returns first EE_Secondary_Table table name
2978
-     *
2979
-     * @return string
2980
-     */
2981
-    public function second_table()
2982
-    {
2983
-        // grab second table from tables array
2984
-        $second_table = end($this->_tables);
2985
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2986
-    }
2987
-
2988
-
2989
-
2990
-    /**
2991
-     * get_table_obj_by_alias
2992
-     * returns table name given it's alias
2993
-     *
2994
-     * @param string $table_alias
2995
-     * @return EE_Primary_Table | EE_Secondary_Table
2996
-     */
2997
-    public function get_table_obj_by_alias($table_alias = '')
2998
-    {
2999
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3000
-    }
3001
-
3002
-
3003
-
3004
-    /**
3005
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3006
-     *
3007
-     * @return EE_Secondary_Table[]
3008
-     */
3009
-    protected function _get_other_tables()
3010
-    {
3011
-        $other_tables = array();
3012
-        foreach ($this->_tables as $table_alias => $table) {
3013
-            if ($table instanceof EE_Secondary_Table) {
3014
-                $other_tables[$table_alias] = $table;
3015
-            }
3016
-        }
3017
-        return $other_tables;
3018
-    }
3019
-
3020
-
3021
-
3022
-    /**
3023
-     * Finds all the fields that correspond to the given table
3024
-     *
3025
-     * @param string $table_alias , array key in EEM_Base::_tables
3026
-     * @return EE_Model_Field_Base[]
3027
-     */
3028
-    public function _get_fields_for_table($table_alias)
3029
-    {
3030
-        return $this->_fields[$table_alias];
3031
-    }
3032
-
3033
-
3034
-
3035
-    /**
3036
-     * Recurses through all the where parameters, and finds all the related models we'll need
3037
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3038
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3039
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3040
-     * related Registration, Transaction, and Payment models.
3041
-     *
3042
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3043
-     * @return EE_Model_Query_Info_Carrier
3044
-     * @throws \EE_Error
3045
-     */
3046
-    public function _extract_related_models_from_query($query_params)
3047
-    {
3048
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3049
-        if (array_key_exists(0, $query_params)) {
3050
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3051
-        }
3052
-        if (array_key_exists('group_by', $query_params)) {
3053
-            if (is_array($query_params['group_by'])) {
3054
-                $this->_extract_related_models_from_sub_params_array_values(
3055
-                    $query_params['group_by'],
3056
-                    $query_info_carrier,
3057
-                    'group_by'
3058
-                );
3059
-            } elseif (! empty ($query_params['group_by'])) {
3060
-                $this->_extract_related_model_info_from_query_param(
3061
-                    $query_params['group_by'],
3062
-                    $query_info_carrier,
3063
-                    'group_by'
3064
-                );
3065
-            }
3066
-        }
3067
-        if (array_key_exists('having', $query_params)) {
3068
-            $this->_extract_related_models_from_sub_params_array_keys(
3069
-                $query_params[0],
3070
-                $query_info_carrier,
3071
-                'having'
3072
-            );
3073
-        }
3074
-        if (array_key_exists('order_by', $query_params)) {
3075
-            if (is_array($query_params['order_by'])) {
3076
-                $this->_extract_related_models_from_sub_params_array_keys(
3077
-                    $query_params['order_by'],
3078
-                    $query_info_carrier,
3079
-                    'order_by'
3080
-                );
3081
-            } elseif (! empty($query_params['order_by'])) {
3082
-                $this->_extract_related_model_info_from_query_param(
3083
-                    $query_params['order_by'],
3084
-                    $query_info_carrier,
3085
-                    'order_by'
3086
-                );
3087
-            }
3088
-        }
3089
-        if (array_key_exists('force_join', $query_params)) {
3090
-            $this->_extract_related_models_from_sub_params_array_values(
3091
-                $query_params['force_join'],
3092
-                $query_info_carrier,
3093
-                'force_join'
3094
-            );
3095
-        }
3096
-        return $query_info_carrier;
3097
-    }
3098
-
3099
-
3100
-
3101
-    /**
3102
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3103
-     *
3104
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3105
-     *                                                      $query_params['having']
3106
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3107
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3108
-     * @throws EE_Error
3109
-     * @return \EE_Model_Query_Info_Carrier
3110
-     */
3111
-    private function _extract_related_models_from_sub_params_array_keys(
3112
-        $sub_query_params,
3113
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3114
-        $query_param_type
3115
-    ) {
3116
-        if (! empty($sub_query_params)) {
3117
-            $sub_query_params = (array)$sub_query_params;
3118
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3119
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3120
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3121
-                    $query_param_type);
3122
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3123
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3124
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3125
-                //of array('Registration.TXN_ID'=>23)
3126
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3127
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3128
-                    if (! is_array($possibly_array_of_params)) {
3129
-                        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'))",
3130
-                            "event_espresso"),
3131
-                            $param, $possibly_array_of_params));
3132
-                    } else {
3133
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3134
-                            $model_query_info_carrier, $query_param_type);
3135
-                    }
3136
-                } elseif ($query_param_type === 0 //ie WHERE
3137
-                          && is_array($possibly_array_of_params)
3138
-                          && isset($possibly_array_of_params[2])
3139
-                          && $possibly_array_of_params[2] == true
3140
-                ) {
3141
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3142
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3143
-                    //from which we should extract query parameters!
3144
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3145
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3146
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3147
-                    }
3148
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3149
-                        $model_query_info_carrier, $query_param_type);
3150
-                }
3151
-            }
3152
-        }
3153
-        return $model_query_info_carrier;
3154
-    }
3155
-
3156
-
3157
-
3158
-    /**
3159
-     * For extracting related models from forced_joins, where the array values contain the info about what
3160
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3161
-     *
3162
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3163
-     *                                                      $query_params['having']
3164
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3165
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3166
-     * @throws EE_Error
3167
-     * @return \EE_Model_Query_Info_Carrier
3168
-     */
3169
-    private function _extract_related_models_from_sub_params_array_values(
3170
-        $sub_query_params,
3171
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3172
-        $query_param_type
3173
-    ) {
3174
-        if (! empty($sub_query_params)) {
3175
-            if (! is_array($sub_query_params)) {
3176
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3177
-                    $sub_query_params));
3178
-            }
3179
-            foreach ($sub_query_params as $param) {
3180
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3181
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3182
-                    $query_param_type);
3183
-            }
3184
-        }
3185
-        return $model_query_info_carrier;
3186
-    }
3187
-
3188
-
3189
-
3190
-    /**
3191
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3192
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3193
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3194
-     * but use them in a different order. Eg, we need to know what models we are querying
3195
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3196
-     * other models before we can finalize the where clause SQL.
3197
-     *
3198
-     * @param array $query_params
3199
-     * @throws EE_Error
3200
-     * @return EE_Model_Query_Info_Carrier
3201
-     */
3202
-    public function _create_model_query_info_carrier($query_params)
3203
-    {
3204
-        if (! is_array($query_params)) {
3205
-            EE_Error::doing_it_wrong(
3206
-                'EEM_Base::_create_model_query_info_carrier',
3207
-                sprintf(
3208
-                    __(
3209
-                        '$query_params should be an array, you passed a variable of type %s',
3210
-                        'event_espresso'
3211
-                    ),
3212
-                    gettype($query_params)
3213
-                ),
3214
-                '4.6.0'
3215
-            );
3216
-            $query_params = array();
3217
-        }
3218
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3219
-        //first check if we should alter the query to account for caps or not
3220
-        //because the caps might require us to do extra joins
3221
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3222
-            $query_params[0] = $where_query_params = array_replace_recursive(
3223
-                $where_query_params,
3224
-                $this->caps_where_conditions(
3225
-                    $query_params['caps']
3226
-                )
3227
-            );
3228
-        }
3229
-        $query_object = $this->_extract_related_models_from_query($query_params);
3230
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3231
-        foreach ($where_query_params as $key => $value) {
3232
-            if (is_int($key)) {
3233
-                throw new EE_Error(
3234
-                    sprintf(
3235
-                        __(
3236
-                            "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.",
3237
-                            "event_espresso"
3238
-                        ),
3239
-                        $key,
3240
-                        var_export($value, true),
3241
-                        var_export($query_params, true),
3242
-                        get_class($this)
3243
-                    )
3244
-                );
3245
-            }
3246
-        }
3247
-        if (
3248
-            array_key_exists('default_where_conditions', $query_params)
3249
-            && ! empty($query_params['default_where_conditions'])
3250
-        ) {
3251
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3252
-        } else {
3253
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3254
-        }
3255
-        $where_query_params = array_merge(
3256
-            $this->_get_default_where_conditions_for_models_in_query(
3257
-                $query_object,
3258
-                $use_default_where_conditions,
3259
-                $where_query_params
3260
-            ),
3261
-            $where_query_params
3262
-        );
3263
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3264
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3265
-        // So we need to setup a subquery and use that for the main join.
3266
-        // Note for now this only works on the primary table for the model.
3267
-        // So for instance, you could set the limit array like this:
3268
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3269
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3270
-            $query_object->set_main_model_join_sql(
3271
-                $this->_construct_limit_join_select(
3272
-                    $query_params['on_join_limit'][0],
3273
-                    $query_params['on_join_limit'][1]
3274
-                )
3275
-            );
3276
-        }
3277
-        //set limit
3278
-        if (array_key_exists('limit', $query_params)) {
3279
-            if (is_array($query_params['limit'])) {
3280
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3281
-                    $e = sprintf(
3282
-                        __(
3283
-                            "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)",
3284
-                            "event_espresso"
3285
-                        ),
3286
-                        http_build_query($query_params['limit'])
3287
-                    );
3288
-                    throw new EE_Error($e . "|" . $e);
3289
-                }
3290
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3291
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3292
-            } elseif (! empty ($query_params['limit'])) {
3293
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3294
-            }
3295
-        }
3296
-        //set order by
3297
-        if (array_key_exists('order_by', $query_params)) {
3298
-            if (is_array($query_params['order_by'])) {
3299
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3300
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3301
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3302
-                if (array_key_exists('order', $query_params)) {
3303
-                    throw new EE_Error(
3304
-                        sprintf(
3305
-                            __(
3306
-                                "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 ",
3307
-                                "event_espresso"
3308
-                            ),
3309
-                            get_class($this),
3310
-                            implode(", ", array_keys($query_params['order_by'])),
3311
-                            implode(", ", $query_params['order_by']),
3312
-                            $query_params['order']
3313
-                        )
3314
-                    );
3315
-                }
3316
-                $this->_extract_related_models_from_sub_params_array_keys(
3317
-                    $query_params['order_by'],
3318
-                    $query_object,
3319
-                    'order_by'
3320
-                );
3321
-                //assume it's an array of fields to order by
3322
-                $order_array = array();
3323
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3324
-                    $order = $this->_extract_order($order);
3325
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3326
-                }
3327
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3328
-            } elseif (! empty ($query_params['order_by'])) {
3329
-                $this->_extract_related_model_info_from_query_param(
3330
-                    $query_params['order_by'],
3331
-                    $query_object,
3332
-                    'order',
3333
-                    $query_params['order_by']
3334
-                );
3335
-                $order = isset($query_params['order'])
3336
-                    ? $this->_extract_order($query_params['order'])
3337
-                    : 'DESC';
3338
-                $query_object->set_order_by_sql(
3339
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3340
-                );
3341
-            }
3342
-        }
3343
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3344
-        if (! array_key_exists('order_by', $query_params)
3345
-            && array_key_exists('order', $query_params)
3346
-            && ! empty($query_params['order'])
3347
-        ) {
3348
-            $pk_field = $this->get_primary_key_field();
3349
-            $order = $this->_extract_order($query_params['order']);
3350
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3351
-        }
3352
-        //set group by
3353
-        if (array_key_exists('group_by', $query_params)) {
3354
-            if (is_array($query_params['group_by'])) {
3355
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3356
-                $group_by_array = array();
3357
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3358
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3359
-                }
3360
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3361
-            } elseif (! empty ($query_params['group_by'])) {
3362
-                $query_object->set_group_by_sql(
3363
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3364
-                );
3365
-            }
3366
-        }
3367
-        //set having
3368
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3369
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3370
-        }
3371
-        //now, just verify they didn't pass anything wack
3372
-        foreach ($query_params as $query_key => $query_value) {
3373
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3374
-                throw new EE_Error(
3375
-                    sprintf(
3376
-                        __(
3377
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3378
-                            'event_espresso'
3379
-                        ),
3380
-                        $query_key,
3381
-                        get_class($this),
3382
-                        //						print_r( $this->_allowed_query_params, TRUE )
3383
-                        implode(',', $this->_allowed_query_params)
3384
-                    )
3385
-                );
3386
-            }
3387
-        }
3388
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3389
-        if (empty($main_model_join_sql)) {
3390
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3391
-        }
3392
-        return $query_object;
3393
-    }
3394
-
3395
-
3396
-
3397
-    /**
3398
-     * Gets the where conditions that should be imposed on the query based on the
3399
-     * context (eg reading frontend, backend, edit or delete).
3400
-     *
3401
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3402
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3403
-     * @throws \EE_Error
3404
-     */
3405
-    public function caps_where_conditions($context = self::caps_read)
3406
-    {
3407
-        EEM_Base::verify_is_valid_cap_context($context);
3408
-        $cap_where_conditions = array();
3409
-        $cap_restrictions = $this->caps_missing($context);
3410
-        /**
3411
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3412
-         */
3413
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3414
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3415
-                $restriction_if_no_cap->get_default_where_conditions());
3416
-        }
3417
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3418
-            $cap_restrictions);
3419
-    }
3420
-
3421
-
3422
-
3423
-    /**
3424
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3425
-     * otherwise throws an exception
3426
-     *
3427
-     * @param string $should_be_order_string
3428
-     * @return string either ASC, asc, DESC or desc
3429
-     * @throws EE_Error
3430
-     */
3431
-    private function _extract_order($should_be_order_string)
3432
-    {
3433
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3434
-            return $should_be_order_string;
3435
-        } else {
3436
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3437
-                "event_espresso"), get_class($this), $should_be_order_string));
3438
-        }
3439
-    }
3440
-
3441
-
3442
-
3443
-    /**
3444
-     * Looks at all the models which are included in this query, and asks each
3445
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3446
-     * so they can be merged
3447
-     *
3448
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3449
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3450
-     *                                                                  'none' means NO default where conditions will
3451
-     *                                                                  be used AT ALL during this query.
3452
-     *                                                                  'other_models_only' means default where
3453
-     *                                                                  conditions from other models will be used, but
3454
-     *                                                                  not for this primary model. 'all', the default,
3455
-     *                                                                  means default where conditions will apply as
3456
-     *                                                                  normal
3457
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3458
-     * @throws EE_Error
3459
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3460
-     */
3461
-    private function _get_default_where_conditions_for_models_in_query(
3462
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3463
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3464
-        $where_query_params = array()
3465
-    ) {
3466
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3467
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3468
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3469
-                "event_espresso"), $use_default_where_conditions,
3470
-                implode(", ", $allowed_used_default_where_conditions_values)));
3471
-        }
3472
-        $universal_query_params = array();
3473
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3474
-            $universal_query_params = $this->_get_default_where_conditions();
3475
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3476
-            $universal_query_params = $this->_get_minimum_where_conditions();
3477
-        }
3478
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3479
-            $related_model = $this->get_related_model_obj($model_name);
3480
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3481
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3482
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3483
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3484
-            } else {
3485
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3486
-                continue;
3487
-            }
3488
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3489
-                $related_model_universal_where_params,
3490
-                $where_query_params,
3491
-                $related_model,
3492
-                $model_relation_path
3493
-            );
3494
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3495
-                $universal_query_params,
3496
-                $overrides
3497
-            );
3498
-        }
3499
-        return $universal_query_params;
3500
-    }
3501
-
3502
-
3503
-
3504
-    /**
3505
-     * Determines whether or not we should use default where conditions for the model in question
3506
-     * (this model, or other related models).
3507
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3508
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3509
-     * We should use default where conditions on related models when they requested to use default where conditions
3510
-     * on all models, or specifically just on other related models
3511
-     * @param      $default_where_conditions_value
3512
-     * @param bool $for_this_model false means this is for OTHER related models
3513
-     * @return bool
3514
-     */
3515
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3516
-    {
3517
-        return (
3518
-                   $for_this_model
3519
-                   && in_array(
3520
-                       $default_where_conditions_value,
3521
-                       array(
3522
-                           EEM_Base::default_where_conditions_all,
3523
-                           EEM_Base::default_where_conditions_this_only,
3524
-                           EEM_Base::default_where_conditions_minimum_others,
3525
-                       ),
3526
-                       true
3527
-                   )
3528
-               )
3529
-               || (
3530
-                   ! $for_this_model
3531
-                   && in_array(
3532
-                       $default_where_conditions_value,
3533
-                       array(
3534
-                           EEM_Base::default_where_conditions_all,
3535
-                           EEM_Base::default_where_conditions_others_only,
3536
-                       ),
3537
-                       true
3538
-                   )
3539
-               );
3540
-    }
3541
-
3542
-    /**
3543
-     * Determines whether or not we should use default minimum conditions for the model in question
3544
-     * (this model, or other related models).
3545
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3546
-     * where conditions.
3547
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3548
-     * on this model or others
3549
-     * @param      $default_where_conditions_value
3550
-     * @param bool $for_this_model false means this is for OTHER related models
3551
-     * @return bool
3552
-     */
3553
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3554
-    {
3555
-        return (
3556
-                   $for_this_model
3557
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3558
-               )
3559
-               || (
3560
-                   ! $for_this_model
3561
-                   && in_array(
3562
-                       $default_where_conditions_value,
3563
-                       array(
3564
-                           EEM_Base::default_where_conditions_minimum_others,
3565
-                           EEM_Base::default_where_conditions_minimum_all,
3566
-                       ),
3567
-                       true
3568
-                   )
3569
-               );
3570
-    }
3571
-
3572
-
3573
-    /**
3574
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3575
-     * then we also add a special where condition which allows for that model's primary key
3576
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3577
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3578
-     *
3579
-     * @param array    $default_where_conditions
3580
-     * @param array    $provided_where_conditions
3581
-     * @param EEM_Base $model
3582
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3583
-     * @return array like EEM_Base::get_all's $query_params[0]
3584
-     * @throws \EE_Error
3585
-     */
3586
-    private function _override_defaults_or_make_null_friendly(
3587
-        $default_where_conditions,
3588
-        $provided_where_conditions,
3589
-        $model,
3590
-        $model_relation_path
3591
-    ) {
3592
-        $null_friendly_where_conditions = array();
3593
-        $none_overridden = true;
3594
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3595
-        foreach ($default_where_conditions as $key => $val) {
3596
-            if (isset($provided_where_conditions[$key])) {
3597
-                $none_overridden = false;
3598
-            } else {
3599
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3600
-            }
3601
-        }
3602
-        if ($none_overridden && $default_where_conditions) {
3603
-            if ($model->has_primary_key_field()) {
3604
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3605
-                                                                                . "."
3606
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3607
-            }/*else{
32
+	//admin posty
33
+	//basic -> grants access to mine -> if they don't have it, select none
34
+	//*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
35
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
36
+	//*_published -> grants access to published -> if they dont have it, select non-published
37
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
38
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
39
+	//frontend posty
40
+	//by default has access to published
41
+	//basic -> grants access to mine that arent published, and all published
42
+	//*_others ->grants access to others that arent private, all mine
43
+	//*_private -> grants full access
44
+	//frontend non-posty
45
+	//like admin posty
46
+	//category-y
47
+	//assign -> grants access to join-table
48
+	//(delete, edit)
49
+	//payment-method-y
50
+	//for each registered payment method,
51
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
52
+	/**
53
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
54
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
55
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
56
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
57
+	 *
58
+	 * @var boolean
59
+	 */
60
+	private $_values_already_prepared_by_model_object = 0;
61
+
62
+	/**
63
+	 * when $_values_already_prepared_by_model_object equals this, we assume
64
+	 * the data is just like form input that needs to have the model fields'
65
+	 * prepare_for_set and prepare_for_use_in_db called on it
66
+	 */
67
+	const not_prepared_by_model_object = 0;
68
+
69
+	/**
70
+	 * when $_values_already_prepared_by_model_object equals this, we
71
+	 * assume this value is coming from a model object and doesn't need to have
72
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
73
+	 */
74
+	const prepared_by_model_object = 1;
75
+
76
+	/**
77
+	 * when $_values_already_prepared_by_model_object equals this, we assume
78
+	 * the values are already to be used in the database (ie no processing is done
79
+	 * on them by the model's fields)
80
+	 */
81
+	const prepared_for_use_in_db = 2;
82
+
83
+
84
+	protected $singular_item = 'Item';
85
+
86
+	protected $plural_item   = 'Items';
87
+
88
+	/**
89
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
90
+	 */
91
+	protected $_tables;
92
+
93
+	/**
94
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
95
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
96
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
97
+	 *
98
+	 * @var \EE_Model_Field_Base[] $_fields
99
+	 */
100
+	protected $_fields;
101
+
102
+	/**
103
+	 * array of different kinds of relations
104
+	 *
105
+	 * @var \EE_Model_Relation_Base[] $_model_relations
106
+	 */
107
+	protected $_model_relations;
108
+
109
+	/**
110
+	 * @var \EE_Index[] $_indexes
111
+	 */
112
+	protected $_indexes = array();
113
+
114
+	/**
115
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
116
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
117
+	 * by setting the same columns as used in these queries in the query yourself.
118
+	 *
119
+	 * @var EE_Default_Where_Conditions
120
+	 */
121
+	protected $_default_where_conditions_strategy;
122
+
123
+	/**
124
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
125
+	 * This is particularly useful when you want something between 'none' and 'default'
126
+	 *
127
+	 * @var EE_Default_Where_Conditions
128
+	 */
129
+	protected $_minimum_where_conditions_strategy;
130
+
131
+	/**
132
+	 * String describing how to find the "owner" of this model's objects.
133
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
134
+	 * But when there isn't, this indicates which related model, or transiently-related model,
135
+	 * has the foreign key to the wp_users table.
136
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
137
+	 * related to events, and events have a foreign key to wp_users.
138
+	 * On EEM_Transaction, this would be 'Transaction.Event'
139
+	 *
140
+	 * @var string
141
+	 */
142
+	protected $_model_chain_to_wp_user = '';
143
+
144
+	/**
145
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
146
+	 * don't need it (particularly CPT models)
147
+	 *
148
+	 * @var bool
149
+	 */
150
+	protected $_ignore_where_strategy = false;
151
+
152
+	/**
153
+	 * String used in caps relating to this model. Eg, if the caps relating to this
154
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
155
+	 *
156
+	 * @var string. If null it hasn't been initialized yet. If false then we
157
+	 * have indicated capabilities don't apply to this
158
+	 */
159
+	protected $_caps_slug = null;
160
+
161
+	/**
162
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
163
+	 * and next-level keys are capability names, and each's value is a
164
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
165
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
166
+	 * and then each capability in the corresponding sub-array that they're missing
167
+	 * adds the where conditions onto the query.
168
+	 *
169
+	 * @var array
170
+	 */
171
+	protected $_cap_restrictions = array(
172
+		self::caps_read       => array(),
173
+		self::caps_read_admin => array(),
174
+		self::caps_edit       => array(),
175
+		self::caps_delete     => array(),
176
+	);
177
+
178
+	/**
179
+	 * Array defining which cap restriction generators to use to create default
180
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
181
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
182
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
183
+	 * automatically set this to false (not just null).
184
+	 *
185
+	 * @var EE_Restriction_Generator_Base[]
186
+	 */
187
+	protected $_cap_restriction_generators = array();
188
+
189
+	/**
190
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
191
+	 */
192
+	const caps_read       = 'read';
193
+
194
+	const caps_read_admin = 'read_admin';
195
+
196
+	const caps_edit       = 'edit';
197
+
198
+	const caps_delete     = 'delete';
199
+
200
+	/**
201
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
202
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
203
+	 * maps to 'read' because when looking for relevant permissions we're going to use
204
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
205
+	 *
206
+	 * @var array
207
+	 */
208
+	protected $_cap_contexts_to_cap_action_map = array(
209
+		self::caps_read       => 'read',
210
+		self::caps_read_admin => 'read',
211
+		self::caps_edit       => 'edit',
212
+		self::caps_delete     => 'delete',
213
+	);
214
+
215
+	/**
216
+	 * Timezone
217
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
218
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
219
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
220
+	 * EE_Datetime_Field data type will have access to it.
221
+	 *
222
+	 * @var string
223
+	 */
224
+	protected $_timezone;
225
+
226
+
227
+	/**
228
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
229
+	 * multisite.
230
+	 *
231
+	 * @var int
232
+	 */
233
+	protected static $_model_query_blog_id;
234
+
235
+	/**
236
+	 * A copy of _fields, except the array keys are the model names pointed to by
237
+	 * the field
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cache_foreign_key_to_fields = array();
242
+
243
+	/**
244
+	 * Cached list of all the fields on the model, indexed by their name
245
+	 *
246
+	 * @var EE_Model_Field_Base[]
247
+	 */
248
+	private $_cached_fields = null;
249
+
250
+	/**
251
+	 * Cached list of all the fields on the model, except those that are
252
+	 * marked as only pertinent to the database
253
+	 *
254
+	 * @var EE_Model_Field_Base[]
255
+	 */
256
+	private $_cached_fields_non_db_only = null;
257
+
258
+	/**
259
+	 * A cached reference to the primary key for quick lookup
260
+	 *
261
+	 * @var EE_Model_Field_Base
262
+	 */
263
+	private $_primary_key_field = null;
264
+
265
+	/**
266
+	 * Flag indicating whether this model has a primary key or not
267
+	 *
268
+	 * @var boolean
269
+	 */
270
+	protected $_has_primary_key_field = null;
271
+
272
+	/**
273
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
274
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
275
+	 *
276
+	 * @var boolean
277
+	 */
278
+	protected $_wp_core_model = false;
279
+
280
+	/**
281
+	 *    List of valid operators that can be used for querying.
282
+	 * The keys are all operators we'll accept, the values are the real SQL
283
+	 * operators used
284
+	 *
285
+	 * @var array
286
+	 */
287
+	protected $_valid_operators = array(
288
+		'='           => '=',
289
+		'<='          => '<=',
290
+		'<'           => '<',
291
+		'>='          => '>=',
292
+		'>'           => '>',
293
+		'!='          => '!=',
294
+		'LIKE'        => 'LIKE',
295
+		'like'        => 'LIKE',
296
+		'NOT_LIKE'    => 'NOT LIKE',
297
+		'not_like'    => 'NOT LIKE',
298
+		'NOT LIKE'    => 'NOT LIKE',
299
+		'not like'    => 'NOT LIKE',
300
+		'IN'          => 'IN',
301
+		'in'          => 'IN',
302
+		'NOT_IN'      => 'NOT IN',
303
+		'not_in'      => 'NOT IN',
304
+		'NOT IN'      => 'NOT IN',
305
+		'not in'      => 'NOT IN',
306
+		'between'     => 'BETWEEN',
307
+		'BETWEEN'     => 'BETWEEN',
308
+		'IS_NOT_NULL' => 'IS NOT NULL',
309
+		'is_not_null' => 'IS NOT NULL',
310
+		'IS NOT NULL' => 'IS NOT NULL',
311
+		'is not null' => 'IS NOT NULL',
312
+		'IS_NULL'     => 'IS NULL',
313
+		'is_null'     => 'IS NULL',
314
+		'IS NULL'     => 'IS NULL',
315
+		'is null'     => 'IS NULL',
316
+		'REGEXP'      => 'REGEXP',
317
+		'regexp'      => 'REGEXP',
318
+		'NOT_REGEXP'  => 'NOT REGEXP',
319
+		'not_regexp'  => 'NOT REGEXP',
320
+		'NOT REGEXP'  => 'NOT REGEXP',
321
+		'not regexp'  => 'NOT REGEXP',
322
+	);
323
+
324
+	/**
325
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
326
+	 *
327
+	 * @var array
328
+	 */
329
+	protected $_in_style_operators = array('IN', 'NOT IN');
330
+
331
+	/**
332
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
333
+	 * '12-31-2012'"
334
+	 *
335
+	 * @var array
336
+	 */
337
+	protected $_between_style_operators = array('BETWEEN');
338
+
339
+	/**
340
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
341
+	 * on a join table.
342
+	 *
343
+	 * @var array
344
+	 */
345
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
346
+
347
+	/**
348
+	 * Allowed values for $query_params['order'] for ordering in queries
349
+	 *
350
+	 * @var array
351
+	 */
352
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
353
+
354
+	/**
355
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
356
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
357
+	 *
358
+	 * @var array
359
+	 */
360
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
361
+
362
+	/**
363
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
364
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
365
+	 *
366
+	 * @var array
367
+	 */
368
+	private $_allowed_query_params = array(
369
+		0,
370
+		'limit',
371
+		'order_by',
372
+		'group_by',
373
+		'having',
374
+		'force_join',
375
+		'order',
376
+		'on_join_limit',
377
+		'default_where_conditions',
378
+		'caps',
379
+	);
380
+
381
+	/**
382
+	 * All the data types that can be used in $wpdb->prepare statements.
383
+	 *
384
+	 * @var array
385
+	 */
386
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
387
+
388
+	/**
389
+	 *    EE_Registry Object
390
+	 *
391
+	 * @var    object
392
+	 * @access    protected
393
+	 */
394
+	protected $EE = null;
395
+
396
+
397
+	/**
398
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
399
+	 *
400
+	 * @var int
401
+	 */
402
+	protected $_show_next_x_db_queries = 0;
403
+
404
+	/**
405
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
406
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
407
+	 *
408
+	 * @var array
409
+	 */
410
+	protected $_custom_selections = array();
411
+
412
+	/**
413
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
414
+	 * caches every model object we've fetched from the DB on this request
415
+	 *
416
+	 * @var array
417
+	 */
418
+	protected $_entity_map;
419
+
420
+	/**
421
+	 * constant used to show EEM_Base has not yet verified the db on this http request
422
+	 */
423
+	const db_verified_none = 0;
424
+
425
+	/**
426
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
427
+	 * but not the addons' dbs
428
+	 */
429
+	const db_verified_core = 1;
430
+
431
+	/**
432
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
433
+	 * the EE core db too)
434
+	 */
435
+	const db_verified_addons = 2;
436
+
437
+	/**
438
+	 * indicates whether an EEM_Base child has already re-verified the DB
439
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
440
+	 * looking like EEM_Base::db_verified_*
441
+	 *
442
+	 * @var int - 0 = none, 1 = core, 2 = addons
443
+	 */
444
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
445
+
446
+	/**
447
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
448
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
449
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
450
+	 */
451
+	const default_where_conditions_all = 'all';
452
+
453
+	/**
454
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
455
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
456
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
457
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
458
+	 *        models which share tables with other models, this can return data for the wrong model.
459
+	 */
460
+	const default_where_conditions_this_only = 'this_model_only';
461
+
462
+	/**
463
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
464
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
465
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
466
+	 */
467
+	const default_where_conditions_others_only = 'other_models_only';
468
+
469
+	/**
470
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
471
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
472
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
473
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
474
+	 *        (regardless of whether those events and venues are trashed)
475
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
476
+	 *        events.
477
+	 */
478
+	const default_where_conditions_minimum_all = 'minimum';
479
+
480
+	/**
481
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
482
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
483
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
484
+	 *        not)
485
+	 */
486
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
487
+
488
+	/**
489
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
490
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
491
+	 *        it's possible it will return table entries for other models. You should use
492
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
493
+	 */
494
+	const default_where_conditions_none = 'none';
495
+
496
+
497
+
498
+	/**
499
+	 * About all child constructors:
500
+	 * they should define the _tables, _fields and _model_relations arrays.
501
+	 * Should ALWAYS be called after child constructor.
502
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
503
+	 * finalizes constructing all the object's attributes.
504
+	 * Generally, rather than requiring a child to code
505
+	 * $this->_tables = array(
506
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
507
+	 *        ...);
508
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
509
+	 * each EE_Table has a function to set the table's alias after the constructor, using
510
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
511
+	 * do something similar.
512
+	 *
513
+	 * @param null $timezone
514
+	 * @throws \EE_Error
515
+	 */
516
+	protected function __construct($timezone = null)
517
+	{
518
+		// check that the model has not been loaded too soon
519
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
520
+			throw new EE_Error (
521
+				sprintf(
522
+					__('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.',
523
+						'event_espresso'),
524
+					get_class($this)
525
+				)
526
+			);
527
+		}
528
+		/**
529
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
530
+		 */
531
+		if (empty(EEM_Base::$_model_query_blog_id)) {
532
+			EEM_Base::set_model_query_blog_id();
533
+		}
534
+		/**
535
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
536
+		 * just use EE_Register_Model_Extension
537
+		 *
538
+		 * @var EE_Table_Base[] $_tables
539
+		 */
540
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
541
+		foreach ($this->_tables as $table_alias => $table_obj) {
542
+			/** @var $table_obj EE_Table_Base */
543
+			$table_obj->_construct_finalize_with_alias($table_alias);
544
+			if ($table_obj instanceof EE_Secondary_Table) {
545
+				/** @var $table_obj EE_Secondary_Table */
546
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
547
+			}
548
+		}
549
+		/**
550
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
551
+		 * EE_Register_Model_Extension
552
+		 *
553
+		 * @param EE_Model_Field_Base[] $_fields
554
+		 */
555
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
556
+		$this->_invalidate_field_caches();
557
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
558
+			if (! array_key_exists($table_alias, $this->_tables)) {
559
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
560
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
561
+			}
562
+			foreach ($fields_for_table as $field_name => $field_obj) {
563
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
564
+				//primary key field base has a slightly different _construct_finalize
565
+				/** @var $field_obj EE_Model_Field_Base */
566
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
567
+			}
568
+		}
569
+		// everything is related to Extra_Meta
570
+		if (get_class($this) !== 'EEM_Extra_Meta') {
571
+			//make extra meta related to everything, but don't block deleting things just
572
+			//because they have related extra meta info. For now just orphan those extra meta
573
+			//in the future we should automatically delete them
574
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
575
+		}
576
+		//and change logs
577
+		if (get_class($this) !== 'EEM_Change_Log') {
578
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
579
+		}
580
+		/**
581
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
582
+		 * EE_Register_Model_Extension
583
+		 *
584
+		 * @param EE_Model_Relation_Base[] $_model_relations
585
+		 */
586
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
587
+			$this->_model_relations);
588
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
589
+			/** @var $relation_obj EE_Model_Relation_Base */
590
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
591
+		}
592
+		foreach ($this->_indexes as $index_name => $index_obj) {
593
+			/** @var $index_obj EE_Index */
594
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
595
+		}
596
+		$this->set_timezone($timezone);
597
+		//finalize default where condition strategy, or set default
598
+		if (! $this->_default_where_conditions_strategy) {
599
+			//nothing was set during child constructor, so set default
600
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
601
+		}
602
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
603
+		if (! $this->_minimum_where_conditions_strategy) {
604
+			//nothing was set during child constructor, so set default
605
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
606
+		}
607
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
608
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
609
+		//to indicate to NOT set it, set it to the logical default
610
+		if ($this->_caps_slug === null) {
611
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
612
+		}
613
+		//initialize the standard cap restriction generators if none were specified by the child constructor
614
+		if ($this->_cap_restriction_generators !== false) {
615
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
616
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
617
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
618
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
619
+						new EE_Restriction_Generator_Protected(),
620
+						$cap_context,
621
+						$this
622
+					);
623
+				}
624
+			}
625
+		}
626
+		//if there are cap restriction generators, use them to make the default cap restrictions
627
+		if ($this->_cap_restriction_generators !== false) {
628
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
629
+				if (! $generator_object) {
630
+					continue;
631
+				}
632
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
633
+					throw new EE_Error(
634
+						sprintf(
635
+							__('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.',
636
+								'event_espresso'),
637
+							$context,
638
+							$this->get_this_model_name()
639
+						)
640
+					);
641
+				}
642
+				$action = $this->cap_action_for_context($context);
643
+				if (! $generator_object->construction_finalized()) {
644
+					$generator_object->_construct_finalize($this, $action);
645
+				}
646
+			}
647
+		}
648
+		do_action('AHEE__' . get_class($this) . '__construct__end');
649
+	}
650
+
651
+
652
+
653
+	/**
654
+	 * Generates the cap restrictions for the given context, or if they were
655
+	 * already generated just gets what's cached
656
+	 *
657
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
658
+	 * @return EE_Default_Where_Conditions[]
659
+	 */
660
+	protected function _generate_cap_restrictions($context)
661
+	{
662
+		if (isset($this->_cap_restriction_generators[$context])
663
+			&& $this->_cap_restriction_generators[$context]
664
+			   instanceof
665
+			   EE_Restriction_Generator_Base
666
+		) {
667
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
668
+		} else {
669
+			return array();
670
+		}
671
+	}
672
+
673
+
674
+
675
+	/**
676
+	 * Used to set the $_model_query_blog_id static property.
677
+	 *
678
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
679
+	 *                      value for get_current_blog_id() will be used.
680
+	 */
681
+	public static function set_model_query_blog_id($blog_id = 0)
682
+	{
683
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
684
+	}
685
+
686
+
687
+
688
+	/**
689
+	 * Returns whatever is set as the internal $model_query_blog_id.
690
+	 *
691
+	 * @return int
692
+	 */
693
+	public static function get_model_query_blog_id()
694
+	{
695
+		return EEM_Base::$_model_query_blog_id;
696
+	}
697
+
698
+
699
+
700
+	/**
701
+	 *        This function is a singleton method used to instantiate the Espresso_model object
702
+	 *
703
+	 * @access public
704
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
705
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
706
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
707
+	 *                         timezone in the 'timezone_string' wp option)
708
+	 * @return static (as in the concrete child class)
709
+	 */
710
+	public static function instance($timezone = null)
711
+	{
712
+		// check if instance of Espresso_model already exists
713
+		if (! static::$_instance instanceof static) {
714
+			// instantiate Espresso_model
715
+			static::$_instance = new static($timezone);
716
+		}
717
+		//we might have a timezone set, let set_timezone decide what to do with it
718
+		static::$_instance->set_timezone($timezone);
719
+		// Espresso_model object
720
+		return static::$_instance;
721
+	}
722
+
723
+
724
+
725
+	/**
726
+	 * resets the model and returns it
727
+	 *
728
+	 * @param null | string $timezone
729
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
730
+	 * all its properties reset; if it wasn't instantiated, returns null)
731
+	 */
732
+	public static function reset($timezone = null)
733
+	{
734
+		if (static::$_instance instanceof EEM_Base) {
735
+			//let's try to NOT swap out the current instance for a new one
736
+			//because if someone has a reference to it, we can't remove their reference
737
+			//so it's best to keep using the same reference, but change the original object
738
+			//reset all its properties to their original values as defined in the class
739
+			$r = new ReflectionClass(get_class(static::$_instance));
740
+			$static_properties = $r->getStaticProperties();
741
+			foreach ($r->getDefaultProperties() as $property => $value) {
742
+				//don't set instance to null like it was originally,
743
+				//but it's static anyways, and we're ignoring static properties (for now at least)
744
+				if (! isset($static_properties[$property])) {
745
+					static::$_instance->{$property} = $value;
746
+				}
747
+			}
748
+			//and then directly call its constructor again, like we would if we
749
+			//were creating a new one
750
+			static::$_instance->__construct($timezone);
751
+			return self::instance();
752
+		}
753
+		return null;
754
+	}
755
+
756
+
757
+
758
+	/**
759
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
760
+	 *
761
+	 * @param  boolean $translated return localized strings or JUST the array.
762
+	 * @return array
763
+	 * @throws \EE_Error
764
+	 */
765
+	public function status_array($translated = false)
766
+	{
767
+		if (! array_key_exists('Status', $this->_model_relations)) {
768
+			return array();
769
+		}
770
+		$model_name = $this->get_this_model_name();
771
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
772
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
773
+		$status_array = array();
774
+		foreach ($stati as $status) {
775
+			$status_array[$status->ID()] = $status->get('STS_code');
776
+		}
777
+		return $translated
778
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
779
+			: $status_array;
780
+	}
781
+
782
+
783
+
784
+	/**
785
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
786
+	 *
787
+	 * @param array $query_params             {
788
+	 * @var array $0 (where) array {
789
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
790
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
791
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
792
+	 *                                        conditions based on related models (and even
793
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
794
+	 *                                        name. Eg,
795
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
796
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
797
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
798
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
799
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
800
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
801
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
802
+	 *                                        to Venues (even when each of those models actually consisted of two
803
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
804
+	 *                                        just having
805
+	 *                                        "Venue.VNU_ID", you could have
806
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
807
+	 *                                        events are related to Registrations, which are related to Attendees). You
808
+	 *                                        can take it even further with
809
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
810
+	 *                                        (from the default of '='), change the value to an numerically-indexed
811
+	 *                                        array, where the first item in the list is the operator. eg: array(
812
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
813
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
814
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
815
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
816
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
817
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
818
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
819
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
820
+	 *                                        the value is a field, simply provide a third array item (true) to the
821
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
822
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
823
+	 *                                        Note: you can also use related model field names like you would any other
824
+	 *                                        field name. eg:
825
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
826
+	 *                                        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__>' =>
827
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
828
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
829
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
830
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
831
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
832
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
833
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
834
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
835
+	 *                                        "stick" until you specify an AND. eg
836
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
837
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
838
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
839
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
840
+	 *                                        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 >>
841
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
842
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
843
+	 *                                        too, eg:
844
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
845
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
846
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
847
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
848
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
849
+	 *                                        the OFFSET, the 2nd is the LIMIT
850
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
851
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
852
+	 *                                        following format array('on_join_limit'
853
+	 *                                        => array( 'table_alias', array(1,2) ) ).
854
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
855
+	 *                                        values are either 'ASC' or 'DESC'.
856
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
857
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
858
+	 *                                        DESC..." respectively. Like the
859
+	 *                                        'where' conditions, these fields can be on related models. Eg
860
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
861
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
862
+	 *                                        Attendee, Price, Datetime, etc.)
863
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
864
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
865
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
866
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
867
+	 *                                        order by the primary key. Eg,
868
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
869
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
870
+	 *                                        DTT_EVT_start) or
871
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
872
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
873
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
874
+	 *                                        'group_by'=>'VNU_ID', or
875
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
876
+	 *                                        if no
877
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
878
+	 *                                        model's primary key (or combined primary keys). This avoids some
879
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
880
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
881
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
882
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
883
+	 *                                        results)
884
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
885
+	 *                                        array where values are models to be joined in the query.Eg
886
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
887
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
888
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
889
+	 *                                        related models which belongs to the current model
890
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
891
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
892
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
893
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
894
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
895
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
896
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
897
+	 *                                        this model's default where conditions added to the query, use
898
+	 *                                        'this_model_only'. If you want to use all default where conditions
899
+	 *                                        (default), set to 'all'.
900
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
901
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
902
+	 *                                        everything? Or should we only show the current user items they should be
903
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
904
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
905
+	 *                                        }
906
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
907
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
908
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
909
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
910
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
911
+	 *                                        array( array(
912
+	 *                                        'OR'=>array(
913
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
914
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
915
+	 *                                        )
916
+	 *                                        ),
917
+	 *                                        'limit'=>10,
918
+	 *                                        'group_by'=>'TXN_ID'
919
+	 *                                        ));
920
+	 *                                        get all the answers to the question titled "shirt size" for event with id
921
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
922
+	 *                                        'Question.QST_display_text'=>'shirt size',
923
+	 *                                        'Registration.Event.EVT_ID'=>12
924
+	 *                                        ),
925
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
926
+	 *                                        ));
927
+	 * @throws \EE_Error
928
+	 */
929
+	public function get_all($query_params = array())
930
+	{
931
+		if (isset($query_params['limit'])
932
+			&& ! isset($query_params['group_by'])
933
+		) {
934
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
935
+		}
936
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
937
+	}
938
+
939
+
940
+
941
+	/**
942
+	 * Modifies the query parameters so we only get back model objects
943
+	 * that "belong" to the current user
944
+	 *
945
+	 * @param array $query_params @see EEM_Base::get_all()
946
+	 * @return array like EEM_Base::get_all
947
+	 */
948
+	public function alter_query_params_to_only_include_mine($query_params = array())
949
+	{
950
+		$wp_user_field_name = $this->wp_user_field_name();
951
+		if ($wp_user_field_name) {
952
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
953
+		}
954
+		return $query_params;
955
+	}
956
+
957
+
958
+
959
+	/**
960
+	 * Returns the name of the field's name that points to the WP_User table
961
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
962
+	 * foreign key to the WP_User table)
963
+	 *
964
+	 * @return string|boolean string on success, boolean false when there is no
965
+	 * foreign key to the WP_User table
966
+	 */
967
+	public function wp_user_field_name()
968
+	{
969
+		try {
970
+			if (! empty($this->_model_chain_to_wp_user)) {
971
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
972
+				$last_model_name = end($models_to_follow_to_wp_users);
973
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
974
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
975
+			} else {
976
+				$model_with_fk_to_wp_users = $this;
977
+				$model_chain_to_wp_user = '';
978
+			}
979
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
980
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
981
+		} catch (EE_Error $e) {
982
+			return false;
983
+		}
984
+	}
985
+
986
+
987
+
988
+	/**
989
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
990
+	 * (or transiently-related model) has a foreign key to the wp_users table;
991
+	 * useful for finding if model objects of this type are 'owned' by the current user.
992
+	 * This is an empty string when the foreign key is on this model and when it isn't,
993
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
994
+	 * (or transiently-related model)
995
+	 *
996
+	 * @return string
997
+	 */
998
+	public function model_chain_to_wp_user()
999
+	{
1000
+		return $this->_model_chain_to_wp_user;
1001
+	}
1002
+
1003
+
1004
+
1005
+	/**
1006
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1007
+	 * like how registrations don't have a foreign key to wp_users, but the
1008
+	 * events they are for are), or is unrelated to wp users.
1009
+	 * generally available
1010
+	 *
1011
+	 * @return boolean
1012
+	 */
1013
+	public function is_owned()
1014
+	{
1015
+		if ($this->model_chain_to_wp_user()) {
1016
+			return true;
1017
+		} else {
1018
+			try {
1019
+				$this->get_foreign_key_to('WP_User');
1020
+				return true;
1021
+			} catch (EE_Error $e) {
1022
+				return false;
1023
+			}
1024
+		}
1025
+	}
1026
+
1027
+
1028
+
1029
+	/**
1030
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1031
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1032
+	 * the model)
1033
+	 *
1034
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1035
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1037
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1038
+	 *                                  override this and set the select to "*", or a specific column name, like
1039
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
+	 *                                  the aliases used to refer to this selection, and values are to be
1042
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
+	 * @throws \EE_Error
1046
+	 */
1047
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1048
+	{
1049
+		// remember the custom selections, if any, and type cast as array
1050
+		// (unless $columns_to_select is an object, then just set as an empty array)
1051
+		// Note: (array) 'some string' === array( 'some string' )
1052
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1053
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1054
+		$select_expressions = $columns_to_select !== null
1055
+			? $this->_construct_select_from_input($columns_to_select)
1056
+			: $this->_construct_default_select_sql($model_query_info);
1057
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1058
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1059
+	}
1060
+
1061
+
1062
+
1063
+	/**
1064
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1065
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1066
+	 * take care of joins, field preparation etc.
1067
+	 *
1068
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1069
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1070
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1071
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1072
+	 *                                  override this and set the select to "*", or a specific column name, like
1073
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1074
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1075
+	 *                                  the aliases used to refer to this selection, and values are to be
1076
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1077
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1078
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1079
+	 * @throws \EE_Error
1080
+	 */
1081
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1082
+	{
1083
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1084
+	}
1085
+
1086
+
1087
+
1088
+	/**
1089
+	 * For creating a custom select statement
1090
+	 *
1091
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1092
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1093
+	 *                                 SQL, and 1=>is the datatype
1094
+	 * @throws EE_Error
1095
+	 * @return string
1096
+	 */
1097
+	private function _construct_select_from_input($columns_to_select)
1098
+	{
1099
+		if (is_array($columns_to_select)) {
1100
+			$select_sql_array = array();
1101
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1102
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1103
+					throw new EE_Error(
1104
+						sprintf(
1105
+							__(
1106
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1107
+								"event_espresso"
1108
+							),
1109
+							$selection_and_datatype,
1110
+							$alias
1111
+						)
1112
+					);
1113
+				}
1114
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1115
+					throw new EE_Error(
1116
+						sprintf(
1117
+							__(
1118
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1119
+								"event_espresso"
1120
+							),
1121
+							$selection_and_datatype[1],
1122
+							$selection_and_datatype[0],
1123
+							$alias,
1124
+							implode(",", $this->_valid_wpdb_data_types)
1125
+						)
1126
+					);
1127
+				}
1128
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1129
+			}
1130
+			$columns_to_select_string = implode(", ", $select_sql_array);
1131
+		} else {
1132
+			$columns_to_select_string = $columns_to_select;
1133
+		}
1134
+		return $columns_to_select_string;
1135
+	}
1136
+
1137
+
1138
+
1139
+	/**
1140
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1141
+	 *
1142
+	 * @return string
1143
+	 * @throws \EE_Error
1144
+	 */
1145
+	public function primary_key_name()
1146
+	{
1147
+		return $this->get_primary_key_field()->get_name();
1148
+	}
1149
+
1150
+
1151
+
1152
+	/**
1153
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1154
+	 * If there is no primary key on this model, $id is treated as primary key string
1155
+	 *
1156
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1157
+	 * @return EE_Base_Class
1158
+	 */
1159
+	public function get_one_by_ID($id)
1160
+	{
1161
+		if ($this->get_from_entity_map($id)) {
1162
+			return $this->get_from_entity_map($id);
1163
+		}
1164
+		return $this->get_one(
1165
+			$this->alter_query_params_to_restrict_by_ID(
1166
+				$id,
1167
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1168
+			)
1169
+		);
1170
+	}
1171
+
1172
+
1173
+
1174
+	/**
1175
+	 * Alters query parameters to only get items with this ID are returned.
1176
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1177
+	 * or could just be a simple primary key ID
1178
+	 *
1179
+	 * @param int   $id
1180
+	 * @param array $query_params
1181
+	 * @return array of normal query params, @see EEM_Base::get_all
1182
+	 * @throws \EE_Error
1183
+	 */
1184
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1185
+	{
1186
+		if (! isset($query_params[0])) {
1187
+			$query_params[0] = array();
1188
+		}
1189
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1190
+		if ($conditions_from_id === null) {
1191
+			$query_params[0][$this->primary_key_name()] = $id;
1192
+		} else {
1193
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1194
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1195
+		}
1196
+		return $query_params;
1197
+	}
1198
+
1199
+
1200
+
1201
+	/**
1202
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1203
+	 * array. If no item is found, null is returned.
1204
+	 *
1205
+	 * @param array $query_params like EEM_Base's $query_params variable.
1206
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1207
+	 * @throws \EE_Error
1208
+	 */
1209
+	public function get_one($query_params = array())
1210
+	{
1211
+		if (! is_array($query_params)) {
1212
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1213
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1214
+					gettype($query_params)), '4.6.0');
1215
+			$query_params = array();
1216
+		}
1217
+		$query_params['limit'] = 1;
1218
+		$items = $this->get_all($query_params);
1219
+		if (empty($items)) {
1220
+			return null;
1221
+		} else {
1222
+			return array_shift($items);
1223
+		}
1224
+	}
1225
+
1226
+
1227
+
1228
+	/**
1229
+	 * Returns the next x number of items in sequence from the given value as
1230
+	 * found in the database matching the given query conditions.
1231
+	 *
1232
+	 * @param mixed $current_field_value    Value used for the reference point.
1233
+	 * @param null  $field_to_order_by      What field is used for the
1234
+	 *                                      reference point.
1235
+	 * @param int   $limit                  How many to return.
1236
+	 * @param array $query_params           Extra conditions on the query.
1237
+	 * @param null  $columns_to_select      If left null, then an array of
1238
+	 *                                      EE_Base_Class objects is returned,
1239
+	 *                                      otherwise you can indicate just the
1240
+	 *                                      columns you want returned.
1241
+	 * @return EE_Base_Class[]|array
1242
+	 * @throws \EE_Error
1243
+	 */
1244
+	public function next_x(
1245
+		$current_field_value,
1246
+		$field_to_order_by = null,
1247
+		$limit = 1,
1248
+		$query_params = array(),
1249
+		$columns_to_select = null
1250
+	) {
1251
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1252
+			$columns_to_select);
1253
+	}
1254
+
1255
+
1256
+
1257
+	/**
1258
+	 * Returns the previous x number of items in sequence from the given value
1259
+	 * as found in the database matching the given query conditions.
1260
+	 *
1261
+	 * @param mixed $current_field_value    Value used for the reference point.
1262
+	 * @param null  $field_to_order_by      What field is used for the
1263
+	 *                                      reference point.
1264
+	 * @param int   $limit                  How many to return.
1265
+	 * @param array $query_params           Extra conditions on the query.
1266
+	 * @param null  $columns_to_select      If left null, then an array of
1267
+	 *                                      EE_Base_Class objects is returned,
1268
+	 *                                      otherwise you can indicate just the
1269
+	 *                                      columns you want returned.
1270
+	 * @return EE_Base_Class[]|array
1271
+	 * @throws \EE_Error
1272
+	 */
1273
+	public function previous_x(
1274
+		$current_field_value,
1275
+		$field_to_order_by = null,
1276
+		$limit = 1,
1277
+		$query_params = array(),
1278
+		$columns_to_select = null
1279
+	) {
1280
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1281
+			$columns_to_select);
1282
+	}
1283
+
1284
+
1285
+
1286
+	/**
1287
+	 * Returns the next item in sequence from the given value as found in the
1288
+	 * database matching the given query conditions.
1289
+	 *
1290
+	 * @param mixed $current_field_value    Value used for the reference point.
1291
+	 * @param null  $field_to_order_by      What field is used for the
1292
+	 *                                      reference point.
1293
+	 * @param array $query_params           Extra conditions on the query.
1294
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1295
+	 *                                      object is returned, otherwise you
1296
+	 *                                      can indicate just the columns you
1297
+	 *                                      want and a single array indexed by
1298
+	 *                                      the columns will be returned.
1299
+	 * @return EE_Base_Class|null|array()
1300
+	 * @throws \EE_Error
1301
+	 */
1302
+	public function next(
1303
+		$current_field_value,
1304
+		$field_to_order_by = null,
1305
+		$query_params = array(),
1306
+		$columns_to_select = null
1307
+	) {
1308
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1309
+			$columns_to_select);
1310
+		return empty($results) ? null : reset($results);
1311
+	}
1312
+
1313
+
1314
+
1315
+	/**
1316
+	 * Returns the previous item in sequence from the given value as found in
1317
+	 * the database matching the given query conditions.
1318
+	 *
1319
+	 * @param mixed $current_field_value    Value used for the reference point.
1320
+	 * @param null  $field_to_order_by      What field is used for the
1321
+	 *                                      reference point.
1322
+	 * @param array $query_params           Extra conditions on the query.
1323
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1324
+	 *                                      object is returned, otherwise you
1325
+	 *                                      can indicate just the columns you
1326
+	 *                                      want and a single array indexed by
1327
+	 *                                      the columns will be returned.
1328
+	 * @return EE_Base_Class|null|array()
1329
+	 * @throws EE_Error
1330
+	 */
1331
+	public function previous(
1332
+		$current_field_value,
1333
+		$field_to_order_by = null,
1334
+		$query_params = array(),
1335
+		$columns_to_select = null
1336
+	) {
1337
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1338
+			$columns_to_select);
1339
+		return empty($results) ? null : reset($results);
1340
+	}
1341
+
1342
+
1343
+
1344
+	/**
1345
+	 * Returns the a consecutive number of items in sequence from the given
1346
+	 * value as found in the database matching the given query conditions.
1347
+	 *
1348
+	 * @param mixed  $current_field_value   Value used for the reference point.
1349
+	 * @param string $operand               What operand is used for the sequence.
1350
+	 * @param string $field_to_order_by     What field is used for the reference point.
1351
+	 * @param int    $limit                 How many to return.
1352
+	 * @param array  $query_params          Extra conditions on the query.
1353
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1354
+	 *                                      otherwise you can indicate just the columns you want returned.
1355
+	 * @return EE_Base_Class[]|array
1356
+	 * @throws EE_Error
1357
+	 */
1358
+	protected function _get_consecutive(
1359
+		$current_field_value,
1360
+		$operand = '>',
1361
+		$field_to_order_by = null,
1362
+		$limit = 1,
1363
+		$query_params = array(),
1364
+		$columns_to_select = null
1365
+	) {
1366
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1367
+		if (empty($field_to_order_by)) {
1368
+			if ($this->has_primary_key_field()) {
1369
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1370
+			} else {
1371
+				if (WP_DEBUG) {
1372
+					throw new EE_Error(__('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).',
1373
+						'event_espresso'));
1374
+				}
1375
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1376
+				return array();
1377
+			}
1378
+		}
1379
+		if (! is_array($query_params)) {
1380
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1381
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1382
+					gettype($query_params)), '4.6.0');
1383
+			$query_params = array();
1384
+		}
1385
+		//let's add the where query param for consecutive look up.
1386
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1387
+		$query_params['limit'] = $limit;
1388
+		//set direction
1389
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1390
+		$query_params['order_by'] = $operand === '>'
1391
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1392
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1393
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1394
+		if (empty($columns_to_select)) {
1395
+			return $this->get_all($query_params);
1396
+		} else {
1397
+			//getting just the fields
1398
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1399
+		}
1400
+	}
1401
+
1402
+
1403
+
1404
+	/**
1405
+	 * This sets the _timezone property after model object has been instantiated.
1406
+	 *
1407
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1408
+	 */
1409
+	public function set_timezone($timezone)
1410
+	{
1411
+		if ($timezone !== null) {
1412
+			$this->_timezone = $timezone;
1413
+		}
1414
+		//note we need to loop through relations and set the timezone on those objects as well.
1415
+		foreach ($this->_model_relations as $relation) {
1416
+			$relation->set_timezone($timezone);
1417
+		}
1418
+		//and finally we do the same for any datetime fields
1419
+		foreach ($this->_fields as $field) {
1420
+			if ($field instanceof EE_Datetime_Field) {
1421
+				$field->set_timezone($timezone);
1422
+			}
1423
+		}
1424
+	}
1425
+
1426
+
1427
+
1428
+	/**
1429
+	 * This just returns whatever is set for the current timezone.
1430
+	 *
1431
+	 * @access public
1432
+	 * @return string
1433
+	 */
1434
+	public function get_timezone()
1435
+	{
1436
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1437
+		if (empty($this->_timezone)) {
1438
+			foreach ($this->_fields as $field) {
1439
+				if ($field instanceof EE_Datetime_Field) {
1440
+					$this->set_timezone($field->get_timezone());
1441
+					break;
1442
+				}
1443
+			}
1444
+		}
1445
+		//if timezone STILL empty then return the default timezone for the site.
1446
+		if (empty($this->_timezone)) {
1447
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1448
+		}
1449
+		return $this->_timezone;
1450
+	}
1451
+
1452
+
1453
+
1454
+	/**
1455
+	 * This returns the date formats set for the given field name and also ensures that
1456
+	 * $this->_timezone property is set correctly.
1457
+	 *
1458
+	 * @since 4.6.x
1459
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1460
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1461
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1462
+	 * @return array formats in an array with the date format first, and the time format last.
1463
+	 */
1464
+	public function get_formats_for($field_name, $pretty = false)
1465
+	{
1466
+		$field_settings = $this->field_settings_for($field_name);
1467
+		//if not a valid EE_Datetime_Field then throw error
1468
+		if (! $field_settings instanceof EE_Datetime_Field) {
1469
+			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.',
1470
+				'event_espresso'), $field_name));
1471
+		}
1472
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1473
+		//the field.
1474
+		$this->_timezone = $field_settings->get_timezone();
1475
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1476
+	}
1477
+
1478
+
1479
+
1480
+	/**
1481
+	 * This returns the current time in a format setup for a query on this model.
1482
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1483
+	 * it will return:
1484
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1485
+	 *  NOW
1486
+	 *  - or a unix timestamp (equivalent to time())
1487
+	 *
1488
+	 * @since 4.6.x
1489
+	 * @param string $field_name       The field the current time is needed for.
1490
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1491
+	 *                                 formatted string matching the set format for the field in the set timezone will
1492
+	 *                                 be returned.
1493
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1494
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1495
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1496
+	 *                                 exception is triggered.
1497
+	 */
1498
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1499
+	{
1500
+		$formats = $this->get_formats_for($field_name);
1501
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1502
+		if ($timestamp) {
1503
+			return $DateTime->format('U');
1504
+		}
1505
+		//not returning timestamp, so return formatted string in timezone.
1506
+		switch ($what) {
1507
+			case 'time' :
1508
+				return $DateTime->format($formats[1]);
1509
+				break;
1510
+			case 'date' :
1511
+				return $DateTime->format($formats[0]);
1512
+				break;
1513
+			default :
1514
+				return $DateTime->format(implode(' ', $formats));
1515
+				break;
1516
+		}
1517
+	}
1518
+
1519
+
1520
+
1521
+	/**
1522
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1523
+	 * for the model are.  Returns a DateTime object.
1524
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1525
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1526
+	 * ignored.
1527
+	 *
1528
+	 * @param string $field_name      The field being setup.
1529
+	 * @param string $timestring      The date time string being used.
1530
+	 * @param string $incoming_format The format for the time string.
1531
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1532
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1533
+	 *                                format is
1534
+	 *                                'U', this is ignored.
1535
+	 * @return DateTime
1536
+	 * @throws \EE_Error
1537
+	 */
1538
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1539
+	{
1540
+		//just using this to ensure the timezone is set correctly internally
1541
+		$this->get_formats_for($field_name);
1542
+		//load EEH_DTT_Helper
1543
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1544
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1545
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1546
+	}
1547
+
1548
+
1549
+
1550
+	/**
1551
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1552
+	 *
1553
+	 * @return EE_Table_Base[]
1554
+	 */
1555
+	public function get_tables()
1556
+	{
1557
+		return $this->_tables;
1558
+	}
1559
+
1560
+
1561
+
1562
+	/**
1563
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1564
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1565
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1566
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1567
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1568
+	 * model object with EVT_ID = 1
1569
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1570
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1571
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1572
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1573
+	 * are not specified)
1574
+	 *
1575
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1576
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1577
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1578
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1579
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1580
+	 *                                         ID=34, we'd use this method as follows:
1581
+	 *                                         EEM_Transaction::instance()->update(
1582
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1583
+	 *                                         array(array('TXN_ID'=>34)));
1584
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1585
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1586
+	 *                                         consider updating Question's QST_admin_label field is of type
1587
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1588
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1589
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1590
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1591
+	 *                                         TRUE, it is assumed that you've already called
1592
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1593
+	 *                                         malicious javascript. However, if
1594
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1595
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1596
+	 *                                         and every other field, before insertion. We provide this parameter
1597
+	 *                                         because model objects perform their prepare_for_set function on all
1598
+	 *                                         their values, and so don't need to be called again (and in many cases,
1599
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1600
+	 *                                         prepare_for_set method...)
1601
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1602
+	 *                                         in this model's entity map according to $fields_n_values that match
1603
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1604
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1605
+	 *                                         could get out-of-sync with the database
1606
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1607
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1608
+	 *                                         bad)
1609
+	 * @throws \EE_Error
1610
+	 */
1611
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1612
+	{
1613
+		if (! is_array($query_params)) {
1614
+			EE_Error::doing_it_wrong('EEM_Base::update',
1615
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1616
+					gettype($query_params)), '4.6.0');
1617
+			$query_params = array();
1618
+		}
1619
+		/**
1620
+		 * Action called before a model update call has been made.
1621
+		 *
1622
+		 * @param EEM_Base $model
1623
+		 * @param array    $fields_n_values the updated fields and their new values
1624
+		 * @param array    $query_params    @see EEM_Base::get_all()
1625
+		 */
1626
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1627
+		/**
1628
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1629
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1630
+		 *
1631
+		 * @param array    $fields_n_values fields and their new values
1632
+		 * @param EEM_Base $model           the model being queried
1633
+		 * @param array    $query_params    see EEM_Base::get_all()
1634
+		 */
1635
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1636
+			$query_params);
1637
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1638
+		//to do that, for each table, verify that it's PK isn't null.
1639
+		$tables = $this->get_tables();
1640
+		//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
1641
+		//NOTE: we should make this code more efficient by NOT querying twice
1642
+		//before the real update, but that needs to first go through ALPHA testing
1643
+		//as it's dangerous. says Mike August 8 2014
1644
+		//we want to make sure the default_where strategy is ignored
1645
+		$this->_ignore_where_strategy = true;
1646
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1647
+		foreach ($wpdb_select_results as $wpdb_result) {
1648
+			// type cast stdClass as array
1649
+			$wpdb_result = (array)$wpdb_result;
1650
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1651
+			if ($this->has_primary_key_field()) {
1652
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1653
+			} else {
1654
+				//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)
1655
+				$main_table_pk_value = null;
1656
+			}
1657
+			//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
1658
+			//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
1659
+			if (count($tables) > 1) {
1660
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1661
+				//in that table, and so we'll want to insert one
1662
+				foreach ($tables as $table_obj) {
1663
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1664
+					//if there is no private key for this table on the results, it means there's no entry
1665
+					//in this table, right? so insert a row in the current table, using any fields available
1666
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1667
+						   && $wpdb_result[$this_table_pk_column])
1668
+					) {
1669
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1670
+							$main_table_pk_value);
1671
+						//if we died here, report the error
1672
+						if (! $success) {
1673
+							return false;
1674
+						}
1675
+					}
1676
+				}
1677
+			}
1678
+			//				//and now check that if we have cached any models by that ID on the model, that
1679
+			//				//they also get updated properly
1680
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1681
+			//				if( $model_object ){
1682
+			//					foreach( $fields_n_values as $field => $value ){
1683
+			//						$model_object->set($field, $value);
1684
+			//let's make sure default_where strategy is followed now
1685
+			$this->_ignore_where_strategy = false;
1686
+		}
1687
+		//if we want to keep model objects in sync, AND
1688
+		//if this wasn't called from a model object (to update itself)
1689
+		//then we want to make sure we keep all the existing
1690
+		//model objects in sync with the db
1691
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1692
+			if ($this->has_primary_key_field()) {
1693
+				$model_objs_affected_ids = $this->get_col($query_params);
1694
+			} else {
1695
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1696
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1697
+				$model_objs_affected_ids = array();
1698
+				foreach ($models_affected_key_columns as $row) {
1699
+					$combined_index_key = $this->get_index_primary_key_string($row);
1700
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1701
+				}
1702
+			}
1703
+			if (! $model_objs_affected_ids) {
1704
+				//wait wait wait- if nothing was affected let's stop here
1705
+				return 0;
1706
+			}
1707
+			foreach ($model_objs_affected_ids as $id) {
1708
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1709
+				if ($model_obj_in_entity_map) {
1710
+					foreach ($fields_n_values as $field => $new_value) {
1711
+						$model_obj_in_entity_map->set($field, $new_value);
1712
+					}
1713
+				}
1714
+			}
1715
+			//if there is a primary key on this model, we can now do a slight optimization
1716
+			if ($this->has_primary_key_field()) {
1717
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1718
+				$query_params = array(
1719
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1720
+					'limit'                    => count($model_objs_affected_ids),
1721
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1722
+				);
1723
+			}
1724
+		}
1725
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1726
+		$SQL = "UPDATE "
1727
+			   . $model_query_info->get_full_join_sql()
1728
+			   . " SET "
1729
+			   . $this->_construct_update_sql($fields_n_values)
1730
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1731
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1732
+		/**
1733
+		 * Action called after a model update call has been made.
1734
+		 *
1735
+		 * @param EEM_Base $model
1736
+		 * @param array    $fields_n_values the updated fields and their new values
1737
+		 * @param array    $query_params    @see EEM_Base::get_all()
1738
+		 * @param int      $rows_affected
1739
+		 */
1740
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1741
+		return $rows_affected;//how many supposedly got updated
1742
+	}
1743
+
1744
+
1745
+
1746
+	/**
1747
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1748
+	 * are teh values of the field specified (or by default the primary key field)
1749
+	 * that matched the query params. Note that you should pass the name of the
1750
+	 * model FIELD, not the database table's column name.
1751
+	 *
1752
+	 * @param array  $query_params @see EEM_Base::get_all()
1753
+	 * @param string $field_to_select
1754
+	 * @return array just like $wpdb->get_col()
1755
+	 * @throws \EE_Error
1756
+	 */
1757
+	public function get_col($query_params = array(), $field_to_select = null)
1758
+	{
1759
+		if ($field_to_select) {
1760
+			$field = $this->field_settings_for($field_to_select);
1761
+		} elseif ($this->has_primary_key_field()) {
1762
+			$field = $this->get_primary_key_field();
1763
+		} else {
1764
+			//no primary key, just grab the first column
1765
+			$field = reset($this->field_settings());
1766
+		}
1767
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1768
+		$select_expressions = $field->get_qualified_column();
1769
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1770
+		return $this->_do_wpdb_query('get_col', array($SQL));
1771
+	}
1772
+
1773
+
1774
+
1775
+	/**
1776
+	 * Returns a single column value for a single row from the database
1777
+	 *
1778
+	 * @param array  $query_params    @see EEM_Base::get_all()
1779
+	 * @param string $field_to_select @see EEM_Base::get_col()
1780
+	 * @return string
1781
+	 * @throws \EE_Error
1782
+	 */
1783
+	public function get_var($query_params = array(), $field_to_select = null)
1784
+	{
1785
+		$query_params['limit'] = 1;
1786
+		$col = $this->get_col($query_params, $field_to_select);
1787
+		if (! empty($col)) {
1788
+			return reset($col);
1789
+		} else {
1790
+			return null;
1791
+		}
1792
+	}
1793
+
1794
+
1795
+
1796
+	/**
1797
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1798
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1799
+	 * injection, but currently no further filtering is done
1800
+	 *
1801
+	 * @global      $wpdb
1802
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1803
+	 *                               be updated to in the DB
1804
+	 * @return string of SQL
1805
+	 * @throws \EE_Error
1806
+	 */
1807
+	public function _construct_update_sql($fields_n_values)
1808
+	{
1809
+		/** @type WPDB $wpdb */
1810
+		global $wpdb;
1811
+		$cols_n_values = array();
1812
+		foreach ($fields_n_values as $field_name => $value) {
1813
+			$field_obj = $this->field_settings_for($field_name);
1814
+			//if the value is NULL, we want to assign the value to that.
1815
+			//wpdb->prepare doesn't really handle that properly
1816
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1817
+			$value_sql = $prepared_value === null ? 'NULL'
1818
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1819
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1820
+		}
1821
+		return implode(",", $cols_n_values);
1822
+	}
1823
+
1824
+
1825
+
1826
+	/**
1827
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1828
+	 * Performs a HARD delete, meaning the database row should always be removed,
1829
+	 * not just have a flag field on it switched
1830
+	 * Wrapper for EEM_Base::delete_permanently()
1831
+	 *
1832
+	 * @param mixed $id
1833
+	 * @return boolean whether the row got deleted or not
1834
+	 * @throws \EE_Error
1835
+	 */
1836
+	public function delete_permanently_by_ID($id)
1837
+	{
1838
+		return $this->delete_permanently(
1839
+			array(
1840
+				array($this->get_primary_key_field()->get_name() => $id),
1841
+				'limit' => 1,
1842
+			)
1843
+		);
1844
+	}
1845
+
1846
+
1847
+
1848
+	/**
1849
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1850
+	 * Wrapper for EEM_Base::delete()
1851
+	 *
1852
+	 * @param mixed $id
1853
+	 * @return boolean whether the row got deleted or not
1854
+	 * @throws \EE_Error
1855
+	 */
1856
+	public function delete_by_ID($id)
1857
+	{
1858
+		return $this->delete(
1859
+			array(
1860
+				array($this->get_primary_key_field()->get_name() => $id),
1861
+				'limit' => 1,
1862
+			)
1863
+		);
1864
+	}
1865
+
1866
+
1867
+
1868
+	/**
1869
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1870
+	 * meaning if the model has a field that indicates its been "trashed" or
1871
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1872
+	 *
1873
+	 * @see EEM_Base::delete_permanently
1874
+	 * @param array   $query_params
1875
+	 * @param boolean $allow_blocking
1876
+	 * @return int how many rows got deleted
1877
+	 * @throws \EE_Error
1878
+	 */
1879
+	public function delete($query_params, $allow_blocking = true)
1880
+	{
1881
+		return $this->delete_permanently($query_params, $allow_blocking);
1882
+	}
1883
+
1884
+
1885
+
1886
+	/**
1887
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1888
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1889
+	 * as archived, not actually deleted
1890
+	 *
1891
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1892
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1893
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1894
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1895
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1896
+	 *                                DB
1897
+	 * @return int how many rows got deleted
1898
+	 * @throws \EE_Error
1899
+	 */
1900
+	public function delete_permanently($query_params, $allow_blocking = true)
1901
+	{
1902
+		/**
1903
+		 * Action called just before performing a real deletion query. You can use the
1904
+		 * model and its $query_params to find exactly which items will be deleted
1905
+		 *
1906
+		 * @param EEM_Base $model
1907
+		 * @param array    $query_params   @see EEM_Base::get_all()
1908
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1909
+		 *                                 to block (prevent) this deletion
1910
+		 */
1911
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1912
+		//some MySQL databases may be running safe mode, which may restrict
1913
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1914
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1915
+		//to delete them
1916
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1917
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1918
+		if ($deletion_where) {
1919
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1920
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1921
+			$table_aliases = array_keys($this->_tables);
1922
+			$SQL = "DELETE "
1923
+				   . implode(", ", $table_aliases)
1924
+				   . " FROM "
1925
+				   . $model_query_info->get_full_join_sql()
1926
+				   . " WHERE "
1927
+				   . $deletion_where;
1928
+			//		/echo "delete sql:$SQL";
1929
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1930
+		} else {
1931
+			$rows_deleted = 0;
1932
+		}
1933
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1934
+		if ($this->has_primary_key_field()) {
1935
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1936
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1937
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1938
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1939
+				}
1940
+			}
1941
+		}
1942
+		/**
1943
+		 * Action called just after performing a real deletion query. Although at this point the
1944
+		 * items should have been deleted
1945
+		 *
1946
+		 * @param EEM_Base $model
1947
+		 * @param array    $query_params @see EEM_Base::get_all()
1948
+		 * @param int      $rows_deleted
1949
+		 */
1950
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1951
+		return $rows_deleted;//how many supposedly got deleted
1952
+	}
1953
+
1954
+
1955
+
1956
+	/**
1957
+	 * Checks all the relations that throw error messages when there are blocking related objects
1958
+	 * for related model objects. If there are any related model objects on those relations,
1959
+	 * adds an EE_Error, and return true
1960
+	 *
1961
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1962
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1963
+	 *                                                 should be ignored when determining whether there are related
1964
+	 *                                                 model objects which block this model object's deletion. Useful
1965
+	 *                                                 if you know A is related to B and are considering deleting A,
1966
+	 *                                                 but want to see if A has any other objects blocking its deletion
1967
+	 *                                                 before removing the relation between A and B
1968
+	 * @return boolean
1969
+	 * @throws \EE_Error
1970
+	 */
1971
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1972
+	{
1973
+		//first, if $ignore_this_model_obj was supplied, get its model
1974
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1975
+			$ignored_model = $ignore_this_model_obj->get_model();
1976
+		} else {
1977
+			$ignored_model = null;
1978
+		}
1979
+		//now check all the relations of $this_model_obj_or_id and see if there
1980
+		//are any related model objects blocking it?
1981
+		$is_blocked = false;
1982
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
1983
+			if ($relation_obj->block_delete_if_related_models_exist()) {
1984
+				//if $ignore_this_model_obj was supplied, then for the query
1985
+				//on that model needs to be told to ignore $ignore_this_model_obj
1986
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1987
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1988
+						array(
1989
+							$ignored_model->get_primary_key_field()->get_name() => array(
1990
+								'!=',
1991
+								$ignore_this_model_obj->ID(),
1992
+							),
1993
+						),
1994
+					));
1995
+				} else {
1996
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1997
+				}
1998
+				if ($related_model_objects) {
1999
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2000
+					$is_blocked = true;
2001
+				}
2002
+			}
2003
+		}
2004
+		return $is_blocked;
2005
+	}
2006
+
2007
+
2008
+
2009
+	/**
2010
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2011
+	 * well.
2012
+	 *
2013
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2014
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2015
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
2016
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
2017
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
2018
+	 *                                      easily corrupt your DB
2019
+	 * @throws EE_Error
2020
+	 * @return string    everything that comes after the WHERE statement.
2021
+	 */
2022
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2023
+	{
2024
+		if ($this->has_primary_key_field()) {
2025
+			$primary_table = $this->_get_main_table();
2026
+			$other_tables = $this->_get_other_tables();
2027
+			$deletes = $query = array();
2028
+			foreach ($objects_for_deletion as $delete_object) {
2029
+				//before we mark this object for deletion,
2030
+				//make sure there's no related objects blocking its deletion (if we're checking)
2031
+				if (
2032
+					$allow_blocking
2033
+					&& $this->delete_is_blocked_by_related_models(
2034
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
2035
+					)
2036
+				) {
2037
+					continue;
2038
+				}
2039
+				//primary table deletes
2040
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2041
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2042
+				}
2043
+				//other tables
2044
+				if (! empty($other_tables)) {
2045
+					foreach ($other_tables as $ot) {
2046
+						//first check if we've got the foreign key column here.
2047
+						if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2048
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2049
+						}
2050
+						// wait! it's entirely possible that we'll have a the primary key
2051
+						// for this table in here, if it's a foreign key for one of the other secondary tables
2052
+						if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2053
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2054
+						}
2055
+						// finally, it is possible that the fk for this table is found
2056
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
2057
+						if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2058
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2059
+						}
2060
+					}
2061
+				}
2062
+			}
2063
+			//we should have deletes now, so let's just go through and setup the where statement
2064
+			foreach ($deletes as $column => $values) {
2065
+				//make sure we have unique $values;
2066
+				$values = array_unique($values);
2067
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
2068
+			}
2069
+			return ! empty($query) ? implode(' AND ', $query) : '';
2070
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2071
+			$ways_to_identify_a_row = array();
2072
+			$fields = $this->get_combined_primary_key_fields();
2073
+			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2074
+			foreach ($objects_for_deletion as $delete_object) {
2075
+				$values_for_each_cpk_for_a_row = array();
2076
+				foreach ($fields as $cpk_field) {
2077
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2078
+						$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2079
+														   . "="
2080
+														   . $delete_object[$cpk_field->get_qualified_column()];
2081
+					}
2082
+				}
2083
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2084
+			}
2085
+			return implode(" OR ", $ways_to_identify_a_row);
2086
+		} else {
2087
+			//so there's no primary key and no combined key...
2088
+			//sorry, can't help you
2089
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2090
+				"event_espresso"), get_class($this)));
2091
+		}
2092
+	}
2093
+
2094
+
2095
+
2096
+	/**
2097
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2098
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2099
+	 * column
2100
+	 *
2101
+	 * @param array  $query_params   like EEM_Base::get_all's
2102
+	 * @param string $field_to_count field on model to count by (not column name)
2103
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2104
+	 *                               that by the setting $distinct to TRUE;
2105
+	 * @return int
2106
+	 * @throws \EE_Error
2107
+	 */
2108
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2109
+	{
2110
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2111
+		if ($field_to_count) {
2112
+			$field_obj = $this->field_settings_for($field_to_count);
2113
+			$column_to_count = $field_obj->get_qualified_column();
2114
+		} elseif ($this->has_primary_key_field()) {
2115
+			$pk_field_obj = $this->get_primary_key_field();
2116
+			$column_to_count = $pk_field_obj->get_qualified_column();
2117
+		} else {
2118
+			//there's no primary key
2119
+			//if we're counting distinct items, and there's no primary key,
2120
+			//we need to list out the columns for distinction;
2121
+			//otherwise we can just use star
2122
+			if ($distinct) {
2123
+				$columns_to_use = array();
2124
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2125
+					$columns_to_use[] = $field_obj->get_qualified_column();
2126
+				}
2127
+				$column_to_count = implode(',', $columns_to_use);
2128
+			} else {
2129
+				$column_to_count = '*';
2130
+			}
2131
+		}
2132
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2133
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2134
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2135
+	}
2136
+
2137
+
2138
+
2139
+	/**
2140
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2141
+	 *
2142
+	 * @param array  $query_params like EEM_Base::get_all
2143
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2144
+	 * @return float
2145
+	 * @throws \EE_Error
2146
+	 */
2147
+	public function sum($query_params, $field_to_sum = null)
2148
+	{
2149
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2150
+		if ($field_to_sum) {
2151
+			$field_obj = $this->field_settings_for($field_to_sum);
2152
+		} else {
2153
+			$field_obj = $this->get_primary_key_field();
2154
+		}
2155
+		$column_to_count = $field_obj->get_qualified_column();
2156
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2157
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2158
+		$data_type = $field_obj->get_wpdb_data_type();
2159
+		if ($data_type === '%d' || $data_type === '%s') {
2160
+			return (float)$return_value;
2161
+		} else {//must be %f
2162
+			return (float)$return_value;
2163
+		}
2164
+	}
2165
+
2166
+
2167
+
2168
+	/**
2169
+	 * Just calls the specified method on $wpdb with the given arguments
2170
+	 * Consolidates a little extra error handling code
2171
+	 *
2172
+	 * @param string $wpdb_method
2173
+	 * @param array  $arguments_to_provide
2174
+	 * @throws EE_Error
2175
+	 * @global wpdb  $wpdb
2176
+	 * @return mixed
2177
+	 */
2178
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2179
+	{
2180
+		//if we're in maintenance mode level 2, DON'T run any queries
2181
+		//because level 2 indicates the database needs updating and
2182
+		//is probably out of sync with the code
2183
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2184
+			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.",
2185
+				"event_espresso")));
2186
+		}
2187
+		/** @type WPDB $wpdb */
2188
+		global $wpdb;
2189
+		if (! method_exists($wpdb, $wpdb_method)) {
2190
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2191
+				'event_espresso'), $wpdb_method));
2192
+		}
2193
+		if (WP_DEBUG) {
2194
+			$old_show_errors_value = $wpdb->show_errors;
2195
+			$wpdb->show_errors(false);
2196
+		}
2197
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2198
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2199
+		if (WP_DEBUG) {
2200
+			$wpdb->show_errors($old_show_errors_value);
2201
+			if (! empty($wpdb->last_error)) {
2202
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2203
+			} elseif ($result === false) {
2204
+				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"',
2205
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2206
+			}
2207
+		} elseif ($result === false) {
2208
+			EE_Error::add_error(
2209
+				sprintf(
2210
+					__('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"',
2211
+						'event_espresso'),
2212
+					$wpdb_method,
2213
+					var_export($arguments_to_provide, true),
2214
+					$wpdb->last_error
2215
+				),
2216
+				__FILE__,
2217
+				__FUNCTION__,
2218
+				__LINE__
2219
+			);
2220
+		}
2221
+		return $result;
2222
+	}
2223
+
2224
+
2225
+
2226
+	/**
2227
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2228
+	 * and if there's an error tries to verify the DB is correct. Uses
2229
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2230
+	 * we should try to fix the EE core db, the addons, or just give up
2231
+	 *
2232
+	 * @param string $wpdb_method
2233
+	 * @param array  $arguments_to_provide
2234
+	 * @return mixed
2235
+	 */
2236
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2237
+	{
2238
+		/** @type WPDB $wpdb */
2239
+		global $wpdb;
2240
+		$wpdb->last_error = null;
2241
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2242
+		// was there an error running the query? but we don't care on new activations
2243
+		// (we're going to setup the DB anyway on new activations)
2244
+		if (($result === false || ! empty($wpdb->last_error))
2245
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2246
+		) {
2247
+			switch (EEM_Base::$_db_verification_level) {
2248
+				case EEM_Base::db_verified_none :
2249
+					// let's double-check core's DB
2250
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2251
+					break;
2252
+				case EEM_Base::db_verified_core :
2253
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2254
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2255
+					break;
2256
+				case EEM_Base::db_verified_addons :
2257
+					// ummmm... you in trouble
2258
+					return $result;
2259
+					break;
2260
+			}
2261
+			if (! empty($error_message)) {
2262
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2263
+				trigger_error($error_message);
2264
+			}
2265
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2266
+		}
2267
+		return $result;
2268
+	}
2269
+
2270
+
2271
+
2272
+	/**
2273
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2274
+	 * EEM_Base::$_db_verification_level
2275
+	 *
2276
+	 * @param string $wpdb_method
2277
+	 * @param array  $arguments_to_provide
2278
+	 * @return string
2279
+	 */
2280
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2281
+	{
2282
+		/** @type WPDB $wpdb */
2283
+		global $wpdb;
2284
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2285
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2286
+		$error_message = sprintf(
2287
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2288
+				'event_espresso'),
2289
+			$wpdb->last_error,
2290
+			$wpdb_method,
2291
+			wp_json_encode($arguments_to_provide)
2292
+		);
2293
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2294
+		return $error_message;
2295
+	}
2296
+
2297
+
2298
+
2299
+	/**
2300
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2301
+	 * EEM_Base::$_db_verification_level
2302
+	 *
2303
+	 * @param $wpdb_method
2304
+	 * @param $arguments_to_provide
2305
+	 * @return string
2306
+	 */
2307
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2308
+	{
2309
+		/** @type WPDB $wpdb */
2310
+		global $wpdb;
2311
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2312
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2313
+		$error_message = sprintf(
2314
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2315
+				'event_espresso'),
2316
+			$wpdb->last_error,
2317
+			$wpdb_method,
2318
+			wp_json_encode($arguments_to_provide)
2319
+		);
2320
+		EE_System::instance()->initialize_addons();
2321
+		return $error_message;
2322
+	}
2323
+
2324
+
2325
+
2326
+	/**
2327
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2328
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2329
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2330
+	 * ..."
2331
+	 *
2332
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2333
+	 * @return string
2334
+	 */
2335
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2336
+	{
2337
+		return " FROM " . $model_query_info->get_full_join_sql() .
2338
+			   $model_query_info->get_where_sql() .
2339
+			   $model_query_info->get_group_by_sql() .
2340
+			   $model_query_info->get_having_sql() .
2341
+			   $model_query_info->get_order_by_sql() .
2342
+			   $model_query_info->get_limit_sql();
2343
+	}
2344
+
2345
+
2346
+
2347
+	/**
2348
+	 * Set to easily debug the next X queries ran from this model.
2349
+	 *
2350
+	 * @param int $count
2351
+	 */
2352
+	public function show_next_x_db_queries($count = 1)
2353
+	{
2354
+		$this->_show_next_x_db_queries = $count;
2355
+	}
2356
+
2357
+
2358
+
2359
+	/**
2360
+	 * @param $sql_query
2361
+	 */
2362
+	public function show_db_query_if_previously_requested($sql_query)
2363
+	{
2364
+		if ($this->_show_next_x_db_queries > 0) {
2365
+			echo $sql_query;
2366
+			$this->_show_next_x_db_queries--;
2367
+		}
2368
+	}
2369
+
2370
+
2371
+
2372
+	/**
2373
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2374
+	 * There are the 3 cases:
2375
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2376
+	 * $otherModelObject has no ID, it is first saved.
2377
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2378
+	 * has no ID, it is first saved.
2379
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2380
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2381
+	 * join table
2382
+	 *
2383
+	 * @param        EE_Base_Class                     /int $thisModelObject
2384
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2385
+	 * @param string $relationName                     , key in EEM_Base::_relations
2386
+	 *                                                 an attendee to a group, you also want to specify which role they
2387
+	 *                                                 will have in that group. So you would use this parameter to
2388
+	 *                                                 specify array('role-column-name'=>'role-id')
2389
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2390
+	 *                                                 to for relation to methods that allow you to further specify
2391
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2392
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2393
+	 *                                                 because these will be inserted in any new rows created as well.
2394
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2395
+	 * @throws \EE_Error
2396
+	 */
2397
+	public function add_relationship_to(
2398
+		$id_or_obj,
2399
+		$other_model_id_or_obj,
2400
+		$relationName,
2401
+		$extra_join_model_fields_n_values = array()
2402
+	) {
2403
+		$relation_obj = $this->related_settings_for($relationName);
2404
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2405
+	}
2406
+
2407
+
2408
+
2409
+	/**
2410
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2411
+	 * There are the 3 cases:
2412
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2413
+	 * error
2414
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2415
+	 * an error
2416
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2417
+	 *
2418
+	 * @param        EE_Base_Class /int $id_or_obj
2419
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2420
+	 * @param string $relationName key in EEM_Base::_relations
2421
+	 * @return boolean of success
2422
+	 * @throws \EE_Error
2423
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2424
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2425
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2426
+	 *                             because these will be inserted in any new rows created as well.
2427
+	 */
2428
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2429
+	{
2430
+		$relation_obj = $this->related_settings_for($relationName);
2431
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2432
+	}
2433
+
2434
+
2435
+
2436
+	/**
2437
+	 * @param mixed           $id_or_obj
2438
+	 * @param string          $relationName
2439
+	 * @param array           $where_query_params
2440
+	 * @param EE_Base_Class[] objects to which relations were removed
2441
+	 * @return \EE_Base_Class[]
2442
+	 * @throws \EE_Error
2443
+	 */
2444
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2445
+	{
2446
+		$relation_obj = $this->related_settings_for($relationName);
2447
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2448
+	}
2449
+
2450
+
2451
+
2452
+	/**
2453
+	 * Gets all the related items of the specified $model_name, using $query_params.
2454
+	 * Note: by default, we remove the "default query params"
2455
+	 * because we want to get even deleted items etc.
2456
+	 *
2457
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2458
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2459
+	 * @param array  $query_params like EEM_Base::get_all
2460
+	 * @return EE_Base_Class[]
2461
+	 * @throws \EE_Error
2462
+	 */
2463
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2464
+	{
2465
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2466
+		$relation_settings = $this->related_settings_for($model_name);
2467
+		return $relation_settings->get_all_related($model_obj, $query_params);
2468
+	}
2469
+
2470
+
2471
+
2472
+	/**
2473
+	 * Deletes all the model objects across the relation indicated by $model_name
2474
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2475
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2476
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2477
+	 *
2478
+	 * @param EE_Base_Class|int|string $id_or_obj
2479
+	 * @param string                   $model_name
2480
+	 * @param array                    $query_params
2481
+	 * @return int how many deleted
2482
+	 * @throws \EE_Error
2483
+	 */
2484
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2485
+	{
2486
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2487
+		$relation_settings = $this->related_settings_for($model_name);
2488
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2489
+	}
2490
+
2491
+
2492
+
2493
+	/**
2494
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2495
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2496
+	 * the model objects can't be hard deleted because of blocking related model objects,
2497
+	 * just does a soft-delete on them instead.
2498
+	 *
2499
+	 * @param EE_Base_Class|int|string $id_or_obj
2500
+	 * @param string                   $model_name
2501
+	 * @param array                    $query_params
2502
+	 * @return int how many deleted
2503
+	 * @throws \EE_Error
2504
+	 */
2505
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2506
+	{
2507
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2508
+		$relation_settings = $this->related_settings_for($model_name);
2509
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2510
+	}
2511
+
2512
+
2513
+
2514
+	/**
2515
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2516
+	 * unless otherwise specified in the $query_params
2517
+	 *
2518
+	 * @param        int             /EE_Base_Class $id_or_obj
2519
+	 * @param string $model_name     like 'Event', or 'Registration'
2520
+	 * @param array  $query_params   like EEM_Base::get_all's
2521
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2522
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2523
+	 *                               that by the setting $distinct to TRUE;
2524
+	 * @return int
2525
+	 * @throws \EE_Error
2526
+	 */
2527
+	public function count_related(
2528
+		$id_or_obj,
2529
+		$model_name,
2530
+		$query_params = array(),
2531
+		$field_to_count = null,
2532
+		$distinct = false
2533
+	) {
2534
+		$related_model = $this->get_related_model_obj($model_name);
2535
+		//we're just going to use the query params on the related model's normal get_all query,
2536
+		//except add a condition to say to match the current mod
2537
+		if (! isset($query_params['default_where_conditions'])) {
2538
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2539
+		}
2540
+		$this_model_name = $this->get_this_model_name();
2541
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2542
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2543
+		return $related_model->count($query_params, $field_to_count, $distinct);
2544
+	}
2545
+
2546
+
2547
+
2548
+	/**
2549
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2550
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2551
+	 *
2552
+	 * @param        int           /EE_Base_Class $id_or_obj
2553
+	 * @param string $model_name   like 'Event', or 'Registration'
2554
+	 * @param array  $query_params like EEM_Base::get_all's
2555
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2556
+	 * @return float
2557
+	 * @throws \EE_Error
2558
+	 */
2559
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2560
+	{
2561
+		$related_model = $this->get_related_model_obj($model_name);
2562
+		if (! is_array($query_params)) {
2563
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2564
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2565
+					gettype($query_params)), '4.6.0');
2566
+			$query_params = array();
2567
+		}
2568
+		//we're just going to use the query params on the related model's normal get_all query,
2569
+		//except add a condition to say to match the current mod
2570
+		if (! isset($query_params['default_where_conditions'])) {
2571
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2572
+		}
2573
+		$this_model_name = $this->get_this_model_name();
2574
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2575
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2576
+		return $related_model->sum($query_params, $field_to_sum);
2577
+	}
2578
+
2579
+
2580
+
2581
+	/**
2582
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2583
+	 * $modelObject
2584
+	 *
2585
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2586
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2587
+	 * @param array               $query_params     like EEM_Base::get_all's
2588
+	 * @return EE_Base_Class
2589
+	 * @throws \EE_Error
2590
+	 */
2591
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2592
+	{
2593
+		$query_params['limit'] = 1;
2594
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2595
+		if ($results) {
2596
+			return array_shift($results);
2597
+		} else {
2598
+			return null;
2599
+		}
2600
+	}
2601
+
2602
+
2603
+
2604
+	/**
2605
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2606
+	 *
2607
+	 * @return string
2608
+	 */
2609
+	public function get_this_model_name()
2610
+	{
2611
+		return str_replace("EEM_", "", get_class($this));
2612
+	}
2613
+
2614
+
2615
+
2616
+	/**
2617
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2618
+	 *
2619
+	 * @return EE_Any_Foreign_Model_Name_Field
2620
+	 * @throws EE_Error
2621
+	 */
2622
+	public function get_field_containing_related_model_name()
2623
+	{
2624
+		foreach ($this->field_settings(true) as $field) {
2625
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2626
+				$field_with_model_name = $field;
2627
+			}
2628
+		}
2629
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2630
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2631
+				$this->get_this_model_name()));
2632
+		}
2633
+		return $field_with_model_name;
2634
+	}
2635
+
2636
+
2637
+
2638
+	/**
2639
+	 * Inserts a new entry into the database, for each table.
2640
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2641
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2642
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2643
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2644
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2645
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2646
+	 *
2647
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2648
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2649
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2650
+	 *                              of EEM_Base)
2651
+	 * @return int new primary key on main table that got inserted
2652
+	 * @throws EE_Error
2653
+	 */
2654
+	public function insert($field_n_values)
2655
+	{
2656
+		/**
2657
+		 * Filters the fields and their values before inserting an item using the models
2658
+		 *
2659
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2660
+		 * @param EEM_Base $model           the model used
2661
+		 */
2662
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2663
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2664
+			$main_table = $this->_get_main_table();
2665
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2666
+			if ($new_id !== false) {
2667
+				foreach ($this->_get_other_tables() as $other_table) {
2668
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2669
+				}
2670
+			}
2671
+			/**
2672
+			 * Done just after attempting to insert a new model object
2673
+			 *
2674
+			 * @param EEM_Base   $model           used
2675
+			 * @param array      $fields_n_values fields and their values
2676
+			 * @param int|string the              ID of the newly-inserted model object
2677
+			 */
2678
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2679
+			return $new_id;
2680
+		} else {
2681
+			return false;
2682
+		}
2683
+	}
2684
+
2685
+
2686
+
2687
+	/**
2688
+	 * Checks that the result would satisfy the unique indexes on this model
2689
+	 *
2690
+	 * @param array  $field_n_values
2691
+	 * @param string $action
2692
+	 * @return boolean
2693
+	 * @throws \EE_Error
2694
+	 */
2695
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2696
+	{
2697
+		foreach ($this->unique_indexes() as $index_name => $index) {
2698
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2699
+			if ($this->exists(array($uniqueness_where_params))) {
2700
+				EE_Error::add_error(
2701
+					sprintf(
2702
+						__(
2703
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2704
+							"event_espresso"
2705
+						),
2706
+						$action,
2707
+						$this->_get_class_name(),
2708
+						$index_name,
2709
+						implode(",", $index->field_names()),
2710
+						http_build_query($uniqueness_where_params)
2711
+					),
2712
+					__FILE__,
2713
+					__FUNCTION__,
2714
+					__LINE__
2715
+				);
2716
+				return false;
2717
+			}
2718
+		}
2719
+		return true;
2720
+	}
2721
+
2722
+
2723
+
2724
+	/**
2725
+	 * Checks the database for an item that conflicts (ie, if this item were
2726
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2727
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2728
+	 * can be either an EE_Base_Class or an array of fields n values
2729
+	 *
2730
+	 * @param EE_Base_Class|array $obj_or_fields_array
2731
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2732
+	 *                                                 when looking for conflicts
2733
+	 *                                                 (ie, if false, we ignore the model object's primary key
2734
+	 *                                                 when finding "conflicts". If true, it's also considered).
2735
+	 *                                                 Only works for INT primary key,
2736
+	 *                                                 STRING primary keys cannot be ignored
2737
+	 * @throws EE_Error
2738
+	 * @return EE_Base_Class|array
2739
+	 */
2740
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2741
+	{
2742
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2743
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2744
+		} elseif (is_array($obj_or_fields_array)) {
2745
+			$fields_n_values = $obj_or_fields_array;
2746
+		} else {
2747
+			throw new EE_Error(
2748
+				sprintf(
2749
+					__(
2750
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2751
+						"event_espresso"
2752
+					),
2753
+					get_class($this),
2754
+					$obj_or_fields_array
2755
+				)
2756
+			);
2757
+		}
2758
+		$query_params = array();
2759
+		if ($this->has_primary_key_field()
2760
+			&& ($include_primary_key
2761
+				|| $this->get_primary_key_field()
2762
+				   instanceof
2763
+				   EE_Primary_Key_String_Field)
2764
+			&& isset($fields_n_values[$this->primary_key_name()])
2765
+		) {
2766
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2767
+		}
2768
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2769
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2770
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2771
+		}
2772
+		//if there is nothing to base this search on, then we shouldn't find anything
2773
+		if (empty($query_params)) {
2774
+			return array();
2775
+		} else {
2776
+			return $this->get_one($query_params);
2777
+		}
2778
+	}
2779
+
2780
+
2781
+
2782
+	/**
2783
+	 * Like count, but is optimized and returns a boolean instead of an int
2784
+	 *
2785
+	 * @param array $query_params
2786
+	 * @return boolean
2787
+	 * @throws \EE_Error
2788
+	 */
2789
+	public function exists($query_params)
2790
+	{
2791
+		$query_params['limit'] = 1;
2792
+		return $this->count($query_params) > 0;
2793
+	}
2794
+
2795
+
2796
+
2797
+	/**
2798
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2799
+	 *
2800
+	 * @param int|string $id
2801
+	 * @return boolean
2802
+	 * @throws \EE_Error
2803
+	 */
2804
+	public function exists_by_ID($id)
2805
+	{
2806
+		return $this->exists(
2807
+			array(
2808
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2809
+				array(
2810
+					$this->primary_key_name() => $id,
2811
+				),
2812
+			)
2813
+		);
2814
+	}
2815
+
2816
+
2817
+
2818
+	/**
2819
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2820
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2821
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2822
+	 * on the main table)
2823
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2824
+	 * cases where we want to call it directly rather than via insert().
2825
+	 *
2826
+	 * @access   protected
2827
+	 * @param EE_Table_Base $table
2828
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2829
+	 *                                       float
2830
+	 * @param int           $new_id          for now we assume only int keys
2831
+	 * @throws EE_Error
2832
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2833
+	 * @return int ID of new row inserted, or FALSE on failure
2834
+	 */
2835
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2836
+	{
2837
+		global $wpdb;
2838
+		$insertion_col_n_values = array();
2839
+		$format_for_insertion = array();
2840
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2841
+		foreach ($fields_on_table as $field_name => $field_obj) {
2842
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2843
+			if ($field_obj->is_auto_increment()) {
2844
+				continue;
2845
+			}
2846
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2847
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2848
+			if ($prepared_value !== null) {
2849
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2850
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2851
+			}
2852
+		}
2853
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2854
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2855
+			//so add the fk to the main table as a column
2856
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2857
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2858
+		}
2859
+		//insert the new entry
2860
+		$result = $this->_do_wpdb_query('insert',
2861
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2862
+		if ($result === false) {
2863
+			return false;
2864
+		}
2865
+		//ok, now what do we return for the ID of the newly-inserted thing?
2866
+		if ($this->has_primary_key_field()) {
2867
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2868
+				return $wpdb->insert_id;
2869
+			} else {
2870
+				//it's not an auto-increment primary key, so
2871
+				//it must have been supplied
2872
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2873
+			}
2874
+		} else {
2875
+			//we can't return a  primary key because there is none. instead return
2876
+			//a unique string indicating this model
2877
+			return $this->get_index_primary_key_string($fields_n_values);
2878
+		}
2879
+	}
2880
+
2881
+
2882
+
2883
+	/**
2884
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2885
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2886
+	 * and there is no default, we pass it along. WPDB will take care of it)
2887
+	 *
2888
+	 * @param EE_Model_Field_Base $field_obj
2889
+	 * @param array               $fields_n_values
2890
+	 * @return mixed string|int|float depending on what the table column will be expecting
2891
+	 * @throws \EE_Error
2892
+	 */
2893
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2894
+	{
2895
+		//if this field doesn't allow nullable, don't allow it
2896
+		if (! $field_obj->is_nullable()
2897
+			&& (
2898
+				! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2899
+		) {
2900
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2901
+		}
2902
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2903
+			: null;
2904
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2905
+	}
2906
+
2907
+
2908
+
2909
+	/**
2910
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2911
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2912
+	 * the field's prepare_for_set() method.
2913
+	 *
2914
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2915
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2916
+	 *                                   top of file)
2917
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2918
+	 *                                   $value is a custom selection
2919
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2920
+	 */
2921
+	private function _prepare_value_for_use_in_db($value, $field)
2922
+	{
2923
+		if ($field && $field instanceof EE_Model_Field_Base) {
2924
+			switch ($this->_values_already_prepared_by_model_object) {
2925
+				/** @noinspection PhpMissingBreakStatementInspection */
2926
+				case self::not_prepared_by_model_object:
2927
+					$value = $field->prepare_for_set($value);
2928
+				//purposefully left out "return"
2929
+				case self::prepared_by_model_object:
2930
+					$value = $field->prepare_for_use_in_db($value);
2931
+				case self::prepared_for_use_in_db:
2932
+					//leave the value alone
2933
+			}
2934
+			return $value;
2935
+		} else {
2936
+			return $value;
2937
+		}
2938
+	}
2939
+
2940
+
2941
+
2942
+	/**
2943
+	 * Returns the main table on this model
2944
+	 *
2945
+	 * @return EE_Primary_Table
2946
+	 * @throws EE_Error
2947
+	 */
2948
+	protected function _get_main_table()
2949
+	{
2950
+		foreach ($this->_tables as $table) {
2951
+			if ($table instanceof EE_Primary_Table) {
2952
+				return $table;
2953
+			}
2954
+		}
2955
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2956
+			'event_espresso'), get_class($this)));
2957
+	}
2958
+
2959
+
2960
+
2961
+	/**
2962
+	 * table
2963
+	 * returns EE_Primary_Table table name
2964
+	 *
2965
+	 * @return string
2966
+	 * @throws \EE_Error
2967
+	 */
2968
+	public function table()
2969
+	{
2970
+		return $this->_get_main_table()->get_table_name();
2971
+	}
2972
+
2973
+
2974
+
2975
+	/**
2976
+	 * table
2977
+	 * returns first EE_Secondary_Table table name
2978
+	 *
2979
+	 * @return string
2980
+	 */
2981
+	public function second_table()
2982
+	{
2983
+		// grab second table from tables array
2984
+		$second_table = end($this->_tables);
2985
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2986
+	}
2987
+
2988
+
2989
+
2990
+	/**
2991
+	 * get_table_obj_by_alias
2992
+	 * returns table name given it's alias
2993
+	 *
2994
+	 * @param string $table_alias
2995
+	 * @return EE_Primary_Table | EE_Secondary_Table
2996
+	 */
2997
+	public function get_table_obj_by_alias($table_alias = '')
2998
+	{
2999
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3000
+	}
3001
+
3002
+
3003
+
3004
+	/**
3005
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3006
+	 *
3007
+	 * @return EE_Secondary_Table[]
3008
+	 */
3009
+	protected function _get_other_tables()
3010
+	{
3011
+		$other_tables = array();
3012
+		foreach ($this->_tables as $table_alias => $table) {
3013
+			if ($table instanceof EE_Secondary_Table) {
3014
+				$other_tables[$table_alias] = $table;
3015
+			}
3016
+		}
3017
+		return $other_tables;
3018
+	}
3019
+
3020
+
3021
+
3022
+	/**
3023
+	 * Finds all the fields that correspond to the given table
3024
+	 *
3025
+	 * @param string $table_alias , array key in EEM_Base::_tables
3026
+	 * @return EE_Model_Field_Base[]
3027
+	 */
3028
+	public function _get_fields_for_table($table_alias)
3029
+	{
3030
+		return $this->_fields[$table_alias];
3031
+	}
3032
+
3033
+
3034
+
3035
+	/**
3036
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3037
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3038
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3039
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3040
+	 * related Registration, Transaction, and Payment models.
3041
+	 *
3042
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3043
+	 * @return EE_Model_Query_Info_Carrier
3044
+	 * @throws \EE_Error
3045
+	 */
3046
+	public function _extract_related_models_from_query($query_params)
3047
+	{
3048
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3049
+		if (array_key_exists(0, $query_params)) {
3050
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3051
+		}
3052
+		if (array_key_exists('group_by', $query_params)) {
3053
+			if (is_array($query_params['group_by'])) {
3054
+				$this->_extract_related_models_from_sub_params_array_values(
3055
+					$query_params['group_by'],
3056
+					$query_info_carrier,
3057
+					'group_by'
3058
+				);
3059
+			} elseif (! empty ($query_params['group_by'])) {
3060
+				$this->_extract_related_model_info_from_query_param(
3061
+					$query_params['group_by'],
3062
+					$query_info_carrier,
3063
+					'group_by'
3064
+				);
3065
+			}
3066
+		}
3067
+		if (array_key_exists('having', $query_params)) {
3068
+			$this->_extract_related_models_from_sub_params_array_keys(
3069
+				$query_params[0],
3070
+				$query_info_carrier,
3071
+				'having'
3072
+			);
3073
+		}
3074
+		if (array_key_exists('order_by', $query_params)) {
3075
+			if (is_array($query_params['order_by'])) {
3076
+				$this->_extract_related_models_from_sub_params_array_keys(
3077
+					$query_params['order_by'],
3078
+					$query_info_carrier,
3079
+					'order_by'
3080
+				);
3081
+			} elseif (! empty($query_params['order_by'])) {
3082
+				$this->_extract_related_model_info_from_query_param(
3083
+					$query_params['order_by'],
3084
+					$query_info_carrier,
3085
+					'order_by'
3086
+				);
3087
+			}
3088
+		}
3089
+		if (array_key_exists('force_join', $query_params)) {
3090
+			$this->_extract_related_models_from_sub_params_array_values(
3091
+				$query_params['force_join'],
3092
+				$query_info_carrier,
3093
+				'force_join'
3094
+			);
3095
+		}
3096
+		return $query_info_carrier;
3097
+	}
3098
+
3099
+
3100
+
3101
+	/**
3102
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3103
+	 *
3104
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3105
+	 *                                                      $query_params['having']
3106
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3107
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3108
+	 * @throws EE_Error
3109
+	 * @return \EE_Model_Query_Info_Carrier
3110
+	 */
3111
+	private function _extract_related_models_from_sub_params_array_keys(
3112
+		$sub_query_params,
3113
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3114
+		$query_param_type
3115
+	) {
3116
+		if (! empty($sub_query_params)) {
3117
+			$sub_query_params = (array)$sub_query_params;
3118
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3119
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3120
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3121
+					$query_param_type);
3122
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3123
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3124
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3125
+				//of array('Registration.TXN_ID'=>23)
3126
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3127
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3128
+					if (! is_array($possibly_array_of_params)) {
3129
+						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'))",
3130
+							"event_espresso"),
3131
+							$param, $possibly_array_of_params));
3132
+					} else {
3133
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3134
+							$model_query_info_carrier, $query_param_type);
3135
+					}
3136
+				} elseif ($query_param_type === 0 //ie WHERE
3137
+						  && is_array($possibly_array_of_params)
3138
+						  && isset($possibly_array_of_params[2])
3139
+						  && $possibly_array_of_params[2] == true
3140
+				) {
3141
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3142
+					//indicating that $possible_array_of_params[1] is actually a field name,
3143
+					//from which we should extract query parameters!
3144
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3145
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3146
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3147
+					}
3148
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3149
+						$model_query_info_carrier, $query_param_type);
3150
+				}
3151
+			}
3152
+		}
3153
+		return $model_query_info_carrier;
3154
+	}
3155
+
3156
+
3157
+
3158
+	/**
3159
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3160
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3161
+	 *
3162
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3163
+	 *                                                      $query_params['having']
3164
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3165
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3166
+	 * @throws EE_Error
3167
+	 * @return \EE_Model_Query_Info_Carrier
3168
+	 */
3169
+	private function _extract_related_models_from_sub_params_array_values(
3170
+		$sub_query_params,
3171
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3172
+		$query_param_type
3173
+	) {
3174
+		if (! empty($sub_query_params)) {
3175
+			if (! is_array($sub_query_params)) {
3176
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3177
+					$sub_query_params));
3178
+			}
3179
+			foreach ($sub_query_params as $param) {
3180
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3181
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3182
+					$query_param_type);
3183
+			}
3184
+		}
3185
+		return $model_query_info_carrier;
3186
+	}
3187
+
3188
+
3189
+
3190
+	/**
3191
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3192
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3193
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3194
+	 * but use them in a different order. Eg, we need to know what models we are querying
3195
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3196
+	 * other models before we can finalize the where clause SQL.
3197
+	 *
3198
+	 * @param array $query_params
3199
+	 * @throws EE_Error
3200
+	 * @return EE_Model_Query_Info_Carrier
3201
+	 */
3202
+	public function _create_model_query_info_carrier($query_params)
3203
+	{
3204
+		if (! is_array($query_params)) {
3205
+			EE_Error::doing_it_wrong(
3206
+				'EEM_Base::_create_model_query_info_carrier',
3207
+				sprintf(
3208
+					__(
3209
+						'$query_params should be an array, you passed a variable of type %s',
3210
+						'event_espresso'
3211
+					),
3212
+					gettype($query_params)
3213
+				),
3214
+				'4.6.0'
3215
+			);
3216
+			$query_params = array();
3217
+		}
3218
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3219
+		//first check if we should alter the query to account for caps or not
3220
+		//because the caps might require us to do extra joins
3221
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3222
+			$query_params[0] = $where_query_params = array_replace_recursive(
3223
+				$where_query_params,
3224
+				$this->caps_where_conditions(
3225
+					$query_params['caps']
3226
+				)
3227
+			);
3228
+		}
3229
+		$query_object = $this->_extract_related_models_from_query($query_params);
3230
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3231
+		foreach ($where_query_params as $key => $value) {
3232
+			if (is_int($key)) {
3233
+				throw new EE_Error(
3234
+					sprintf(
3235
+						__(
3236
+							"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.",
3237
+							"event_espresso"
3238
+						),
3239
+						$key,
3240
+						var_export($value, true),
3241
+						var_export($query_params, true),
3242
+						get_class($this)
3243
+					)
3244
+				);
3245
+			}
3246
+		}
3247
+		if (
3248
+			array_key_exists('default_where_conditions', $query_params)
3249
+			&& ! empty($query_params['default_where_conditions'])
3250
+		) {
3251
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3252
+		} else {
3253
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3254
+		}
3255
+		$where_query_params = array_merge(
3256
+			$this->_get_default_where_conditions_for_models_in_query(
3257
+				$query_object,
3258
+				$use_default_where_conditions,
3259
+				$where_query_params
3260
+			),
3261
+			$where_query_params
3262
+		);
3263
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3264
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3265
+		// So we need to setup a subquery and use that for the main join.
3266
+		// Note for now this only works on the primary table for the model.
3267
+		// So for instance, you could set the limit array like this:
3268
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3269
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3270
+			$query_object->set_main_model_join_sql(
3271
+				$this->_construct_limit_join_select(
3272
+					$query_params['on_join_limit'][0],
3273
+					$query_params['on_join_limit'][1]
3274
+				)
3275
+			);
3276
+		}
3277
+		//set limit
3278
+		if (array_key_exists('limit', $query_params)) {
3279
+			if (is_array($query_params['limit'])) {
3280
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3281
+					$e = sprintf(
3282
+						__(
3283
+							"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)",
3284
+							"event_espresso"
3285
+						),
3286
+						http_build_query($query_params['limit'])
3287
+					);
3288
+					throw new EE_Error($e . "|" . $e);
3289
+				}
3290
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3291
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3292
+			} elseif (! empty ($query_params['limit'])) {
3293
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3294
+			}
3295
+		}
3296
+		//set order by
3297
+		if (array_key_exists('order_by', $query_params)) {
3298
+			if (is_array($query_params['order_by'])) {
3299
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3300
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3301
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3302
+				if (array_key_exists('order', $query_params)) {
3303
+					throw new EE_Error(
3304
+						sprintf(
3305
+							__(
3306
+								"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 ",
3307
+								"event_espresso"
3308
+							),
3309
+							get_class($this),
3310
+							implode(", ", array_keys($query_params['order_by'])),
3311
+							implode(", ", $query_params['order_by']),
3312
+							$query_params['order']
3313
+						)
3314
+					);
3315
+				}
3316
+				$this->_extract_related_models_from_sub_params_array_keys(
3317
+					$query_params['order_by'],
3318
+					$query_object,
3319
+					'order_by'
3320
+				);
3321
+				//assume it's an array of fields to order by
3322
+				$order_array = array();
3323
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3324
+					$order = $this->_extract_order($order);
3325
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3326
+				}
3327
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3328
+			} elseif (! empty ($query_params['order_by'])) {
3329
+				$this->_extract_related_model_info_from_query_param(
3330
+					$query_params['order_by'],
3331
+					$query_object,
3332
+					'order',
3333
+					$query_params['order_by']
3334
+				);
3335
+				$order = isset($query_params['order'])
3336
+					? $this->_extract_order($query_params['order'])
3337
+					: 'DESC';
3338
+				$query_object->set_order_by_sql(
3339
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3340
+				);
3341
+			}
3342
+		}
3343
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3344
+		if (! array_key_exists('order_by', $query_params)
3345
+			&& array_key_exists('order', $query_params)
3346
+			&& ! empty($query_params['order'])
3347
+		) {
3348
+			$pk_field = $this->get_primary_key_field();
3349
+			$order = $this->_extract_order($query_params['order']);
3350
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3351
+		}
3352
+		//set group by
3353
+		if (array_key_exists('group_by', $query_params)) {
3354
+			if (is_array($query_params['group_by'])) {
3355
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3356
+				$group_by_array = array();
3357
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3358
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3359
+				}
3360
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3361
+			} elseif (! empty ($query_params['group_by'])) {
3362
+				$query_object->set_group_by_sql(
3363
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3364
+				);
3365
+			}
3366
+		}
3367
+		//set having
3368
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3369
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3370
+		}
3371
+		//now, just verify they didn't pass anything wack
3372
+		foreach ($query_params as $query_key => $query_value) {
3373
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3374
+				throw new EE_Error(
3375
+					sprintf(
3376
+						__(
3377
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3378
+							'event_espresso'
3379
+						),
3380
+						$query_key,
3381
+						get_class($this),
3382
+						//						print_r( $this->_allowed_query_params, TRUE )
3383
+						implode(',', $this->_allowed_query_params)
3384
+					)
3385
+				);
3386
+			}
3387
+		}
3388
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3389
+		if (empty($main_model_join_sql)) {
3390
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3391
+		}
3392
+		return $query_object;
3393
+	}
3394
+
3395
+
3396
+
3397
+	/**
3398
+	 * Gets the where conditions that should be imposed on the query based on the
3399
+	 * context (eg reading frontend, backend, edit or delete).
3400
+	 *
3401
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3402
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3403
+	 * @throws \EE_Error
3404
+	 */
3405
+	public function caps_where_conditions($context = self::caps_read)
3406
+	{
3407
+		EEM_Base::verify_is_valid_cap_context($context);
3408
+		$cap_where_conditions = array();
3409
+		$cap_restrictions = $this->caps_missing($context);
3410
+		/**
3411
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3412
+		 */
3413
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3414
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3415
+				$restriction_if_no_cap->get_default_where_conditions());
3416
+		}
3417
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3418
+			$cap_restrictions);
3419
+	}
3420
+
3421
+
3422
+
3423
+	/**
3424
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3425
+	 * otherwise throws an exception
3426
+	 *
3427
+	 * @param string $should_be_order_string
3428
+	 * @return string either ASC, asc, DESC or desc
3429
+	 * @throws EE_Error
3430
+	 */
3431
+	private function _extract_order($should_be_order_string)
3432
+	{
3433
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3434
+			return $should_be_order_string;
3435
+		} else {
3436
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3437
+				"event_espresso"), get_class($this), $should_be_order_string));
3438
+		}
3439
+	}
3440
+
3441
+
3442
+
3443
+	/**
3444
+	 * Looks at all the models which are included in this query, and asks each
3445
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3446
+	 * so they can be merged
3447
+	 *
3448
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3449
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3450
+	 *                                                                  'none' means NO default where conditions will
3451
+	 *                                                                  be used AT ALL during this query.
3452
+	 *                                                                  'other_models_only' means default where
3453
+	 *                                                                  conditions from other models will be used, but
3454
+	 *                                                                  not for this primary model. 'all', the default,
3455
+	 *                                                                  means default where conditions will apply as
3456
+	 *                                                                  normal
3457
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3458
+	 * @throws EE_Error
3459
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3460
+	 */
3461
+	private function _get_default_where_conditions_for_models_in_query(
3462
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3463
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3464
+		$where_query_params = array()
3465
+	) {
3466
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3467
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3468
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3469
+				"event_espresso"), $use_default_where_conditions,
3470
+				implode(", ", $allowed_used_default_where_conditions_values)));
3471
+		}
3472
+		$universal_query_params = array();
3473
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3474
+			$universal_query_params = $this->_get_default_where_conditions();
3475
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3476
+			$universal_query_params = $this->_get_minimum_where_conditions();
3477
+		}
3478
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3479
+			$related_model = $this->get_related_model_obj($model_name);
3480
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3481
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3482
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3483
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3484
+			} else {
3485
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3486
+				continue;
3487
+			}
3488
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3489
+				$related_model_universal_where_params,
3490
+				$where_query_params,
3491
+				$related_model,
3492
+				$model_relation_path
3493
+			);
3494
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3495
+				$universal_query_params,
3496
+				$overrides
3497
+			);
3498
+		}
3499
+		return $universal_query_params;
3500
+	}
3501
+
3502
+
3503
+
3504
+	/**
3505
+	 * Determines whether or not we should use default where conditions for the model in question
3506
+	 * (this model, or other related models).
3507
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3508
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3509
+	 * We should use default where conditions on related models when they requested to use default where conditions
3510
+	 * on all models, or specifically just on other related models
3511
+	 * @param      $default_where_conditions_value
3512
+	 * @param bool $for_this_model false means this is for OTHER related models
3513
+	 * @return bool
3514
+	 */
3515
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3516
+	{
3517
+		return (
3518
+				   $for_this_model
3519
+				   && in_array(
3520
+					   $default_where_conditions_value,
3521
+					   array(
3522
+						   EEM_Base::default_where_conditions_all,
3523
+						   EEM_Base::default_where_conditions_this_only,
3524
+						   EEM_Base::default_where_conditions_minimum_others,
3525
+					   ),
3526
+					   true
3527
+				   )
3528
+			   )
3529
+			   || (
3530
+				   ! $for_this_model
3531
+				   && in_array(
3532
+					   $default_where_conditions_value,
3533
+					   array(
3534
+						   EEM_Base::default_where_conditions_all,
3535
+						   EEM_Base::default_where_conditions_others_only,
3536
+					   ),
3537
+					   true
3538
+				   )
3539
+			   );
3540
+	}
3541
+
3542
+	/**
3543
+	 * Determines whether or not we should use default minimum conditions for the model in question
3544
+	 * (this model, or other related models).
3545
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3546
+	 * where conditions.
3547
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3548
+	 * on this model or others
3549
+	 * @param      $default_where_conditions_value
3550
+	 * @param bool $for_this_model false means this is for OTHER related models
3551
+	 * @return bool
3552
+	 */
3553
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3554
+	{
3555
+		return (
3556
+				   $for_this_model
3557
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3558
+			   )
3559
+			   || (
3560
+				   ! $for_this_model
3561
+				   && in_array(
3562
+					   $default_where_conditions_value,
3563
+					   array(
3564
+						   EEM_Base::default_where_conditions_minimum_others,
3565
+						   EEM_Base::default_where_conditions_minimum_all,
3566
+					   ),
3567
+					   true
3568
+				   )
3569
+			   );
3570
+	}
3571
+
3572
+
3573
+	/**
3574
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3575
+	 * then we also add a special where condition which allows for that model's primary key
3576
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3577
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3578
+	 *
3579
+	 * @param array    $default_where_conditions
3580
+	 * @param array    $provided_where_conditions
3581
+	 * @param EEM_Base $model
3582
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3583
+	 * @return array like EEM_Base::get_all's $query_params[0]
3584
+	 * @throws \EE_Error
3585
+	 */
3586
+	private function _override_defaults_or_make_null_friendly(
3587
+		$default_where_conditions,
3588
+		$provided_where_conditions,
3589
+		$model,
3590
+		$model_relation_path
3591
+	) {
3592
+		$null_friendly_where_conditions = array();
3593
+		$none_overridden = true;
3594
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3595
+		foreach ($default_where_conditions as $key => $val) {
3596
+			if (isset($provided_where_conditions[$key])) {
3597
+				$none_overridden = false;
3598
+			} else {
3599
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3600
+			}
3601
+		}
3602
+		if ($none_overridden && $default_where_conditions) {
3603
+			if ($model->has_primary_key_field()) {
3604
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3605
+																				. "."
3606
+																				. $model->primary_key_name()] = array('IS NULL');
3607
+			}/*else{
3608 3608
 				//@todo NO PK, use other defaults
3609 3609
 			}*/
3610
-        }
3611
-        return $null_friendly_where_conditions;
3612
-    }
3613
-
3614
-
3615
-
3616
-    /**
3617
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3618
-     * default where conditions on all get_all, update, and delete queries done by this model.
3619
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3620
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3621
-     *
3622
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3623
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3624
-     */
3625
-    private function _get_default_where_conditions($model_relation_path = null)
3626
-    {
3627
-        if ($this->_ignore_where_strategy) {
3628
-            return array();
3629
-        }
3630
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3631
-    }
3632
-
3633
-
3634
-
3635
-    /**
3636
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3637
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3638
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3639
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3640
-     * Similar to _get_default_where_conditions
3641
-     *
3642
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3643
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3644
-     */
3645
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3646
-    {
3647
-        if ($this->_ignore_where_strategy) {
3648
-            return array();
3649
-        }
3650
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3651
-    }
3652
-
3653
-
3654
-
3655
-    /**
3656
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3657
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3658
-     *
3659
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3660
-     * @return string
3661
-     * @throws \EE_Error
3662
-     */
3663
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3664
-    {
3665
-        $selects = $this->_get_columns_to_select_for_this_model();
3666
-        foreach (
3667
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3668
-            $name_of_other_model_included
3669
-        ) {
3670
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3671
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3672
-            foreach ($other_model_selects as $key => $value) {
3673
-                $selects[] = $value;
3674
-            }
3675
-        }
3676
-        return implode(", ", $selects);
3677
-    }
3678
-
3679
-
3680
-
3681
-    /**
3682
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3683
-     * So that's going to be the columns for all the fields on the model
3684
-     *
3685
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3686
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3687
-     */
3688
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3689
-    {
3690
-        $fields = $this->field_settings();
3691
-        $selects = array();
3692
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3693
-            $this->get_this_model_name());
3694
-        foreach ($fields as $field_obj) {
3695
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3696
-                         . $field_obj->get_table_alias()
3697
-                         . "."
3698
-                         . $field_obj->get_table_column()
3699
-                         . " AS '"
3700
-                         . $table_alias_with_model_relation_chain_prefix
3701
-                         . $field_obj->get_table_alias()
3702
-                         . "."
3703
-                         . $field_obj->get_table_column()
3704
-                         . "'";
3705
-        }
3706
-        //make sure we are also getting the PKs of each table
3707
-        $tables = $this->get_tables();
3708
-        if (count($tables) > 1) {
3709
-            foreach ($tables as $table_obj) {
3710
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3711
-                                       . $table_obj->get_fully_qualified_pk_column();
3712
-                if (! in_array($qualified_pk_column, $selects)) {
3713
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3714
-                }
3715
-            }
3716
-        }
3717
-        return $selects;
3718
-    }
3719
-
3720
-
3721
-
3722
-    /**
3723
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3724
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3725
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3726
-     * SQL for joining, and the data types
3727
-     *
3728
-     * @param null|string                 $original_query_param
3729
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3730
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3731
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3732
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3733
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3734
-     *                                                          or 'Registration's
3735
-     * @param string                      $original_query_param what it originally was (eg
3736
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3737
-     *                                                          matches $query_param
3738
-     * @throws EE_Error
3739
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3740
-     */
3741
-    private function _extract_related_model_info_from_query_param(
3742
-        $query_param,
3743
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3744
-        $query_param_type,
3745
-        $original_query_param = null
3746
-    ) {
3747
-        if ($original_query_param === null) {
3748
-            $original_query_param = $query_param;
3749
-        }
3750
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3751
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3752
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3753
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3754
-        //check to see if we have a field on this model
3755
-        $this_model_fields = $this->field_settings(true);
3756
-        if (array_key_exists($query_param, $this_model_fields)) {
3757
-            if ($allow_fields) {
3758
-                return;
3759
-            } else {
3760
-                throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3761
-                    "event_espresso"),
3762
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3763
-            }
3764
-        } //check if this is a special logic query param
3765
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3766
-            if ($allow_logic_query_params) {
3767
-                return;
3768
-            } else {
3769
-                throw new EE_Error(
3770
-                    sprintf(
3771
-                        __('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',
3772
-                            'event_espresso'),
3773
-                        implode('", "', $this->_logic_query_param_keys),
3774
-                        $query_param,
3775
-                        get_class($this),
3776
-                        '<br />',
3777
-                        "\t"
3778
-                        . ' $passed_in_query_info = <pre>'
3779
-                        . print_r($passed_in_query_info, true)
3780
-                        . '</pre>'
3781
-                        . "\n\t"
3782
-                        . ' $query_param_type = '
3783
-                        . $query_param_type
3784
-                        . "\n\t"
3785
-                        . ' $original_query_param = '
3786
-                        . $original_query_param
3787
-                    )
3788
-                );
3789
-            }
3790
-        } //check if it's a custom selection
3791
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3792
-            return;
3793
-        }
3794
-        //check if has a model name at the beginning
3795
-        //and
3796
-        //check if it's a field on a related model
3797
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3798
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3799
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3800
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3801
-                if ($query_param === '') {
3802
-                    //nothing left to $query_param
3803
-                    //we should actually end in a field name, not a model like this!
3804
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3805
-                        "event_espresso"),
3806
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3807
-                } else {
3808
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3809
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3810
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3811
-                    return;
3812
-                }
3813
-            } elseif ($query_param === $valid_related_model_name) {
3814
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3815
-                return;
3816
-            }
3817
-        }
3818
-        //ok so $query_param didn't start with a model name
3819
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3820
-        //it's wack, that's what it is
3821
-        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",
3822
-            "event_espresso"),
3823
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3824
-    }
3825
-
3826
-
3827
-
3828
-    /**
3829
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3830
-     * and store it on $passed_in_query_info
3831
-     *
3832
-     * @param string                      $model_name
3833
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3834
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3835
-     *                                                          model and $model_name. Eg, if we are querying Event,
3836
-     *                                                          and are adding a join to 'Payment' with the original
3837
-     *                                                          query param key
3838
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3839
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3840
-     *                                                          Payment wants to add default query params so that it
3841
-     *                                                          will know what models to prepend onto its default query
3842
-     *                                                          params or in case it wants to rename tables (in case
3843
-     *                                                          there are multiple joins to the same table)
3844
-     * @return void
3845
-     * @throws \EE_Error
3846
-     */
3847
-    private function _add_join_to_model(
3848
-        $model_name,
3849
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3850
-        $original_query_param
3851
-    ) {
3852
-        $relation_obj = $this->related_settings_for($model_name);
3853
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3854
-        //check if the relation is HABTM, because then we're essentially doing two joins
3855
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3856
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3857
-            $join_model_obj = $relation_obj->get_join_model();
3858
-            //replace the model specified with the join model for this relation chain, whi
3859
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3860
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3861
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3862
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3863
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3864
-            $passed_in_query_info->merge($new_query_info);
3865
-        }
3866
-        //now just join to the other table pointed to by the relation object, and add its data types
3867
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3868
-            array($model_relation_chain => $model_name),
3869
-            $relation_obj->get_join_statement($model_relation_chain));
3870
-        $passed_in_query_info->merge($new_query_info);
3871
-    }
3872
-
3873
-
3874
-
3875
-    /**
3876
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3877
-     *
3878
-     * @param array $where_params like EEM_Base::get_all
3879
-     * @return string of SQL
3880
-     * @throws \EE_Error
3881
-     */
3882
-    private function _construct_where_clause($where_params)
3883
-    {
3884
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3885
-        if ($SQL) {
3886
-            return " WHERE " . $SQL;
3887
-        } else {
3888
-            return '';
3889
-        }
3890
-    }
3891
-
3892
-
3893
-
3894
-    /**
3895
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3896
-     * and should be passed HAVING parameters, not WHERE parameters
3897
-     *
3898
-     * @param array $having_params
3899
-     * @return string
3900
-     * @throws \EE_Error
3901
-     */
3902
-    private function _construct_having_clause($having_params)
3903
-    {
3904
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3905
-        if ($SQL) {
3906
-            return " HAVING " . $SQL;
3907
-        } else {
3908
-            return '';
3909
-        }
3910
-    }
3911
-
3912
-
3913
-
3914
-    /**
3915
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3916
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3917
-     * EEM_Attendee.
3918
-     *
3919
-     * @param string $field_name
3920
-     * @param string $model_name
3921
-     * @return EE_Model_Field_Base
3922
-     * @throws EE_Error
3923
-     */
3924
-    protected function _get_field_on_model($field_name, $model_name)
3925
-    {
3926
-        $model_class = 'EEM_' . $model_name;
3927
-        $model_filepath = $model_class . ".model.php";
3928
-        if (is_readable($model_filepath)) {
3929
-            require_once($model_filepath);
3930
-            $model_instance = call_user_func($model_name . "::instance");
3931
-            /* @var $model_instance EEM_Base */
3932
-            return $model_instance->field_settings_for($field_name);
3933
-        } else {
3934
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3935
-                'event_espresso'), $model_name, $model_class, $model_filepath));
3936
-        }
3937
-    }
3938
-
3939
-
3940
-
3941
-    /**
3942
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3943
-     * Event_Meta.meta_value = 'foo'))"
3944
-     *
3945
-     * @param array  $where_params see EEM_Base::get_all for documentation
3946
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3947
-     * @throws EE_Error
3948
-     * @return string of SQL
3949
-     */
3950
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3951
-    {
3952
-        $where_clauses = array();
3953
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3954
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3955
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3956
-                switch ($query_param) {
3957
-                    case 'not':
3958
-                    case 'NOT':
3959
-                        $where_clauses[] = "! ("
3960
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3961
-                                $glue)
3962
-                                           . ")";
3963
-                        break;
3964
-                    case 'and':
3965
-                    case 'AND':
3966
-                        $where_clauses[] = " ("
3967
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3968
-                                ' AND ')
3969
-                                           . ")";
3970
-                        break;
3971
-                    case 'or':
3972
-                    case 'OR':
3973
-                        $where_clauses[] = " ("
3974
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3975
-                                ' OR ')
3976
-                                           . ")";
3977
-                        break;
3978
-                }
3979
-            } else {
3980
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3981
-                //if it's not a normal field, maybe it's a custom selection?
3982
-                if (! $field_obj) {
3983
-                    if (isset($this->_custom_selections[$query_param][1])) {
3984
-                        $field_obj = $this->_custom_selections[$query_param][1];
3985
-                    } else {
3986
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3987
-                            "event_espresso"), $query_param));
3988
-                    }
3989
-                }
3990
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3991
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3992
-            }
3993
-        }
3994
-        return $where_clauses ? implode($glue, $where_clauses) : '';
3995
-    }
3996
-
3997
-
3998
-
3999
-    /**
4000
-     * Takes the input parameter and extract the table name (alias) and column name
4001
-     *
4002
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4003
-     * @throws EE_Error
4004
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4005
-     */
4006
-    private function _deduce_column_name_from_query_param($query_param)
4007
-    {
4008
-        $field = $this->_deduce_field_from_query_param($query_param);
4009
-        if ($field) {
4010
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4011
-                $query_param);
4012
-            return $table_alias_prefix . $field->get_qualified_column();
4013
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4014
-            //maybe it's custom selection item?
4015
-            //if so, just use it as the "column name"
4016
-            return $query_param;
4017
-        } else {
4018
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4019
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4020
-        }
4021
-    }
4022
-
4023
-
4024
-
4025
-    /**
4026
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4027
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4028
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4029
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4030
-     *
4031
-     * @param string $condition_query_param_key
4032
-     * @return string
4033
-     */
4034
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4035
-    {
4036
-        $pos_of_star = strpos($condition_query_param_key, '*');
4037
-        if ($pos_of_star === false) {
4038
-            return $condition_query_param_key;
4039
-        } else {
4040
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4041
-            return $condition_query_param_sans_star;
4042
-        }
4043
-    }
4044
-
4045
-
4046
-
4047
-    /**
4048
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4049
-     *
4050
-     * @param                            mixed      array | string    $op_and_value
4051
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4052
-     * @throws EE_Error
4053
-     * @return string
4054
-     */
4055
-    private function _construct_op_and_value($op_and_value, $field_obj)
4056
-    {
4057
-        if (is_array($op_and_value)) {
4058
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4059
-            if (! $operator) {
4060
-                $php_array_like_string = array();
4061
-                foreach ($op_and_value as $key => $value) {
4062
-                    $php_array_like_string[] = "$key=>$value";
4063
-                }
4064
-                throw new EE_Error(
4065
-                    sprintf(
4066
-                        __(
4067
-                            "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))",
4068
-                            "event_espresso"
4069
-                        ),
4070
-                        implode(",", $php_array_like_string)
4071
-                    )
4072
-                );
4073
-            }
4074
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4075
-        } else {
4076
-            $operator = '=';
4077
-            $value = $op_and_value;
4078
-        }
4079
-        //check to see if the value is actually another field
4080
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4081
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4082
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4083
-            //in this case, the value should be an array, or at least a comma-separated list
4084
-            //it will need to handle a little differently
4085
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4086
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4087
-            return $operator . SP . $cleaned_value;
4088
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4089
-            //the value should be an array with count of two.
4090
-            if (count($value) !== 2) {
4091
-                throw new EE_Error(
4092
-                    sprintf(
4093
-                        __(
4094
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4095
-                            'event_espresso'
4096
-                        ),
4097
-                        "BETWEEN"
4098
-                    )
4099
-                );
4100
-            }
4101
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4102
-            return $operator . SP . $cleaned_value;
4103
-        } elseif (in_array($operator, $this->_null_style_operators)) {
4104
-            if ($value !== null) {
4105
-                throw new EE_Error(
4106
-                    sprintf(
4107
-                        __(
4108
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4109
-                            "event_espresso"
4110
-                        ),
4111
-                        $value,
4112
-                        $operator
4113
-                    )
4114
-                );
4115
-            }
4116
-            return $operator;
4117
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
4118
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4119
-            //remove other junk. So just treat it as a string.
4120
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4121
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4122
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4123
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4124
-            throw new EE_Error(
4125
-                sprintf(
4126
-                    __(
4127
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4128
-                        'event_espresso'
4129
-                    ),
4130
-                    $operator,
4131
-                    $operator
4132
-                )
4133
-            );
4134
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4135
-            throw new EE_Error(
4136
-                sprintf(
4137
-                    __(
4138
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4139
-                        'event_espresso'
4140
-                    ),
4141
-                    $operator,
4142
-                    $operator
4143
-                )
4144
-            );
4145
-        } else {
4146
-            throw new EE_Error(
4147
-                sprintf(
4148
-                    __(
4149
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4150
-                        "event_espresso"
4151
-                    ),
4152
-                    http_build_query($op_and_value)
4153
-                )
4154
-            );
4155
-        }
4156
-    }
4157
-
4158
-
4159
-
4160
-    /**
4161
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4162
-     *
4163
-     * @param array                      $values
4164
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4165
-     *                                              '%s'
4166
-     * @return string
4167
-     * @throws \EE_Error
4168
-     */
4169
-    public function _construct_between_value($values, $field_obj)
4170
-    {
4171
-        $cleaned_values = array();
4172
-        foreach ($values as $value) {
4173
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4174
-        }
4175
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4176
-    }
4177
-
4178
-
4179
-
4180
-    /**
4181
-     * Takes an array or a comma-separated list of $values and cleans them
4182
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4183
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4184
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4185
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4186
-     *
4187
-     * @param mixed                      $values    array or comma-separated string
4188
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4189
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4190
-     * @throws \EE_Error
4191
-     */
4192
-    public function _construct_in_value($values, $field_obj)
4193
-    {
4194
-        //check if the value is a CSV list
4195
-        if (is_string($values)) {
4196
-            //in which case, turn it into an array
4197
-            $values = explode(",", $values);
4198
-        }
4199
-        $cleaned_values = array();
4200
-        foreach ($values as $value) {
4201
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4202
-        }
4203
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4204
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4205
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4206
-        if (empty($cleaned_values)) {
4207
-            $all_fields = $this->field_settings();
4208
-            $a_field = array_shift($all_fields);
4209
-            $main_table = $this->_get_main_table();
4210
-            $cleaned_values[] = "SELECT "
4211
-                                . $a_field->get_table_column()
4212
-                                . " FROM "
4213
-                                . $main_table->get_table_name()
4214
-                                . " WHERE FALSE";
4215
-        }
4216
-        return "(" . implode(",", $cleaned_values) . ")";
4217
-    }
4218
-
4219
-
4220
-
4221
-    /**
4222
-     * @param mixed                      $value
4223
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4224
-     * @throws EE_Error
4225
-     * @return false|null|string
4226
-     */
4227
-    private function _wpdb_prepare_using_field($value, $field_obj)
4228
-    {
4229
-        /** @type WPDB $wpdb */
4230
-        global $wpdb;
4231
-        if ($field_obj instanceof EE_Model_Field_Base) {
4232
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4233
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4234
-        } else {//$field_obj should really just be a data type
4235
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4236
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4237
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4238
-            }
4239
-            return $wpdb->prepare($field_obj, $value);
4240
-        }
4241
-    }
4242
-
4243
-
4244
-
4245
-    /**
4246
-     * Takes the input parameter and finds the model field that it indicates.
4247
-     *
4248
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4249
-     * @throws EE_Error
4250
-     * @return EE_Model_Field_Base
4251
-     */
4252
-    protected function _deduce_field_from_query_param($query_param_name)
4253
-    {
4254
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4255
-        //which will help us find the database table and column
4256
-        $query_param_parts = explode(".", $query_param_name);
4257
-        if (empty($query_param_parts)) {
4258
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4259
-                'event_espresso'), $query_param_name));
4260
-        }
4261
-        $number_of_parts = count($query_param_parts);
4262
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4263
-        if ($number_of_parts === 1) {
4264
-            $field_name = $last_query_param_part;
4265
-            $model_obj = $this;
4266
-        } else {// $number_of_parts >= 2
4267
-            //the last part is the column name, and there are only 2parts. therefore...
4268
-            $field_name = $last_query_param_part;
4269
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4270
-        }
4271
-        try {
4272
-            return $model_obj->field_settings_for($field_name);
4273
-        } catch (EE_Error $e) {
4274
-            return null;
4275
-        }
4276
-    }
4277
-
4278
-
4279
-
4280
-    /**
4281
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4282
-     * alias and column which corresponds to it
4283
-     *
4284
-     * @param string $field_name
4285
-     * @throws EE_Error
4286
-     * @return string
4287
-     */
4288
-    public function _get_qualified_column_for_field($field_name)
4289
-    {
4290
-        $all_fields = $this->field_settings();
4291
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4292
-        if ($field) {
4293
-            return $field->get_qualified_column();
4294
-        } else {
4295
-            throw new EE_Error(sprintf(__("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.",
4296
-                'event_espresso'), $field_name, get_class($this)));
4297
-        }
4298
-    }
4299
-
4300
-
4301
-
4302
-    /**
4303
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4304
-     * Example usage:
4305
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4306
-     *      array(),
4307
-     *      ARRAY_A,
4308
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4309
-     *  );
4310
-     * is equivalent to
4311
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4312
-     * and
4313
-     *  EEM_Event::instance()->get_all_wpdb_results(
4314
-     *      array(
4315
-     *          array(
4316
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4317
-     *          ),
4318
-     *          ARRAY_A,
4319
-     *          implode(
4320
-     *              ', ',
4321
-     *              array_merge(
4322
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4323
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4324
-     *              )
4325
-     *          )
4326
-     *      )
4327
-     *  );
4328
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4329
-     *
4330
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4331
-     *                                            and the one whose fields you are selecting for example: when querying
4332
-     *                                            tickets model and selecting fields from the tickets model you would
4333
-     *                                            leave this parameter empty, because no models are needed to join
4334
-     *                                            between the queried model and the selected one. Likewise when
4335
-     *                                            querying the datetime model and selecting fields from the tickets
4336
-     *                                            model, it would also be left empty, because there is a direct
4337
-     *                                            relation from datetimes to tickets, so no model is needed to join
4338
-     *                                            them together. However, when querying from the event model and
4339
-     *                                            selecting fields from the ticket model, you should provide the string
4340
-     *                                            'Datetime', indicating that the event model must first join to the
4341
-     *                                            datetime model in order to find its relation to ticket model.
4342
-     *                                            Also, when querying from the venue model and selecting fields from
4343
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4344
-     *                                            indicating you need to join the venue model to the event model,
4345
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4346
-     *                                            This string is used to deduce the prefix that gets added onto the
4347
-     *                                            models' tables qualified columns
4348
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4349
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4350
-     *                                            qualified column names
4351
-     * @return array|string
4352
-     */
4353
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4354
-    {
4355
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4356
-        $qualified_columns = array();
4357
-        foreach ($this->field_settings() as $field_name => $field) {
4358
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4359
-        }
4360
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4361
-    }
4362
-
4363
-
4364
-
4365
-    /**
4366
-     * constructs the select use on special limit joins
4367
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4368
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4369
-     * (as that is typically where the limits would be set).
4370
-     *
4371
-     * @param  string       $table_alias The table the select is being built for
4372
-     * @param  mixed|string $limit       The limit for this select
4373
-     * @return string                The final select join element for the query.
4374
-     */
4375
-    public function _construct_limit_join_select($table_alias, $limit)
4376
-    {
4377
-        $SQL = '';
4378
-        foreach ($this->_tables as $table_obj) {
4379
-            if ($table_obj instanceof EE_Primary_Table) {
4380
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4381
-                    ? $table_obj->get_select_join_limit($limit)
4382
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4383
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4384
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4385
-                    ? $table_obj->get_select_join_limit_join($limit)
4386
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4387
-            }
4388
-        }
4389
-        return $SQL;
4390
-    }
4391
-
4392
-
4393
-
4394
-    /**
4395
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4396
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4397
-     *
4398
-     * @return string SQL
4399
-     * @throws \EE_Error
4400
-     */
4401
-    public function _construct_internal_join()
4402
-    {
4403
-        $SQL = $this->_get_main_table()->get_table_sql();
4404
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4405
-        return $SQL;
4406
-    }
4407
-
4408
-
4409
-
4410
-    /**
4411
-     * Constructs the SQL for joining all the tables on this model.
4412
-     * Normally $alias should be the primary table's alias, but in cases where
4413
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4414
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4415
-     * alias, this will construct SQL like:
4416
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4417
-     * With $alias being a secondary table's alias, this will construct SQL like:
4418
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4419
-     *
4420
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4421
-     * @return string
4422
-     */
4423
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4424
-    {
4425
-        $SQL = '';
4426
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4427
-        foreach ($this->_tables as $table_obj) {
4428
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4429
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4430
-                    //so we're joining to this table, meaning the table is already in
4431
-                    //the FROM statement, BUT the primary table isn't. So we want
4432
-                    //to add the inverse join sql
4433
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4434
-                } else {
4435
-                    //just add a regular JOIN to this table from the primary table
4436
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4437
-                }
4438
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4439
-        }
4440
-        return $SQL;
4441
-    }
4442
-
4443
-
4444
-
4445
-    /**
4446
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4447
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4448
-     * their data type (eg, '%s', '%d', etc)
4449
-     *
4450
-     * @return array
4451
-     */
4452
-    public function _get_data_types()
4453
-    {
4454
-        $data_types = array();
4455
-        foreach ($this->field_settings() as $field_obj) {
4456
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4457
-            /** @var $field_obj EE_Model_Field_Base */
4458
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4459
-        }
4460
-        return $data_types;
4461
-    }
4462
-
4463
-
4464
-
4465
-    /**
4466
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4467
-     *
4468
-     * @param string $model_name
4469
-     * @throws EE_Error
4470
-     * @return EEM_Base
4471
-     */
4472
-    public function get_related_model_obj($model_name)
4473
-    {
4474
-        $model_classname = "EEM_" . $model_name;
4475
-        if (! class_exists($model_classname)) {
4476
-            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",
4477
-                'event_espresso'), $model_name, $model_classname));
4478
-        }
4479
-        return call_user_func($model_classname . "::instance");
4480
-    }
4481
-
4482
-
4483
-
4484
-    /**
4485
-     * Returns the array of EE_ModelRelations for this model.
4486
-     *
4487
-     * @return EE_Model_Relation_Base[]
4488
-     */
4489
-    public function relation_settings()
4490
-    {
4491
-        return $this->_model_relations;
4492
-    }
4493
-
4494
-
4495
-
4496
-    /**
4497
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4498
-     * because without THOSE models, this model probably doesn't have much purpose.
4499
-     * (Eg, without an event, datetimes have little purpose.)
4500
-     *
4501
-     * @return EE_Belongs_To_Relation[]
4502
-     */
4503
-    public function belongs_to_relations()
4504
-    {
4505
-        $belongs_to_relations = array();
4506
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4507
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4508
-                $belongs_to_relations[$model_name] = $relation_obj;
4509
-            }
4510
-        }
4511
-        return $belongs_to_relations;
4512
-    }
4513
-
4514
-
4515
-
4516
-    /**
4517
-     * Returns the specified EE_Model_Relation, or throws an exception
4518
-     *
4519
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4520
-     * @throws EE_Error
4521
-     * @return EE_Model_Relation_Base
4522
-     */
4523
-    public function related_settings_for($relation_name)
4524
-    {
4525
-        $relatedModels = $this->relation_settings();
4526
-        if (! array_key_exists($relation_name, $relatedModels)) {
4527
-            throw new EE_Error(
4528
-                sprintf(
4529
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4530
-                        'event_espresso'),
4531
-                    $relation_name,
4532
-                    $this->_get_class_name(),
4533
-                    implode(', ', array_keys($relatedModels))
4534
-                )
4535
-            );
4536
-        }
4537
-        return $relatedModels[$relation_name];
4538
-    }
4539
-
4540
-
4541
-
4542
-    /**
4543
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4544
-     * fields
4545
-     *
4546
-     * @param string $fieldName
4547
-     * @throws EE_Error
4548
-     * @return EE_Model_Field_Base
4549
-     */
4550
-    public function field_settings_for($fieldName)
4551
-    {
4552
-        $fieldSettings = $this->field_settings(true);
4553
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4554
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4555
-                get_class($this)));
4556
-        }
4557
-        return $fieldSettings[$fieldName];
4558
-    }
4559
-
4560
-
4561
-
4562
-    /**
4563
-     * Checks if this field exists on this model
4564
-     *
4565
-     * @param string $fieldName a key in the model's _field_settings array
4566
-     * @return boolean
4567
-     */
4568
-    public function has_field($fieldName)
4569
-    {
4570
-        $fieldSettings = $this->field_settings(true);
4571
-        if (isset($fieldSettings[$fieldName])) {
4572
-            return true;
4573
-        } else {
4574
-            return false;
4575
-        }
4576
-    }
4577
-
4578
-
4579
-
4580
-    /**
4581
-     * Returns whether or not this model has a relation to the specified model
4582
-     *
4583
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4584
-     * @return boolean
4585
-     */
4586
-    public function has_relation($relation_name)
4587
-    {
4588
-        $relations = $this->relation_settings();
4589
-        if (isset($relations[$relation_name])) {
4590
-            return true;
4591
-        } else {
4592
-            return false;
4593
-        }
4594
-    }
4595
-
4596
-
4597
-
4598
-    /**
4599
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4600
-     * Eg, on EE_Answer that would be ANS_ID field object
4601
-     *
4602
-     * @param $field_obj
4603
-     * @return boolean
4604
-     */
4605
-    public function is_primary_key_field($field_obj)
4606
-    {
4607
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4608
-    }
4609
-
4610
-
4611
-
4612
-    /**
4613
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4614
-     * Eg, on EE_Answer that would be ANS_ID field object
4615
-     *
4616
-     * @return EE_Model_Field_Base
4617
-     * @throws EE_Error
4618
-     */
4619
-    public function get_primary_key_field()
4620
-    {
4621
-        if ($this->_primary_key_field === null) {
4622
-            foreach ($this->field_settings(true) as $field_obj) {
4623
-                if ($this->is_primary_key_field($field_obj)) {
4624
-                    $this->_primary_key_field = $field_obj;
4625
-                    break;
4626
-                }
4627
-            }
4628
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4629
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4630
-                    get_class($this)));
4631
-            }
4632
-        }
4633
-        return $this->_primary_key_field;
4634
-    }
4635
-
4636
-
4637
-
4638
-    /**
4639
-     * Returns whether or not not there is a primary key on this model.
4640
-     * Internally does some caching.
4641
-     *
4642
-     * @return boolean
4643
-     */
4644
-    public function has_primary_key_field()
4645
-    {
4646
-        if ($this->_has_primary_key_field === null) {
4647
-            try {
4648
-                $this->get_primary_key_field();
4649
-                $this->_has_primary_key_field = true;
4650
-            } catch (EE_Error $e) {
4651
-                $this->_has_primary_key_field = false;
4652
-            }
4653
-        }
4654
-        return $this->_has_primary_key_field;
4655
-    }
4656
-
4657
-
4658
-
4659
-    /**
4660
-     * Finds the first field of type $field_class_name.
4661
-     *
4662
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4663
-     *                                 EE_Foreign_Key_Field, etc
4664
-     * @return EE_Model_Field_Base or null if none is found
4665
-     */
4666
-    public function get_a_field_of_type($field_class_name)
4667
-    {
4668
-        foreach ($this->field_settings() as $field) {
4669
-            if ($field instanceof $field_class_name) {
4670
-                return $field;
4671
-            }
4672
-        }
4673
-        return null;
4674
-    }
4675
-
4676
-
4677
-
4678
-    /**
4679
-     * Gets a foreign key field pointing to model.
4680
-     *
4681
-     * @param string $model_name eg Event, Registration, not EEM_Event
4682
-     * @return EE_Foreign_Key_Field_Base
4683
-     * @throws EE_Error
4684
-     */
4685
-    public function get_foreign_key_to($model_name)
4686
-    {
4687
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4688
-            foreach ($this->field_settings() as $field) {
4689
-                if (
4690
-                    $field instanceof EE_Foreign_Key_Field_Base
4691
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4692
-                ) {
4693
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4694
-                    break;
4695
-                }
4696
-            }
4697
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4698
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4699
-                    'event_espresso'), $model_name, get_class($this)));
4700
-            }
4701
-        }
4702
-        return $this->_cache_foreign_key_to_fields[$model_name];
4703
-    }
4704
-
4705
-
4706
-
4707
-    /**
4708
-     * Gets the actual table for the table alias
4709
-     *
4710
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4711
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4712
-     *                            Either one works
4713
-     * @return EE_Table_Base
4714
-     */
4715
-    public function get_table_for_alias($table_alias)
4716
-    {
4717
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4718
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4719
-    }
4720
-
4721
-
4722
-
4723
-    /**
4724
-     * Returns a flat array of all field son this model, instead of organizing them
4725
-     * by table_alias as they are in the constructor.
4726
-     *
4727
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4728
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4729
-     */
4730
-    public function field_settings($include_db_only_fields = false)
4731
-    {
4732
-        if ($include_db_only_fields) {
4733
-            if ($this->_cached_fields === null) {
4734
-                $this->_cached_fields = array();
4735
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4736
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4737
-                        $this->_cached_fields[$field_name] = $field_obj;
4738
-                    }
4739
-                }
4740
-            }
4741
-            return $this->_cached_fields;
4742
-        } else {
4743
-            if ($this->_cached_fields_non_db_only === null) {
4744
-                $this->_cached_fields_non_db_only = array();
4745
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4746
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4747
-                        /** @var $field_obj EE_Model_Field_Base */
4748
-                        if (! $field_obj->is_db_only_field()) {
4749
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4750
-                        }
4751
-                    }
4752
-                }
4753
-            }
4754
-            return $this->_cached_fields_non_db_only;
4755
-        }
4756
-    }
4757
-
4758
-
4759
-
4760
-    /**
4761
-     *        cycle though array of attendees and create objects out of each item
4762
-     *
4763
-     * @access        private
4764
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4765
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4766
-     *                           numerically indexed)
4767
-     * @throws \EE_Error
4768
-     */
4769
-    protected function _create_objects($rows = array())
4770
-    {
4771
-        $array_of_objects = array();
4772
-        if (empty($rows)) {
4773
-            return array();
4774
-        }
4775
-        $count_if_model_has_no_primary_key = 0;
4776
-        $has_primary_key = $this->has_primary_key_field();
4777
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4778
-        foreach ((array)$rows as $row) {
4779
-            if (empty($row)) {
4780
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4781
-                return array();
4782
-            }
4783
-            //check if we've already set this object in the results array,
4784
-            //in which case there's no need to process it further (again)
4785
-            if ($has_primary_key) {
4786
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4787
-                    $row,
4788
-                    $primary_key_field->get_qualified_column(),
4789
-                    $primary_key_field->get_table_column()
4790
-                );
4791
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4792
-                    continue;
4793
-                }
4794
-            }
4795
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4796
-            if (! $classInstance) {
4797
-                throw new EE_Error(
4798
-                    sprintf(
4799
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4800
-                        $this->get_this_model_name(),
4801
-                        http_build_query($row)
4802
-                    )
4803
-                );
4804
-            }
4805
-            //set the timezone on the instantiated objects
4806
-            $classInstance->set_timezone($this->_timezone);
4807
-            //make sure if there is any timezone setting present that we set the timezone for the object
4808
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4809
-            $array_of_objects[$key] = $classInstance;
4810
-            //also, for all the relations of type BelongsTo, see if we can cache
4811
-            //those related models
4812
-            //(we could do this for other relations too, but if there are conditions
4813
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4814
-            //so it requires a little more thought than just caching them immediately...)
4815
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4816
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4817
-                    //check if this model's INFO is present. If so, cache it on the model
4818
-                    $other_model = $relation_obj->get_other_model();
4819
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4820
-                    //if we managed to make a model object from the results, cache it on the main model object
4821
-                    if ($other_model_obj_maybe) {
4822
-                        //set timezone on these other model objects if they are present
4823
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4824
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4825
-                    }
4826
-                }
4827
-            }
4828
-        }
4829
-        return $array_of_objects;
4830
-    }
4831
-
4832
-
4833
-
4834
-    /**
4835
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4836
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4837
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4838
-     * object (as set in the model_field!).
4839
-     *
4840
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4841
-     */
4842
-    public function create_default_object()
4843
-    {
4844
-        $this_model_fields_and_values = array();
4845
-        //setup the row using default values;
4846
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4847
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4848
-        }
4849
-        $className = $this->_get_class_name();
4850
-        $classInstance = EE_Registry::instance()
4851
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4852
-        return $classInstance;
4853
-    }
4854
-
4855
-
4856
-
4857
-    /**
4858
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4859
-     *                             or an stdClass where each property is the name of a column,
4860
-     * @return EE_Base_Class
4861
-     * @throws \EE_Error
4862
-     */
4863
-    public function instantiate_class_from_array_or_object($cols_n_values)
4864
-    {
4865
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4866
-            $cols_n_values = get_object_vars($cols_n_values);
4867
-        }
4868
-        $primary_key = null;
4869
-        //make sure the array only has keys that are fields/columns on this model
4870
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4871
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4872
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4873
-        }
4874
-        $className = $this->_get_class_name();
4875
-        //check we actually found results that we can use to build our model object
4876
-        //if not, return null
4877
-        if ($this->has_primary_key_field()) {
4878
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4879
-                return null;
4880
-            }
4881
-        } else if ($this->unique_indexes()) {
4882
-            $first_column = reset($this_model_fields_n_values);
4883
-            if (empty($first_column)) {
4884
-                return null;
4885
-            }
4886
-        }
4887
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4888
-        if ($primary_key) {
4889
-            $classInstance = $this->get_from_entity_map($primary_key);
4890
-            if (! $classInstance) {
4891
-                $classInstance = EE_Registry::instance()
4892
-                                            ->load_class($className,
4893
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4894
-                // add this new object to the entity map
4895
-                $classInstance = $this->add_to_entity_map($classInstance);
4896
-            }
4897
-        } else {
4898
-            $classInstance = EE_Registry::instance()
4899
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4900
-                                            true, false);
4901
-        }
4902
-        //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.
4903
-        $this->set_timezone($classInstance->get_timezone());
4904
-        return $classInstance;
4905
-    }
4906
-
4907
-
4908
-
4909
-    /**
4910
-     * Gets the model object from the  entity map if it exists
4911
-     *
4912
-     * @param int|string $id the ID of the model object
4913
-     * @return EE_Base_Class
4914
-     */
4915
-    public function get_from_entity_map($id)
4916
-    {
4917
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4918
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4919
-    }
4920
-
4921
-
4922
-
4923
-    /**
4924
-     * add_to_entity_map
4925
-     * Adds the object to the model's entity mappings
4926
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4927
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4928
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4929
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4930
-     *        then this method should be called immediately after the update query
4931
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4932
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4933
-     *
4934
-     * @param    EE_Base_Class $object
4935
-     * @throws EE_Error
4936
-     * @return \EE_Base_Class
4937
-     */
4938
-    public function add_to_entity_map(EE_Base_Class $object)
4939
-    {
4940
-        $className = $this->_get_class_name();
4941
-        if (! $object instanceof $className) {
4942
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4943
-                is_object($object) ? get_class($object) : $object, $className));
4944
-        }
4945
-        /** @var $object EE_Base_Class */
4946
-        if (! $object->ID()) {
4947
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4948
-                "event_espresso"), get_class($this)));
4949
-        }
4950
-        // double check it's not already there
4951
-        $classInstance = $this->get_from_entity_map($object->ID());
4952
-        if ($classInstance) {
4953
-            return $classInstance;
4954
-        } else {
4955
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4956
-            return $object;
4957
-        }
4958
-    }
4959
-
4960
-
4961
-
4962
-    /**
4963
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4964
-     * if no identifier is provided, then the entire entity map is emptied
4965
-     *
4966
-     * @param int|string $id the ID of the model object
4967
-     * @return boolean
4968
-     */
4969
-    public function clear_entity_map($id = null)
4970
-    {
4971
-        if (empty($id)) {
4972
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4973
-            return true;
4974
-        }
4975
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4976
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4977
-            return true;
4978
-        }
4979
-        return false;
4980
-    }
4981
-
4982
-
4983
-
4984
-    /**
4985
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4986
-     * Given an array where keys are column (or column alias) names and values,
4987
-     * returns an array of their corresponding field names and database values
4988
-     *
4989
-     * @param array $cols_n_values
4990
-     * @return array
4991
-     */
4992
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4993
-    {
4994
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4995
-    }
4996
-
4997
-
4998
-
4999
-    /**
5000
-     * _deduce_fields_n_values_from_cols_n_values
5001
-     * Given an array where keys are column (or column alias) names and values,
5002
-     * returns an array of their corresponding field names and database values
5003
-     *
5004
-     * @param string $cols_n_values
5005
-     * @return array
5006
-     */
5007
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5008
-    {
5009
-        $this_model_fields_n_values = array();
5010
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5011
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5012
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5013
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5014
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5015
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5016
-                    if (! $field_obj->is_db_only_field()) {
5017
-                        //prepare field as if its coming from db
5018
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5019
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5020
-                    }
5021
-                }
5022
-            } else {
5023
-                //the table's rows existed. Use their values
5024
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5025
-                    if (! $field_obj->is_db_only_field()) {
5026
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5027
-                            $cols_n_values, $field_obj->get_qualified_column(),
5028
-                            $field_obj->get_table_column()
5029
-                        );
5030
-                    }
5031
-                }
5032
-            }
5033
-        }
5034
-        return $this_model_fields_n_values;
5035
-    }
5036
-
5037
-
5038
-
5039
-    /**
5040
-     * @param $cols_n_values
5041
-     * @param $qualified_column
5042
-     * @param $regular_column
5043
-     * @return null
5044
-     */
5045
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5046
-    {
5047
-        $value = null;
5048
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5049
-        //does the field on the model relate to this column retrieved from the db?
5050
-        //or is it a db-only field? (not relating to the model)
5051
-        if (isset($cols_n_values[$qualified_column])) {
5052
-            $value = $cols_n_values[$qualified_column];
5053
-        } elseif (isset($cols_n_values[$regular_column])) {
5054
-            $value = $cols_n_values[$regular_column];
5055
-        }
5056
-        return $value;
5057
-    }
5058
-
5059
-
5060
-
5061
-    /**
5062
-     * refresh_entity_map_from_db
5063
-     * Makes sure the model object in the entity map at $id assumes the values
5064
-     * of the database (opposite of EE_base_Class::save())
5065
-     *
5066
-     * @param int|string $id
5067
-     * @return EE_Base_Class
5068
-     * @throws \EE_Error
5069
-     */
5070
-    public function refresh_entity_map_from_db($id)
5071
-    {
5072
-        $obj_in_map = $this->get_from_entity_map($id);
5073
-        if ($obj_in_map) {
5074
-            $wpdb_results = $this->_get_all_wpdb_results(
5075
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5076
-            );
5077
-            if ($wpdb_results && is_array($wpdb_results)) {
5078
-                $one_row = reset($wpdb_results);
5079
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5080
-                    $obj_in_map->set_from_db($field_name, $db_value);
5081
-                }
5082
-                //clear the cache of related model objects
5083
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5084
-                    $obj_in_map->clear_cache($relation_name, null, true);
5085
-                }
5086
-            }
5087
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5088
-            return $obj_in_map;
5089
-        } else {
5090
-            return $this->get_one_by_ID($id);
5091
-        }
5092
-    }
5093
-
5094
-
5095
-
5096
-    /**
5097
-     * refresh_entity_map_with
5098
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5099
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5100
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5101
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5102
-     *
5103
-     * @param int|string    $id
5104
-     * @param EE_Base_Class $replacing_model_obj
5105
-     * @return \EE_Base_Class
5106
-     * @throws \EE_Error
5107
-     */
5108
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5109
-    {
5110
-        $obj_in_map = $this->get_from_entity_map($id);
5111
-        if ($obj_in_map) {
5112
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5113
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5114
-                    $obj_in_map->set($field_name, $value);
5115
-                }
5116
-                //make the model object in the entity map's cache match the $replacing_model_obj
5117
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5118
-                    $obj_in_map->clear_cache($relation_name, null, true);
5119
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5120
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5121
-                    }
5122
-                }
5123
-            }
5124
-            return $obj_in_map;
5125
-        } else {
5126
-            $this->add_to_entity_map($replacing_model_obj);
5127
-            return $replacing_model_obj;
5128
-        }
5129
-    }
5130
-
5131
-
5132
-
5133
-    /**
5134
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5135
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5136
-     * require_once($this->_getClassName().".class.php");
5137
-     *
5138
-     * @return string
5139
-     */
5140
-    private function _get_class_name()
5141
-    {
5142
-        return "EE_" . $this->get_this_model_name();
5143
-    }
5144
-
5145
-
5146
-
5147
-    /**
5148
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5149
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5150
-     * it would be 'Events'.
5151
-     *
5152
-     * @param int $quantity
5153
-     * @return string
5154
-     */
5155
-    public function item_name($quantity = 1)
5156
-    {
5157
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5158
-    }
5159
-
5160
-
5161
-
5162
-    /**
5163
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5164
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5165
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5166
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5167
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5168
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5169
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5170
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5171
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5172
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5173
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5174
-     *        return $previousReturnValue.$returnString;
5175
-     * }
5176
-     * require('EEM_Answer.model.php');
5177
-     * $answer=EEM_Answer::instance();
5178
-     * echo $answer->my_callback('monkeys',100);
5179
-     * //will output "you called my_callback! and passed args:monkeys,100"
5180
-     *
5181
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5182
-     * @param array  $args       array of original arguments passed to the function
5183
-     * @throws EE_Error
5184
-     * @return mixed whatever the plugin which calls add_filter decides
5185
-     */
5186
-    public function __call($methodName, $args)
5187
-    {
5188
-        $className = get_class($this);
5189
-        $tagName = "FHEE__{$className}__{$methodName}";
5190
-        if (! has_filter($tagName)) {
5191
-            throw new EE_Error(
5192
-                sprintf(
5193
-                    __('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 );',
5194
-                        'event_espresso'),
5195
-                    $methodName,
5196
-                    $className,
5197
-                    $tagName,
5198
-                    '<br />'
5199
-                )
5200
-            );
5201
-        }
5202
-        return apply_filters($tagName, null, $this, $args);
5203
-    }
5204
-
5205
-
5206
-
5207
-    /**
5208
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5209
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5210
-     *
5211
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5212
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5213
-     *                                                       the object's class name
5214
-     *                                                       or object's ID
5215
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5216
-     *                                                       exists in the database. If it does not, we add it
5217
-     * @throws EE_Error
5218
-     * @return EE_Base_Class
5219
-     */
5220
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5221
-    {
5222
-        $className = $this->_get_class_name();
5223
-        if ($base_class_obj_or_id instanceof $className) {
5224
-            $model_object = $base_class_obj_or_id;
5225
-        } else {
5226
-            $primary_key_field = $this->get_primary_key_field();
5227
-            if (
5228
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5229
-                && (
5230
-                    is_int($base_class_obj_or_id)
5231
-                    || is_string($base_class_obj_or_id)
5232
-                )
5233
-            ) {
5234
-                // assume it's an ID.
5235
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5236
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5237
-            } else if (
5238
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5239
-                && is_string($base_class_obj_or_id)
5240
-            ) {
5241
-                // assume its a string representation of the object
5242
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5243
-            } else {
5244
-                throw new EE_Error(
5245
-                    sprintf(
5246
-                        __(
5247
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5248
-                            'event_espresso'
5249
-                        ),
5250
-                        $base_class_obj_or_id,
5251
-                        $this->_get_class_name(),
5252
-                        print_r($base_class_obj_or_id, true)
5253
-                    )
5254
-                );
5255
-            }
5256
-        }
5257
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5258
-            $model_object->save();
5259
-        }
5260
-        return $model_object;
5261
-    }
5262
-
5263
-
5264
-
5265
-    /**
5266
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5267
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5268
-     * returns it ID.
5269
-     *
5270
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5271
-     * @return int|string depending on the type of this model object's ID
5272
-     * @throws EE_Error
5273
-     */
5274
-    public function ensure_is_ID($base_class_obj_or_id)
5275
-    {
5276
-        $className = $this->_get_class_name();
5277
-        if ($base_class_obj_or_id instanceof $className) {
5278
-            /** @var $base_class_obj_or_id EE_Base_Class */
5279
-            $id = $base_class_obj_or_id->ID();
5280
-        } elseif (is_int($base_class_obj_or_id)) {
5281
-            //assume it's an ID
5282
-            $id = $base_class_obj_or_id;
5283
-        } elseif (is_string($base_class_obj_or_id)) {
5284
-            //assume its a string representation of the object
5285
-            $id = $base_class_obj_or_id;
5286
-        } else {
5287
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5288
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5289
-                print_r($base_class_obj_or_id, true)));
5290
-        }
5291
-        return $id;
5292
-    }
5293
-
5294
-
5295
-
5296
-    /**
5297
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5298
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5299
-     * been sanitized and converted into the appropriate domain.
5300
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5301
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5302
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5303
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5304
-     * $EVT = EEM_Event::instance(); $old_setting =
5305
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5306
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5307
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5308
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5309
-     *
5310
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5311
-     * @return void
5312
-     */
5313
-    public function assume_values_already_prepared_by_model_object(
5314
-        $values_already_prepared = self::not_prepared_by_model_object
5315
-    ) {
5316
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5317
-    }
5318
-
5319
-
5320
-
5321
-    /**
5322
-     * Read comments for assume_values_already_prepared_by_model_object()
5323
-     *
5324
-     * @return int
5325
-     */
5326
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5327
-    {
5328
-        return $this->_values_already_prepared_by_model_object;
5329
-    }
5330
-
5331
-
5332
-
5333
-    /**
5334
-     * Gets all the indexes on this model
5335
-     *
5336
-     * @return EE_Index[]
5337
-     */
5338
-    public function indexes()
5339
-    {
5340
-        return $this->_indexes;
5341
-    }
5342
-
5343
-
5344
-
5345
-    /**
5346
-     * Gets all the Unique Indexes on this model
5347
-     *
5348
-     * @return EE_Unique_Index[]
5349
-     */
5350
-    public function unique_indexes()
5351
-    {
5352
-        $unique_indexes = array();
5353
-        foreach ($this->_indexes as $name => $index) {
5354
-            if ($index instanceof EE_Unique_Index) {
5355
-                $unique_indexes [$name] = $index;
5356
-            }
5357
-        }
5358
-        return $unique_indexes;
5359
-    }
5360
-
5361
-
5362
-
5363
-    /**
5364
-     * Gets all the fields which, when combined, make the primary key.
5365
-     * This is usually just an array with 1 element (the primary key), but in cases
5366
-     * where there is no primary key, it's a combination of fields as defined
5367
-     * on a primary index
5368
-     *
5369
-     * @return EE_Model_Field_Base[] indexed by the field's name
5370
-     * @throws \EE_Error
5371
-     */
5372
-    public function get_combined_primary_key_fields()
5373
-    {
5374
-        foreach ($this->indexes() as $index) {
5375
-            if ($index instanceof EE_Primary_Key_Index) {
5376
-                return $index->fields();
5377
-            }
5378
-        }
5379
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5380
-    }
5381
-
5382
-
5383
-
5384
-    /**
5385
-     * Used to build a primary key string (when the model has no primary key),
5386
-     * which can be used a unique string to identify this model object.
5387
-     *
5388
-     * @param array $cols_n_values keys are field names, values are their values
5389
-     * @return string
5390
-     * @throws \EE_Error
5391
-     */
5392
-    public function get_index_primary_key_string($cols_n_values)
5393
-    {
5394
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5395
-            $this->get_combined_primary_key_fields());
5396
-        return http_build_query($cols_n_values_for_primary_key_index);
5397
-    }
5398
-
5399
-
5400
-
5401
-    /**
5402
-     * Gets the field values from the primary key string
5403
-     *
5404
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5405
-     * @param string $index_primary_key_string
5406
-     * @return null|array
5407
-     * @throws \EE_Error
5408
-     */
5409
-    public function parse_index_primary_key_string($index_primary_key_string)
5410
-    {
5411
-        $key_fields = $this->get_combined_primary_key_fields();
5412
-        //check all of them are in the $id
5413
-        $key_vals_in_combined_pk = array();
5414
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5415
-        foreach ($key_fields as $key_field_name => $field_obj) {
5416
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5417
-                return null;
5418
-            }
5419
-        }
5420
-        return $key_vals_in_combined_pk;
5421
-    }
5422
-
5423
-
5424
-
5425
-    /**
5426
-     * verifies that an array of key-value pairs for model fields has a key
5427
-     * for each field comprising the primary key index
5428
-     *
5429
-     * @param array $key_vals
5430
-     * @return boolean
5431
-     * @throws \EE_Error
5432
-     */
5433
-    public function has_all_combined_primary_key_fields($key_vals)
5434
-    {
5435
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5436
-        foreach ($keys_it_should_have as $key) {
5437
-            if (! isset($key_vals[$key])) {
5438
-                return false;
5439
-            }
5440
-        }
5441
-        return true;
5442
-    }
5443
-
5444
-
5445
-
5446
-    /**
5447
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5448
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5449
-     *
5450
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5451
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5452
-     * @throws EE_Error
5453
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5454
-     *                                                              indexed)
5455
-     */
5456
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5457
-    {
5458
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5459
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5460
-        } elseif (is_array($model_object_or_attributes_array)) {
5461
-            $attributes_array = $model_object_or_attributes_array;
5462
-        } else {
5463
-            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",
5464
-                "event_espresso"), $model_object_or_attributes_array));
5465
-        }
5466
-        //even copies obviously won't have the same ID, so remove the primary key
5467
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5468
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5469
-            unset($attributes_array[$this->primary_key_name()]);
5470
-        }
5471
-        if (isset($query_params[0])) {
5472
-            $query_params[0] = array_merge($attributes_array, $query_params);
5473
-        } else {
5474
-            $query_params[0] = $attributes_array;
5475
-        }
5476
-        return $this->get_all($query_params);
5477
-    }
5478
-
5479
-
5480
-
5481
-    /**
5482
-     * Gets the first copy we find. See get_all_copies for more details
5483
-     *
5484
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5485
-     * @param array $query_params
5486
-     * @return EE_Base_Class
5487
-     * @throws \EE_Error
5488
-     */
5489
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5490
-    {
5491
-        if (! is_array($query_params)) {
5492
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5493
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5494
-                    gettype($query_params)), '4.6.0');
5495
-            $query_params = array();
5496
-        }
5497
-        $query_params['limit'] = 1;
5498
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5499
-        if (is_array($copies)) {
5500
-            return array_shift($copies);
5501
-        } else {
5502
-            return null;
5503
-        }
5504
-    }
5505
-
5506
-
5507
-
5508
-    /**
5509
-     * Updates the item with the specified id. Ignores default query parameters because
5510
-     * we have specified the ID, and its assumed we KNOW what we're doing
5511
-     *
5512
-     * @param array      $fields_n_values keys are field names, values are their new values
5513
-     * @param int|string $id              the value of the primary key to update
5514
-     * @return int number of rows updated
5515
-     * @throws \EE_Error
5516
-     */
5517
-    public function update_by_ID($fields_n_values, $id)
5518
-    {
5519
-        $query_params = array(
5520
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5521
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5522
-        );
5523
-        return $this->update($fields_n_values, $query_params);
5524
-    }
5525
-
5526
-
5527
-
5528
-    /**
5529
-     * Changes an operator which was supplied to the models into one usable in SQL
5530
-     *
5531
-     * @param string $operator_supplied
5532
-     * @return string an operator which can be used in SQL
5533
-     * @throws EE_Error
5534
-     */
5535
-    private function _prepare_operator_for_sql($operator_supplied)
5536
-    {
5537
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5538
-            : null;
5539
-        if ($sql_operator) {
5540
-            return $sql_operator;
5541
-        } else {
5542
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5543
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5544
-        }
5545
-    }
5546
-
5547
-
5548
-
5549
-    /**
5550
-     * Gets an array where keys are the primary keys and values are their 'names'
5551
-     * (as determined by the model object's name() function, which is often overridden)
5552
-     *
5553
-     * @param array $query_params like get_all's
5554
-     * @return string[]
5555
-     * @throws \EE_Error
5556
-     */
5557
-    public function get_all_names($query_params = array())
5558
-    {
5559
-        $objs = $this->get_all($query_params);
5560
-        $names = array();
5561
-        foreach ($objs as $obj) {
5562
-            $names[$obj->ID()] = $obj->name();
5563
-        }
5564
-        return $names;
5565
-    }
5566
-
5567
-
5568
-
5569
-    /**
5570
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5571
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5572
-     * this is duplicated effort and reduces efficiency) you would be better to use
5573
-     * array_keys() on $model_objects.
5574
-     *
5575
-     * @param \EE_Base_Class[] $model_objects
5576
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5577
-     *                                               in the returned array
5578
-     * @return array
5579
-     * @throws \EE_Error
5580
-     */
5581
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5582
-    {
5583
-        if (! $this->has_primary_key_field()) {
5584
-            if (WP_DEBUG) {
5585
-                EE_Error::add_error(
5586
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5587
-                    __FILE__,
5588
-                    __FUNCTION__,
5589
-                    __LINE__
5590
-                );
5591
-            }
5592
-        }
5593
-        $IDs = array();
5594
-        foreach ($model_objects as $model_object) {
5595
-            $id = $model_object->ID();
5596
-            if (! $id) {
5597
-                if ($filter_out_empty_ids) {
5598
-                    continue;
5599
-                }
5600
-                if (WP_DEBUG) {
5601
-                    EE_Error::add_error(
5602
-                        __(
5603
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5604
-                            'event_espresso'
5605
-                        ),
5606
-                        __FILE__,
5607
-                        __FUNCTION__,
5608
-                        __LINE__
5609
-                    );
5610
-                }
5611
-            }
5612
-            $IDs[] = $id;
5613
-        }
5614
-        return $IDs;
5615
-    }
5616
-
5617
-
5618
-
5619
-    /**
5620
-     * Returns the string used in capabilities relating to this model. If there
5621
-     * are no capabilities that relate to this model returns false
5622
-     *
5623
-     * @return string|false
5624
-     */
5625
-    public function cap_slug()
5626
-    {
5627
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5628
-    }
5629
-
5630
-
5631
-
5632
-    /**
5633
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5634
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5635
-     * only returns the cap restrictions array in that context (ie, the array
5636
-     * at that key)
5637
-     *
5638
-     * @param string $context
5639
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5640
-     * @throws \EE_Error
5641
-     */
5642
-    public function cap_restrictions($context = EEM_Base::caps_read)
5643
-    {
5644
-        EEM_Base::verify_is_valid_cap_context($context);
5645
-        //check if we ought to run the restriction generator first
5646
-        if (
5647
-            isset($this->_cap_restriction_generators[$context])
5648
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5649
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5650
-        ) {
5651
-            $this->_cap_restrictions[$context] = array_merge(
5652
-                $this->_cap_restrictions[$context],
5653
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5654
-            );
5655
-        }
5656
-        //and make sure we've finalized the construction of each restriction
5657
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5658
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5659
-                $where_conditions_obj->_finalize_construct($this);
5660
-            }
5661
-        }
5662
-        return $this->_cap_restrictions[$context];
5663
-    }
5664
-
5665
-
5666
-
5667
-    /**
5668
-     * Indicating whether or not this model thinks its a wp core model
5669
-     *
5670
-     * @return boolean
5671
-     */
5672
-    public function is_wp_core_model()
5673
-    {
5674
-        return $this->_wp_core_model;
5675
-    }
5676
-
5677
-
5678
-
5679
-    /**
5680
-     * Gets all the caps that are missing which impose a restriction on
5681
-     * queries made in this context
5682
-     *
5683
-     * @param string $context one of EEM_Base::caps_ constants
5684
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5685
-     * @throws \EE_Error
5686
-     */
5687
-    public function caps_missing($context = EEM_Base::caps_read)
5688
-    {
5689
-        $missing_caps = array();
5690
-        $cap_restrictions = $this->cap_restrictions($context);
5691
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5692
-            if (! EE_Capabilities::instance()
5693
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5694
-            ) {
5695
-                $missing_caps[$cap] = $restriction_if_no_cap;
5696
-            }
5697
-        }
5698
-        return $missing_caps;
5699
-    }
5700
-
5701
-
5702
-
5703
-    /**
5704
-     * Gets the mapping from capability contexts to action strings used in capability names
5705
-     *
5706
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5707
-     * one of 'read', 'edit', or 'delete'
5708
-     */
5709
-    public function cap_contexts_to_cap_action_map()
5710
-    {
5711
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5712
-            $this);
5713
-    }
5714
-
5715
-
5716
-
5717
-    /**
5718
-     * Gets the action string for the specified capability context
5719
-     *
5720
-     * @param string $context
5721
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5722
-     * @throws \EE_Error
5723
-     */
5724
-    public function cap_action_for_context($context)
5725
-    {
5726
-        $mapping = $this->cap_contexts_to_cap_action_map();
5727
-        if (isset($mapping[$context])) {
5728
-            return $mapping[$context];
5729
-        }
5730
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5731
-            return $action;
5732
-        }
5733
-        throw new EE_Error(
5734
-            sprintf(
5735
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5736
-                $context,
5737
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5738
-            )
5739
-        );
5740
-    }
5741
-
5742
-
5743
-
5744
-    /**
5745
-     * Returns all the capability contexts which are valid when querying models
5746
-     *
5747
-     * @return array
5748
-     */
5749
-    public static function valid_cap_contexts()
5750
-    {
5751
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5752
-            self::caps_read,
5753
-            self::caps_read_admin,
5754
-            self::caps_edit,
5755
-            self::caps_delete,
5756
-        ));
5757
-    }
5758
-
5759
-
5760
-
5761
-    /**
5762
-     * Returns all valid options for 'default_where_conditions'
5763
-     *
5764
-     * @return array
5765
-     */
5766
-    public static function valid_default_where_conditions()
5767
-    {
5768
-        return array(
5769
-            EEM_Base::default_where_conditions_all,
5770
-            EEM_Base::default_where_conditions_this_only,
5771
-            EEM_Base::default_where_conditions_others_only,
5772
-            EEM_Base::default_where_conditions_minimum_all,
5773
-            EEM_Base::default_where_conditions_minimum_others,
5774
-            EEM_Base::default_where_conditions_none
5775
-        );
5776
-    }
5777
-
5778
-    // public static function default_where_conditions_full
5779
-    /**
5780
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5781
-     *
5782
-     * @param string $context
5783
-     * @return bool
5784
-     * @throws \EE_Error
5785
-     */
5786
-    static public function verify_is_valid_cap_context($context)
5787
-    {
5788
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5789
-        if (in_array($context, $valid_cap_contexts)) {
5790
-            return true;
5791
-        } else {
5792
-            throw new EE_Error(
5793
-                sprintf(
5794
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5795
-                        'event_espresso'),
5796
-                    $context,
5797
-                    'EEM_Base',
5798
-                    implode(',', $valid_cap_contexts)
5799
-                )
5800
-            );
5801
-        }
5802
-    }
5803
-
5804
-
5805
-
5806
-    /**
5807
-     * Clears all the models field caches. This is only useful when a sub-class
5808
-     * might have added a field or something and these caches might be invalidated
5809
-     */
5810
-    protected function _invalidate_field_caches()
5811
-    {
5812
-        $this->_cache_foreign_key_to_fields = array();
5813
-        $this->_cached_fields = null;
5814
-        $this->_cached_fields_non_db_only = null;
5815
-    }
5816
-
5817
-
5818
-
5819
-    /**
5820
-     * Gets the list of all the where query param keys that relate to logic instead of field names
5821
-     * (eg "and", "or", "not").
5822
-     *
5823
-     * @return array
5824
-     */
5825
-    public function logic_query_param_keys()
5826
-    {
5827
-        return $this->_logic_query_param_keys;
5828
-    }
5829
-
5830
-
5831
-
5832
-    /**
5833
-     * Determines whether or not the where query param array key is for a logic query param.
5834
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5835
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5836
-     *
5837
-     * @param $query_param_key
5838
-     * @return bool
5839
-     */
5840
-    public function is_logic_query_param_key($query_param_key)
5841
-    {
5842
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5843
-            if ($query_param_key === $logic_query_param_key
5844
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5845
-            ) {
5846
-                return true;
5847
-            }
5848
-        }
5849
-        return false;
5850
-    }
3610
+		}
3611
+		return $null_friendly_where_conditions;
3612
+	}
3613
+
3614
+
3615
+
3616
+	/**
3617
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3618
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3619
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3620
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3621
+	 *
3622
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3623
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3624
+	 */
3625
+	private function _get_default_where_conditions($model_relation_path = null)
3626
+	{
3627
+		if ($this->_ignore_where_strategy) {
3628
+			return array();
3629
+		}
3630
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3631
+	}
3632
+
3633
+
3634
+
3635
+	/**
3636
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3637
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3638
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3639
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3640
+	 * Similar to _get_default_where_conditions
3641
+	 *
3642
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3643
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3644
+	 */
3645
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3646
+	{
3647
+		if ($this->_ignore_where_strategy) {
3648
+			return array();
3649
+		}
3650
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3651
+	}
3652
+
3653
+
3654
+
3655
+	/**
3656
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3657
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3658
+	 *
3659
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3660
+	 * @return string
3661
+	 * @throws \EE_Error
3662
+	 */
3663
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3664
+	{
3665
+		$selects = $this->_get_columns_to_select_for_this_model();
3666
+		foreach (
3667
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3668
+			$name_of_other_model_included
3669
+		) {
3670
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3671
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3672
+			foreach ($other_model_selects as $key => $value) {
3673
+				$selects[] = $value;
3674
+			}
3675
+		}
3676
+		return implode(", ", $selects);
3677
+	}
3678
+
3679
+
3680
+
3681
+	/**
3682
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3683
+	 * So that's going to be the columns for all the fields on the model
3684
+	 *
3685
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3686
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3687
+	 */
3688
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3689
+	{
3690
+		$fields = $this->field_settings();
3691
+		$selects = array();
3692
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3693
+			$this->get_this_model_name());
3694
+		foreach ($fields as $field_obj) {
3695
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3696
+						 . $field_obj->get_table_alias()
3697
+						 . "."
3698
+						 . $field_obj->get_table_column()
3699
+						 . " AS '"
3700
+						 . $table_alias_with_model_relation_chain_prefix
3701
+						 . $field_obj->get_table_alias()
3702
+						 . "."
3703
+						 . $field_obj->get_table_column()
3704
+						 . "'";
3705
+		}
3706
+		//make sure we are also getting the PKs of each table
3707
+		$tables = $this->get_tables();
3708
+		if (count($tables) > 1) {
3709
+			foreach ($tables as $table_obj) {
3710
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3711
+									   . $table_obj->get_fully_qualified_pk_column();
3712
+				if (! in_array($qualified_pk_column, $selects)) {
3713
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3714
+				}
3715
+			}
3716
+		}
3717
+		return $selects;
3718
+	}
3719
+
3720
+
3721
+
3722
+	/**
3723
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3724
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3725
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3726
+	 * SQL for joining, and the data types
3727
+	 *
3728
+	 * @param null|string                 $original_query_param
3729
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3730
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3731
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3732
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3733
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3734
+	 *                                                          or 'Registration's
3735
+	 * @param string                      $original_query_param what it originally was (eg
3736
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3737
+	 *                                                          matches $query_param
3738
+	 * @throws EE_Error
3739
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3740
+	 */
3741
+	private function _extract_related_model_info_from_query_param(
3742
+		$query_param,
3743
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3744
+		$query_param_type,
3745
+		$original_query_param = null
3746
+	) {
3747
+		if ($original_query_param === null) {
3748
+			$original_query_param = $query_param;
3749
+		}
3750
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3751
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3752
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3753
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3754
+		//check to see if we have a field on this model
3755
+		$this_model_fields = $this->field_settings(true);
3756
+		if (array_key_exists($query_param, $this_model_fields)) {
3757
+			if ($allow_fields) {
3758
+				return;
3759
+			} else {
3760
+				throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3761
+					"event_espresso"),
3762
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3763
+			}
3764
+		} //check if this is a special logic query param
3765
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3766
+			if ($allow_logic_query_params) {
3767
+				return;
3768
+			} else {
3769
+				throw new EE_Error(
3770
+					sprintf(
3771
+						__('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',
3772
+							'event_espresso'),
3773
+						implode('", "', $this->_logic_query_param_keys),
3774
+						$query_param,
3775
+						get_class($this),
3776
+						'<br />',
3777
+						"\t"
3778
+						. ' $passed_in_query_info = <pre>'
3779
+						. print_r($passed_in_query_info, true)
3780
+						. '</pre>'
3781
+						. "\n\t"
3782
+						. ' $query_param_type = '
3783
+						. $query_param_type
3784
+						. "\n\t"
3785
+						. ' $original_query_param = '
3786
+						. $original_query_param
3787
+					)
3788
+				);
3789
+			}
3790
+		} //check if it's a custom selection
3791
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3792
+			return;
3793
+		}
3794
+		//check if has a model name at the beginning
3795
+		//and
3796
+		//check if it's a field on a related model
3797
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3798
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3799
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3800
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3801
+				if ($query_param === '') {
3802
+					//nothing left to $query_param
3803
+					//we should actually end in a field name, not a model like this!
3804
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3805
+						"event_espresso"),
3806
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3807
+				} else {
3808
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3809
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3810
+						$passed_in_query_info, $query_param_type, $original_query_param);
3811
+					return;
3812
+				}
3813
+			} elseif ($query_param === $valid_related_model_name) {
3814
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3815
+				return;
3816
+			}
3817
+		}
3818
+		//ok so $query_param didn't start with a model name
3819
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3820
+		//it's wack, that's what it is
3821
+		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",
3822
+			"event_espresso"),
3823
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3824
+	}
3825
+
3826
+
3827
+
3828
+	/**
3829
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3830
+	 * and store it on $passed_in_query_info
3831
+	 *
3832
+	 * @param string                      $model_name
3833
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3834
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3835
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3836
+	 *                                                          and are adding a join to 'Payment' with the original
3837
+	 *                                                          query param key
3838
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3839
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3840
+	 *                                                          Payment wants to add default query params so that it
3841
+	 *                                                          will know what models to prepend onto its default query
3842
+	 *                                                          params or in case it wants to rename tables (in case
3843
+	 *                                                          there are multiple joins to the same table)
3844
+	 * @return void
3845
+	 * @throws \EE_Error
3846
+	 */
3847
+	private function _add_join_to_model(
3848
+		$model_name,
3849
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3850
+		$original_query_param
3851
+	) {
3852
+		$relation_obj = $this->related_settings_for($model_name);
3853
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3854
+		//check if the relation is HABTM, because then we're essentially doing two joins
3855
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3856
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3857
+			$join_model_obj = $relation_obj->get_join_model();
3858
+			//replace the model specified with the join model for this relation chain, whi
3859
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3860
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3861
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3862
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3863
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3864
+			$passed_in_query_info->merge($new_query_info);
3865
+		}
3866
+		//now just join to the other table pointed to by the relation object, and add its data types
3867
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3868
+			array($model_relation_chain => $model_name),
3869
+			$relation_obj->get_join_statement($model_relation_chain));
3870
+		$passed_in_query_info->merge($new_query_info);
3871
+	}
3872
+
3873
+
3874
+
3875
+	/**
3876
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3877
+	 *
3878
+	 * @param array $where_params like EEM_Base::get_all
3879
+	 * @return string of SQL
3880
+	 * @throws \EE_Error
3881
+	 */
3882
+	private function _construct_where_clause($where_params)
3883
+	{
3884
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3885
+		if ($SQL) {
3886
+			return " WHERE " . $SQL;
3887
+		} else {
3888
+			return '';
3889
+		}
3890
+	}
3891
+
3892
+
3893
+
3894
+	/**
3895
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3896
+	 * and should be passed HAVING parameters, not WHERE parameters
3897
+	 *
3898
+	 * @param array $having_params
3899
+	 * @return string
3900
+	 * @throws \EE_Error
3901
+	 */
3902
+	private function _construct_having_clause($having_params)
3903
+	{
3904
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3905
+		if ($SQL) {
3906
+			return " HAVING " . $SQL;
3907
+		} else {
3908
+			return '';
3909
+		}
3910
+	}
3911
+
3912
+
3913
+
3914
+	/**
3915
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3916
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3917
+	 * EEM_Attendee.
3918
+	 *
3919
+	 * @param string $field_name
3920
+	 * @param string $model_name
3921
+	 * @return EE_Model_Field_Base
3922
+	 * @throws EE_Error
3923
+	 */
3924
+	protected function _get_field_on_model($field_name, $model_name)
3925
+	{
3926
+		$model_class = 'EEM_' . $model_name;
3927
+		$model_filepath = $model_class . ".model.php";
3928
+		if (is_readable($model_filepath)) {
3929
+			require_once($model_filepath);
3930
+			$model_instance = call_user_func($model_name . "::instance");
3931
+			/* @var $model_instance EEM_Base */
3932
+			return $model_instance->field_settings_for($field_name);
3933
+		} else {
3934
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3935
+				'event_espresso'), $model_name, $model_class, $model_filepath));
3936
+		}
3937
+	}
3938
+
3939
+
3940
+
3941
+	/**
3942
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3943
+	 * Event_Meta.meta_value = 'foo'))"
3944
+	 *
3945
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3946
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3947
+	 * @throws EE_Error
3948
+	 * @return string of SQL
3949
+	 */
3950
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3951
+	{
3952
+		$where_clauses = array();
3953
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3954
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3955
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3956
+				switch ($query_param) {
3957
+					case 'not':
3958
+					case 'NOT':
3959
+						$where_clauses[] = "! ("
3960
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3961
+								$glue)
3962
+										   . ")";
3963
+						break;
3964
+					case 'and':
3965
+					case 'AND':
3966
+						$where_clauses[] = " ("
3967
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3968
+								' AND ')
3969
+										   . ")";
3970
+						break;
3971
+					case 'or':
3972
+					case 'OR':
3973
+						$where_clauses[] = " ("
3974
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3975
+								' OR ')
3976
+										   . ")";
3977
+						break;
3978
+				}
3979
+			} else {
3980
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3981
+				//if it's not a normal field, maybe it's a custom selection?
3982
+				if (! $field_obj) {
3983
+					if (isset($this->_custom_selections[$query_param][1])) {
3984
+						$field_obj = $this->_custom_selections[$query_param][1];
3985
+					} else {
3986
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3987
+							"event_espresso"), $query_param));
3988
+					}
3989
+				}
3990
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3991
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3992
+			}
3993
+		}
3994
+		return $where_clauses ? implode($glue, $where_clauses) : '';
3995
+	}
3996
+
3997
+
3998
+
3999
+	/**
4000
+	 * Takes the input parameter and extract the table name (alias) and column name
4001
+	 *
4002
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4003
+	 * @throws EE_Error
4004
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4005
+	 */
4006
+	private function _deduce_column_name_from_query_param($query_param)
4007
+	{
4008
+		$field = $this->_deduce_field_from_query_param($query_param);
4009
+		if ($field) {
4010
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4011
+				$query_param);
4012
+			return $table_alias_prefix . $field->get_qualified_column();
4013
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
4014
+			//maybe it's custom selection item?
4015
+			//if so, just use it as the "column name"
4016
+			return $query_param;
4017
+		} else {
4018
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4019
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4020
+		}
4021
+	}
4022
+
4023
+
4024
+
4025
+	/**
4026
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4027
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4028
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4029
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4030
+	 *
4031
+	 * @param string $condition_query_param_key
4032
+	 * @return string
4033
+	 */
4034
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4035
+	{
4036
+		$pos_of_star = strpos($condition_query_param_key, '*');
4037
+		if ($pos_of_star === false) {
4038
+			return $condition_query_param_key;
4039
+		} else {
4040
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4041
+			return $condition_query_param_sans_star;
4042
+		}
4043
+	}
4044
+
4045
+
4046
+
4047
+	/**
4048
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4049
+	 *
4050
+	 * @param                            mixed      array | string    $op_and_value
4051
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4052
+	 * @throws EE_Error
4053
+	 * @return string
4054
+	 */
4055
+	private function _construct_op_and_value($op_and_value, $field_obj)
4056
+	{
4057
+		if (is_array($op_and_value)) {
4058
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4059
+			if (! $operator) {
4060
+				$php_array_like_string = array();
4061
+				foreach ($op_and_value as $key => $value) {
4062
+					$php_array_like_string[] = "$key=>$value";
4063
+				}
4064
+				throw new EE_Error(
4065
+					sprintf(
4066
+						__(
4067
+							"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))",
4068
+							"event_espresso"
4069
+						),
4070
+						implode(",", $php_array_like_string)
4071
+					)
4072
+				);
4073
+			}
4074
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4075
+		} else {
4076
+			$operator = '=';
4077
+			$value = $op_and_value;
4078
+		}
4079
+		//check to see if the value is actually another field
4080
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4081
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4082
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4083
+			//in this case, the value should be an array, or at least a comma-separated list
4084
+			//it will need to handle a little differently
4085
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4086
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4087
+			return $operator . SP . $cleaned_value;
4088
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4089
+			//the value should be an array with count of two.
4090
+			if (count($value) !== 2) {
4091
+				throw new EE_Error(
4092
+					sprintf(
4093
+						__(
4094
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4095
+							'event_espresso'
4096
+						),
4097
+						"BETWEEN"
4098
+					)
4099
+				);
4100
+			}
4101
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4102
+			return $operator . SP . $cleaned_value;
4103
+		} elseif (in_array($operator, $this->_null_style_operators)) {
4104
+			if ($value !== null) {
4105
+				throw new EE_Error(
4106
+					sprintf(
4107
+						__(
4108
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4109
+							"event_espresso"
4110
+						),
4111
+						$value,
4112
+						$operator
4113
+					)
4114
+				);
4115
+			}
4116
+			return $operator;
4117
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
4118
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4119
+			//remove other junk. So just treat it as a string.
4120
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4121
+		} elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4122
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4123
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4124
+			throw new EE_Error(
4125
+				sprintf(
4126
+					__(
4127
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4128
+						'event_espresso'
4129
+					),
4130
+					$operator,
4131
+					$operator
4132
+				)
4133
+			);
4134
+		} elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4135
+			throw new EE_Error(
4136
+				sprintf(
4137
+					__(
4138
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4139
+						'event_espresso'
4140
+					),
4141
+					$operator,
4142
+					$operator
4143
+				)
4144
+			);
4145
+		} else {
4146
+			throw new EE_Error(
4147
+				sprintf(
4148
+					__(
4149
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4150
+						"event_espresso"
4151
+					),
4152
+					http_build_query($op_and_value)
4153
+				)
4154
+			);
4155
+		}
4156
+	}
4157
+
4158
+
4159
+
4160
+	/**
4161
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4162
+	 *
4163
+	 * @param array                      $values
4164
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4165
+	 *                                              '%s'
4166
+	 * @return string
4167
+	 * @throws \EE_Error
4168
+	 */
4169
+	public function _construct_between_value($values, $field_obj)
4170
+	{
4171
+		$cleaned_values = array();
4172
+		foreach ($values as $value) {
4173
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4174
+		}
4175
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4176
+	}
4177
+
4178
+
4179
+
4180
+	/**
4181
+	 * Takes an array or a comma-separated list of $values and cleans them
4182
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4183
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4184
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4185
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4186
+	 *
4187
+	 * @param mixed                      $values    array or comma-separated string
4188
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4189
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4190
+	 * @throws \EE_Error
4191
+	 */
4192
+	public function _construct_in_value($values, $field_obj)
4193
+	{
4194
+		//check if the value is a CSV list
4195
+		if (is_string($values)) {
4196
+			//in which case, turn it into an array
4197
+			$values = explode(",", $values);
4198
+		}
4199
+		$cleaned_values = array();
4200
+		foreach ($values as $value) {
4201
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4202
+		}
4203
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4204
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4205
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4206
+		if (empty($cleaned_values)) {
4207
+			$all_fields = $this->field_settings();
4208
+			$a_field = array_shift($all_fields);
4209
+			$main_table = $this->_get_main_table();
4210
+			$cleaned_values[] = "SELECT "
4211
+								. $a_field->get_table_column()
4212
+								. " FROM "
4213
+								. $main_table->get_table_name()
4214
+								. " WHERE FALSE";
4215
+		}
4216
+		return "(" . implode(",", $cleaned_values) . ")";
4217
+	}
4218
+
4219
+
4220
+
4221
+	/**
4222
+	 * @param mixed                      $value
4223
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4224
+	 * @throws EE_Error
4225
+	 * @return false|null|string
4226
+	 */
4227
+	private function _wpdb_prepare_using_field($value, $field_obj)
4228
+	{
4229
+		/** @type WPDB $wpdb */
4230
+		global $wpdb;
4231
+		if ($field_obj instanceof EE_Model_Field_Base) {
4232
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4233
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4234
+		} else {//$field_obj should really just be a data type
4235
+			if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4236
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4237
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4238
+			}
4239
+			return $wpdb->prepare($field_obj, $value);
4240
+		}
4241
+	}
4242
+
4243
+
4244
+
4245
+	/**
4246
+	 * Takes the input parameter and finds the model field that it indicates.
4247
+	 *
4248
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4249
+	 * @throws EE_Error
4250
+	 * @return EE_Model_Field_Base
4251
+	 */
4252
+	protected function _deduce_field_from_query_param($query_param_name)
4253
+	{
4254
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4255
+		//which will help us find the database table and column
4256
+		$query_param_parts = explode(".", $query_param_name);
4257
+		if (empty($query_param_parts)) {
4258
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4259
+				'event_espresso'), $query_param_name));
4260
+		}
4261
+		$number_of_parts = count($query_param_parts);
4262
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4263
+		if ($number_of_parts === 1) {
4264
+			$field_name = $last_query_param_part;
4265
+			$model_obj = $this;
4266
+		} else {// $number_of_parts >= 2
4267
+			//the last part is the column name, and there are only 2parts. therefore...
4268
+			$field_name = $last_query_param_part;
4269
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4270
+		}
4271
+		try {
4272
+			return $model_obj->field_settings_for($field_name);
4273
+		} catch (EE_Error $e) {
4274
+			return null;
4275
+		}
4276
+	}
4277
+
4278
+
4279
+
4280
+	/**
4281
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4282
+	 * alias and column which corresponds to it
4283
+	 *
4284
+	 * @param string $field_name
4285
+	 * @throws EE_Error
4286
+	 * @return string
4287
+	 */
4288
+	public function _get_qualified_column_for_field($field_name)
4289
+	{
4290
+		$all_fields = $this->field_settings();
4291
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4292
+		if ($field) {
4293
+			return $field->get_qualified_column();
4294
+		} else {
4295
+			throw new EE_Error(sprintf(__("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.",
4296
+				'event_espresso'), $field_name, get_class($this)));
4297
+		}
4298
+	}
4299
+
4300
+
4301
+
4302
+	/**
4303
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4304
+	 * Example usage:
4305
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4306
+	 *      array(),
4307
+	 *      ARRAY_A,
4308
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4309
+	 *  );
4310
+	 * is equivalent to
4311
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4312
+	 * and
4313
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4314
+	 *      array(
4315
+	 *          array(
4316
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4317
+	 *          ),
4318
+	 *          ARRAY_A,
4319
+	 *          implode(
4320
+	 *              ', ',
4321
+	 *              array_merge(
4322
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4323
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4324
+	 *              )
4325
+	 *          )
4326
+	 *      )
4327
+	 *  );
4328
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4329
+	 *
4330
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4331
+	 *                                            and the one whose fields you are selecting for example: when querying
4332
+	 *                                            tickets model and selecting fields from the tickets model you would
4333
+	 *                                            leave this parameter empty, because no models are needed to join
4334
+	 *                                            between the queried model and the selected one. Likewise when
4335
+	 *                                            querying the datetime model and selecting fields from the tickets
4336
+	 *                                            model, it would also be left empty, because there is a direct
4337
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4338
+	 *                                            them together. However, when querying from the event model and
4339
+	 *                                            selecting fields from the ticket model, you should provide the string
4340
+	 *                                            'Datetime', indicating that the event model must first join to the
4341
+	 *                                            datetime model in order to find its relation to ticket model.
4342
+	 *                                            Also, when querying from the venue model and selecting fields from
4343
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4344
+	 *                                            indicating you need to join the venue model to the event model,
4345
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4346
+	 *                                            This string is used to deduce the prefix that gets added onto the
4347
+	 *                                            models' tables qualified columns
4348
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4349
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4350
+	 *                                            qualified column names
4351
+	 * @return array|string
4352
+	 */
4353
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4354
+	{
4355
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4356
+		$qualified_columns = array();
4357
+		foreach ($this->field_settings() as $field_name => $field) {
4358
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4359
+		}
4360
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4361
+	}
4362
+
4363
+
4364
+
4365
+	/**
4366
+	 * constructs the select use on special limit joins
4367
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4368
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4369
+	 * (as that is typically where the limits would be set).
4370
+	 *
4371
+	 * @param  string       $table_alias The table the select is being built for
4372
+	 * @param  mixed|string $limit       The limit for this select
4373
+	 * @return string                The final select join element for the query.
4374
+	 */
4375
+	public function _construct_limit_join_select($table_alias, $limit)
4376
+	{
4377
+		$SQL = '';
4378
+		foreach ($this->_tables as $table_obj) {
4379
+			if ($table_obj instanceof EE_Primary_Table) {
4380
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4381
+					? $table_obj->get_select_join_limit($limit)
4382
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4383
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4384
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4385
+					? $table_obj->get_select_join_limit_join($limit)
4386
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4387
+			}
4388
+		}
4389
+		return $SQL;
4390
+	}
4391
+
4392
+
4393
+
4394
+	/**
4395
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4396
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4397
+	 *
4398
+	 * @return string SQL
4399
+	 * @throws \EE_Error
4400
+	 */
4401
+	public function _construct_internal_join()
4402
+	{
4403
+		$SQL = $this->_get_main_table()->get_table_sql();
4404
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4405
+		return $SQL;
4406
+	}
4407
+
4408
+
4409
+
4410
+	/**
4411
+	 * Constructs the SQL for joining all the tables on this model.
4412
+	 * Normally $alias should be the primary table's alias, but in cases where
4413
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4414
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4415
+	 * alias, this will construct SQL like:
4416
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4417
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4418
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4419
+	 *
4420
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4421
+	 * @return string
4422
+	 */
4423
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4424
+	{
4425
+		$SQL = '';
4426
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4427
+		foreach ($this->_tables as $table_obj) {
4428
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4429
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4430
+					//so we're joining to this table, meaning the table is already in
4431
+					//the FROM statement, BUT the primary table isn't. So we want
4432
+					//to add the inverse join sql
4433
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4434
+				} else {
4435
+					//just add a regular JOIN to this table from the primary table
4436
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4437
+				}
4438
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4439
+		}
4440
+		return $SQL;
4441
+	}
4442
+
4443
+
4444
+
4445
+	/**
4446
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4447
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4448
+	 * their data type (eg, '%s', '%d', etc)
4449
+	 *
4450
+	 * @return array
4451
+	 */
4452
+	public function _get_data_types()
4453
+	{
4454
+		$data_types = array();
4455
+		foreach ($this->field_settings() as $field_obj) {
4456
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4457
+			/** @var $field_obj EE_Model_Field_Base */
4458
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4459
+		}
4460
+		return $data_types;
4461
+	}
4462
+
4463
+
4464
+
4465
+	/**
4466
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4467
+	 *
4468
+	 * @param string $model_name
4469
+	 * @throws EE_Error
4470
+	 * @return EEM_Base
4471
+	 */
4472
+	public function get_related_model_obj($model_name)
4473
+	{
4474
+		$model_classname = "EEM_" . $model_name;
4475
+		if (! class_exists($model_classname)) {
4476
+			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",
4477
+				'event_espresso'), $model_name, $model_classname));
4478
+		}
4479
+		return call_user_func($model_classname . "::instance");
4480
+	}
4481
+
4482
+
4483
+
4484
+	/**
4485
+	 * Returns the array of EE_ModelRelations for this model.
4486
+	 *
4487
+	 * @return EE_Model_Relation_Base[]
4488
+	 */
4489
+	public function relation_settings()
4490
+	{
4491
+		return $this->_model_relations;
4492
+	}
4493
+
4494
+
4495
+
4496
+	/**
4497
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4498
+	 * because without THOSE models, this model probably doesn't have much purpose.
4499
+	 * (Eg, without an event, datetimes have little purpose.)
4500
+	 *
4501
+	 * @return EE_Belongs_To_Relation[]
4502
+	 */
4503
+	public function belongs_to_relations()
4504
+	{
4505
+		$belongs_to_relations = array();
4506
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4507
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4508
+				$belongs_to_relations[$model_name] = $relation_obj;
4509
+			}
4510
+		}
4511
+		return $belongs_to_relations;
4512
+	}
4513
+
4514
+
4515
+
4516
+	/**
4517
+	 * Returns the specified EE_Model_Relation, or throws an exception
4518
+	 *
4519
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4520
+	 * @throws EE_Error
4521
+	 * @return EE_Model_Relation_Base
4522
+	 */
4523
+	public function related_settings_for($relation_name)
4524
+	{
4525
+		$relatedModels = $this->relation_settings();
4526
+		if (! array_key_exists($relation_name, $relatedModels)) {
4527
+			throw new EE_Error(
4528
+				sprintf(
4529
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4530
+						'event_espresso'),
4531
+					$relation_name,
4532
+					$this->_get_class_name(),
4533
+					implode(', ', array_keys($relatedModels))
4534
+				)
4535
+			);
4536
+		}
4537
+		return $relatedModels[$relation_name];
4538
+	}
4539
+
4540
+
4541
+
4542
+	/**
4543
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4544
+	 * fields
4545
+	 *
4546
+	 * @param string $fieldName
4547
+	 * @throws EE_Error
4548
+	 * @return EE_Model_Field_Base
4549
+	 */
4550
+	public function field_settings_for($fieldName)
4551
+	{
4552
+		$fieldSettings = $this->field_settings(true);
4553
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4554
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4555
+				get_class($this)));
4556
+		}
4557
+		return $fieldSettings[$fieldName];
4558
+	}
4559
+
4560
+
4561
+
4562
+	/**
4563
+	 * Checks if this field exists on this model
4564
+	 *
4565
+	 * @param string $fieldName a key in the model's _field_settings array
4566
+	 * @return boolean
4567
+	 */
4568
+	public function has_field($fieldName)
4569
+	{
4570
+		$fieldSettings = $this->field_settings(true);
4571
+		if (isset($fieldSettings[$fieldName])) {
4572
+			return true;
4573
+		} else {
4574
+			return false;
4575
+		}
4576
+	}
4577
+
4578
+
4579
+
4580
+	/**
4581
+	 * Returns whether or not this model has a relation to the specified model
4582
+	 *
4583
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4584
+	 * @return boolean
4585
+	 */
4586
+	public function has_relation($relation_name)
4587
+	{
4588
+		$relations = $this->relation_settings();
4589
+		if (isset($relations[$relation_name])) {
4590
+			return true;
4591
+		} else {
4592
+			return false;
4593
+		}
4594
+	}
4595
+
4596
+
4597
+
4598
+	/**
4599
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4600
+	 * Eg, on EE_Answer that would be ANS_ID field object
4601
+	 *
4602
+	 * @param $field_obj
4603
+	 * @return boolean
4604
+	 */
4605
+	public function is_primary_key_field($field_obj)
4606
+	{
4607
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4608
+	}
4609
+
4610
+
4611
+
4612
+	/**
4613
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4614
+	 * Eg, on EE_Answer that would be ANS_ID field object
4615
+	 *
4616
+	 * @return EE_Model_Field_Base
4617
+	 * @throws EE_Error
4618
+	 */
4619
+	public function get_primary_key_field()
4620
+	{
4621
+		if ($this->_primary_key_field === null) {
4622
+			foreach ($this->field_settings(true) as $field_obj) {
4623
+				if ($this->is_primary_key_field($field_obj)) {
4624
+					$this->_primary_key_field = $field_obj;
4625
+					break;
4626
+				}
4627
+			}
4628
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4629
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4630
+					get_class($this)));
4631
+			}
4632
+		}
4633
+		return $this->_primary_key_field;
4634
+	}
4635
+
4636
+
4637
+
4638
+	/**
4639
+	 * Returns whether or not not there is a primary key on this model.
4640
+	 * Internally does some caching.
4641
+	 *
4642
+	 * @return boolean
4643
+	 */
4644
+	public function has_primary_key_field()
4645
+	{
4646
+		if ($this->_has_primary_key_field === null) {
4647
+			try {
4648
+				$this->get_primary_key_field();
4649
+				$this->_has_primary_key_field = true;
4650
+			} catch (EE_Error $e) {
4651
+				$this->_has_primary_key_field = false;
4652
+			}
4653
+		}
4654
+		return $this->_has_primary_key_field;
4655
+	}
4656
+
4657
+
4658
+
4659
+	/**
4660
+	 * Finds the first field of type $field_class_name.
4661
+	 *
4662
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4663
+	 *                                 EE_Foreign_Key_Field, etc
4664
+	 * @return EE_Model_Field_Base or null if none is found
4665
+	 */
4666
+	public function get_a_field_of_type($field_class_name)
4667
+	{
4668
+		foreach ($this->field_settings() as $field) {
4669
+			if ($field instanceof $field_class_name) {
4670
+				return $field;
4671
+			}
4672
+		}
4673
+		return null;
4674
+	}
4675
+
4676
+
4677
+
4678
+	/**
4679
+	 * Gets a foreign key field pointing to model.
4680
+	 *
4681
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4682
+	 * @return EE_Foreign_Key_Field_Base
4683
+	 * @throws EE_Error
4684
+	 */
4685
+	public function get_foreign_key_to($model_name)
4686
+	{
4687
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4688
+			foreach ($this->field_settings() as $field) {
4689
+				if (
4690
+					$field instanceof EE_Foreign_Key_Field_Base
4691
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4692
+				) {
4693
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4694
+					break;
4695
+				}
4696
+			}
4697
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4698
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4699
+					'event_espresso'), $model_name, get_class($this)));
4700
+			}
4701
+		}
4702
+		return $this->_cache_foreign_key_to_fields[$model_name];
4703
+	}
4704
+
4705
+
4706
+
4707
+	/**
4708
+	 * Gets the actual table for the table alias
4709
+	 *
4710
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4711
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4712
+	 *                            Either one works
4713
+	 * @return EE_Table_Base
4714
+	 */
4715
+	public function get_table_for_alias($table_alias)
4716
+	{
4717
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4718
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4719
+	}
4720
+
4721
+
4722
+
4723
+	/**
4724
+	 * Returns a flat array of all field son this model, instead of organizing them
4725
+	 * by table_alias as they are in the constructor.
4726
+	 *
4727
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4728
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4729
+	 */
4730
+	public function field_settings($include_db_only_fields = false)
4731
+	{
4732
+		if ($include_db_only_fields) {
4733
+			if ($this->_cached_fields === null) {
4734
+				$this->_cached_fields = array();
4735
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4736
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4737
+						$this->_cached_fields[$field_name] = $field_obj;
4738
+					}
4739
+				}
4740
+			}
4741
+			return $this->_cached_fields;
4742
+		} else {
4743
+			if ($this->_cached_fields_non_db_only === null) {
4744
+				$this->_cached_fields_non_db_only = array();
4745
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4746
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4747
+						/** @var $field_obj EE_Model_Field_Base */
4748
+						if (! $field_obj->is_db_only_field()) {
4749
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4750
+						}
4751
+					}
4752
+				}
4753
+			}
4754
+			return $this->_cached_fields_non_db_only;
4755
+		}
4756
+	}
4757
+
4758
+
4759
+
4760
+	/**
4761
+	 *        cycle though array of attendees and create objects out of each item
4762
+	 *
4763
+	 * @access        private
4764
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4765
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4766
+	 *                           numerically indexed)
4767
+	 * @throws \EE_Error
4768
+	 */
4769
+	protected function _create_objects($rows = array())
4770
+	{
4771
+		$array_of_objects = array();
4772
+		if (empty($rows)) {
4773
+			return array();
4774
+		}
4775
+		$count_if_model_has_no_primary_key = 0;
4776
+		$has_primary_key = $this->has_primary_key_field();
4777
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4778
+		foreach ((array)$rows as $row) {
4779
+			if (empty($row)) {
4780
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4781
+				return array();
4782
+			}
4783
+			//check if we've already set this object in the results array,
4784
+			//in which case there's no need to process it further (again)
4785
+			if ($has_primary_key) {
4786
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4787
+					$row,
4788
+					$primary_key_field->get_qualified_column(),
4789
+					$primary_key_field->get_table_column()
4790
+				);
4791
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4792
+					continue;
4793
+				}
4794
+			}
4795
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4796
+			if (! $classInstance) {
4797
+				throw new EE_Error(
4798
+					sprintf(
4799
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4800
+						$this->get_this_model_name(),
4801
+						http_build_query($row)
4802
+					)
4803
+				);
4804
+			}
4805
+			//set the timezone on the instantiated objects
4806
+			$classInstance->set_timezone($this->_timezone);
4807
+			//make sure if there is any timezone setting present that we set the timezone for the object
4808
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4809
+			$array_of_objects[$key] = $classInstance;
4810
+			//also, for all the relations of type BelongsTo, see if we can cache
4811
+			//those related models
4812
+			//(we could do this for other relations too, but if there are conditions
4813
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4814
+			//so it requires a little more thought than just caching them immediately...)
4815
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4816
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4817
+					//check if this model's INFO is present. If so, cache it on the model
4818
+					$other_model = $relation_obj->get_other_model();
4819
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4820
+					//if we managed to make a model object from the results, cache it on the main model object
4821
+					if ($other_model_obj_maybe) {
4822
+						//set timezone on these other model objects if they are present
4823
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4824
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4825
+					}
4826
+				}
4827
+			}
4828
+		}
4829
+		return $array_of_objects;
4830
+	}
4831
+
4832
+
4833
+
4834
+	/**
4835
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4836
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4837
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4838
+	 * object (as set in the model_field!).
4839
+	 *
4840
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4841
+	 */
4842
+	public function create_default_object()
4843
+	{
4844
+		$this_model_fields_and_values = array();
4845
+		//setup the row using default values;
4846
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4847
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4848
+		}
4849
+		$className = $this->_get_class_name();
4850
+		$classInstance = EE_Registry::instance()
4851
+									->load_class($className, array($this_model_fields_and_values), false, false);
4852
+		return $classInstance;
4853
+	}
4854
+
4855
+
4856
+
4857
+	/**
4858
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4859
+	 *                             or an stdClass where each property is the name of a column,
4860
+	 * @return EE_Base_Class
4861
+	 * @throws \EE_Error
4862
+	 */
4863
+	public function instantiate_class_from_array_or_object($cols_n_values)
4864
+	{
4865
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4866
+			$cols_n_values = get_object_vars($cols_n_values);
4867
+		}
4868
+		$primary_key = null;
4869
+		//make sure the array only has keys that are fields/columns on this model
4870
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4871
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4872
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4873
+		}
4874
+		$className = $this->_get_class_name();
4875
+		//check we actually found results that we can use to build our model object
4876
+		//if not, return null
4877
+		if ($this->has_primary_key_field()) {
4878
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4879
+				return null;
4880
+			}
4881
+		} else if ($this->unique_indexes()) {
4882
+			$first_column = reset($this_model_fields_n_values);
4883
+			if (empty($first_column)) {
4884
+				return null;
4885
+			}
4886
+		}
4887
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4888
+		if ($primary_key) {
4889
+			$classInstance = $this->get_from_entity_map($primary_key);
4890
+			if (! $classInstance) {
4891
+				$classInstance = EE_Registry::instance()
4892
+											->load_class($className,
4893
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4894
+				// add this new object to the entity map
4895
+				$classInstance = $this->add_to_entity_map($classInstance);
4896
+			}
4897
+		} else {
4898
+			$classInstance = EE_Registry::instance()
4899
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4900
+											true, false);
4901
+		}
4902
+		//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.
4903
+		$this->set_timezone($classInstance->get_timezone());
4904
+		return $classInstance;
4905
+	}
4906
+
4907
+
4908
+
4909
+	/**
4910
+	 * Gets the model object from the  entity map if it exists
4911
+	 *
4912
+	 * @param int|string $id the ID of the model object
4913
+	 * @return EE_Base_Class
4914
+	 */
4915
+	public function get_from_entity_map($id)
4916
+	{
4917
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4918
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4919
+	}
4920
+
4921
+
4922
+
4923
+	/**
4924
+	 * add_to_entity_map
4925
+	 * Adds the object to the model's entity mappings
4926
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4927
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4928
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4929
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4930
+	 *        then this method should be called immediately after the update query
4931
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4932
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4933
+	 *
4934
+	 * @param    EE_Base_Class $object
4935
+	 * @throws EE_Error
4936
+	 * @return \EE_Base_Class
4937
+	 */
4938
+	public function add_to_entity_map(EE_Base_Class $object)
4939
+	{
4940
+		$className = $this->_get_class_name();
4941
+		if (! $object instanceof $className) {
4942
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4943
+				is_object($object) ? get_class($object) : $object, $className));
4944
+		}
4945
+		/** @var $object EE_Base_Class */
4946
+		if (! $object->ID()) {
4947
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4948
+				"event_espresso"), get_class($this)));
4949
+		}
4950
+		// double check it's not already there
4951
+		$classInstance = $this->get_from_entity_map($object->ID());
4952
+		if ($classInstance) {
4953
+			return $classInstance;
4954
+		} else {
4955
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4956
+			return $object;
4957
+		}
4958
+	}
4959
+
4960
+
4961
+
4962
+	/**
4963
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4964
+	 * if no identifier is provided, then the entire entity map is emptied
4965
+	 *
4966
+	 * @param int|string $id the ID of the model object
4967
+	 * @return boolean
4968
+	 */
4969
+	public function clear_entity_map($id = null)
4970
+	{
4971
+		if (empty($id)) {
4972
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4973
+			return true;
4974
+		}
4975
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4976
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4977
+			return true;
4978
+		}
4979
+		return false;
4980
+	}
4981
+
4982
+
4983
+
4984
+	/**
4985
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4986
+	 * Given an array where keys are column (or column alias) names and values,
4987
+	 * returns an array of their corresponding field names and database values
4988
+	 *
4989
+	 * @param array $cols_n_values
4990
+	 * @return array
4991
+	 */
4992
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4993
+	{
4994
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4995
+	}
4996
+
4997
+
4998
+
4999
+	/**
5000
+	 * _deduce_fields_n_values_from_cols_n_values
5001
+	 * Given an array where keys are column (or column alias) names and values,
5002
+	 * returns an array of their corresponding field names and database values
5003
+	 *
5004
+	 * @param string $cols_n_values
5005
+	 * @return array
5006
+	 */
5007
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5008
+	{
5009
+		$this_model_fields_n_values = array();
5010
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5011
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5012
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5013
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5014
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5015
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5016
+					if (! $field_obj->is_db_only_field()) {
5017
+						//prepare field as if its coming from db
5018
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5019
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5020
+					}
5021
+				}
5022
+			} else {
5023
+				//the table's rows existed. Use their values
5024
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5025
+					if (! $field_obj->is_db_only_field()) {
5026
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5027
+							$cols_n_values, $field_obj->get_qualified_column(),
5028
+							$field_obj->get_table_column()
5029
+						);
5030
+					}
5031
+				}
5032
+			}
5033
+		}
5034
+		return $this_model_fields_n_values;
5035
+	}
5036
+
5037
+
5038
+
5039
+	/**
5040
+	 * @param $cols_n_values
5041
+	 * @param $qualified_column
5042
+	 * @param $regular_column
5043
+	 * @return null
5044
+	 */
5045
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5046
+	{
5047
+		$value = null;
5048
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5049
+		//does the field on the model relate to this column retrieved from the db?
5050
+		//or is it a db-only field? (not relating to the model)
5051
+		if (isset($cols_n_values[$qualified_column])) {
5052
+			$value = $cols_n_values[$qualified_column];
5053
+		} elseif (isset($cols_n_values[$regular_column])) {
5054
+			$value = $cols_n_values[$regular_column];
5055
+		}
5056
+		return $value;
5057
+	}
5058
+
5059
+
5060
+
5061
+	/**
5062
+	 * refresh_entity_map_from_db
5063
+	 * Makes sure the model object in the entity map at $id assumes the values
5064
+	 * of the database (opposite of EE_base_Class::save())
5065
+	 *
5066
+	 * @param int|string $id
5067
+	 * @return EE_Base_Class
5068
+	 * @throws \EE_Error
5069
+	 */
5070
+	public function refresh_entity_map_from_db($id)
5071
+	{
5072
+		$obj_in_map = $this->get_from_entity_map($id);
5073
+		if ($obj_in_map) {
5074
+			$wpdb_results = $this->_get_all_wpdb_results(
5075
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5076
+			);
5077
+			if ($wpdb_results && is_array($wpdb_results)) {
5078
+				$one_row = reset($wpdb_results);
5079
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5080
+					$obj_in_map->set_from_db($field_name, $db_value);
5081
+				}
5082
+				//clear the cache of related model objects
5083
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5084
+					$obj_in_map->clear_cache($relation_name, null, true);
5085
+				}
5086
+			}
5087
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5088
+			return $obj_in_map;
5089
+		} else {
5090
+			return $this->get_one_by_ID($id);
5091
+		}
5092
+	}
5093
+
5094
+
5095
+
5096
+	/**
5097
+	 * refresh_entity_map_with
5098
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5099
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5100
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5101
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5102
+	 *
5103
+	 * @param int|string    $id
5104
+	 * @param EE_Base_Class $replacing_model_obj
5105
+	 * @return \EE_Base_Class
5106
+	 * @throws \EE_Error
5107
+	 */
5108
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5109
+	{
5110
+		$obj_in_map = $this->get_from_entity_map($id);
5111
+		if ($obj_in_map) {
5112
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5113
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5114
+					$obj_in_map->set($field_name, $value);
5115
+				}
5116
+				//make the model object in the entity map's cache match the $replacing_model_obj
5117
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5118
+					$obj_in_map->clear_cache($relation_name, null, true);
5119
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5120
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5121
+					}
5122
+				}
5123
+			}
5124
+			return $obj_in_map;
5125
+		} else {
5126
+			$this->add_to_entity_map($replacing_model_obj);
5127
+			return $replacing_model_obj;
5128
+		}
5129
+	}
5130
+
5131
+
5132
+
5133
+	/**
5134
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5135
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5136
+	 * require_once($this->_getClassName().".class.php");
5137
+	 *
5138
+	 * @return string
5139
+	 */
5140
+	private function _get_class_name()
5141
+	{
5142
+		return "EE_" . $this->get_this_model_name();
5143
+	}
5144
+
5145
+
5146
+
5147
+	/**
5148
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5149
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5150
+	 * it would be 'Events'.
5151
+	 *
5152
+	 * @param int $quantity
5153
+	 * @return string
5154
+	 */
5155
+	public function item_name($quantity = 1)
5156
+	{
5157
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5158
+	}
5159
+
5160
+
5161
+
5162
+	/**
5163
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5164
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5165
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5166
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5167
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5168
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5169
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5170
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5171
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5172
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5173
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5174
+	 *        return $previousReturnValue.$returnString;
5175
+	 * }
5176
+	 * require('EEM_Answer.model.php');
5177
+	 * $answer=EEM_Answer::instance();
5178
+	 * echo $answer->my_callback('monkeys',100);
5179
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5180
+	 *
5181
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5182
+	 * @param array  $args       array of original arguments passed to the function
5183
+	 * @throws EE_Error
5184
+	 * @return mixed whatever the plugin which calls add_filter decides
5185
+	 */
5186
+	public function __call($methodName, $args)
5187
+	{
5188
+		$className = get_class($this);
5189
+		$tagName = "FHEE__{$className}__{$methodName}";
5190
+		if (! has_filter($tagName)) {
5191
+			throw new EE_Error(
5192
+				sprintf(
5193
+					__('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 );',
5194
+						'event_espresso'),
5195
+					$methodName,
5196
+					$className,
5197
+					$tagName,
5198
+					'<br />'
5199
+				)
5200
+			);
5201
+		}
5202
+		return apply_filters($tagName, null, $this, $args);
5203
+	}
5204
+
5205
+
5206
+
5207
+	/**
5208
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5209
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5210
+	 *
5211
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5212
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5213
+	 *                                                       the object's class name
5214
+	 *                                                       or object's ID
5215
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5216
+	 *                                                       exists in the database. If it does not, we add it
5217
+	 * @throws EE_Error
5218
+	 * @return EE_Base_Class
5219
+	 */
5220
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5221
+	{
5222
+		$className = $this->_get_class_name();
5223
+		if ($base_class_obj_or_id instanceof $className) {
5224
+			$model_object = $base_class_obj_or_id;
5225
+		} else {
5226
+			$primary_key_field = $this->get_primary_key_field();
5227
+			if (
5228
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5229
+				&& (
5230
+					is_int($base_class_obj_or_id)
5231
+					|| is_string($base_class_obj_or_id)
5232
+				)
5233
+			) {
5234
+				// assume it's an ID.
5235
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5236
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5237
+			} else if (
5238
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5239
+				&& is_string($base_class_obj_or_id)
5240
+			) {
5241
+				// assume its a string representation of the object
5242
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5243
+			} else {
5244
+				throw new EE_Error(
5245
+					sprintf(
5246
+						__(
5247
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5248
+							'event_espresso'
5249
+						),
5250
+						$base_class_obj_or_id,
5251
+						$this->_get_class_name(),
5252
+						print_r($base_class_obj_or_id, true)
5253
+					)
5254
+				);
5255
+			}
5256
+		}
5257
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5258
+			$model_object->save();
5259
+		}
5260
+		return $model_object;
5261
+	}
5262
+
5263
+
5264
+
5265
+	/**
5266
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5267
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5268
+	 * returns it ID.
5269
+	 *
5270
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5271
+	 * @return int|string depending on the type of this model object's ID
5272
+	 * @throws EE_Error
5273
+	 */
5274
+	public function ensure_is_ID($base_class_obj_or_id)
5275
+	{
5276
+		$className = $this->_get_class_name();
5277
+		if ($base_class_obj_or_id instanceof $className) {
5278
+			/** @var $base_class_obj_or_id EE_Base_Class */
5279
+			$id = $base_class_obj_or_id->ID();
5280
+		} elseif (is_int($base_class_obj_or_id)) {
5281
+			//assume it's an ID
5282
+			$id = $base_class_obj_or_id;
5283
+		} elseif (is_string($base_class_obj_or_id)) {
5284
+			//assume its a string representation of the object
5285
+			$id = $base_class_obj_or_id;
5286
+		} else {
5287
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5288
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5289
+				print_r($base_class_obj_or_id, true)));
5290
+		}
5291
+		return $id;
5292
+	}
5293
+
5294
+
5295
+
5296
+	/**
5297
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5298
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5299
+	 * been sanitized and converted into the appropriate domain.
5300
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5301
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5302
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5303
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5304
+	 * $EVT = EEM_Event::instance(); $old_setting =
5305
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5306
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5307
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5308
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5309
+	 *
5310
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5311
+	 * @return void
5312
+	 */
5313
+	public function assume_values_already_prepared_by_model_object(
5314
+		$values_already_prepared = self::not_prepared_by_model_object
5315
+	) {
5316
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5317
+	}
5318
+
5319
+
5320
+
5321
+	/**
5322
+	 * Read comments for assume_values_already_prepared_by_model_object()
5323
+	 *
5324
+	 * @return int
5325
+	 */
5326
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5327
+	{
5328
+		return $this->_values_already_prepared_by_model_object;
5329
+	}
5330
+
5331
+
5332
+
5333
+	/**
5334
+	 * Gets all the indexes on this model
5335
+	 *
5336
+	 * @return EE_Index[]
5337
+	 */
5338
+	public function indexes()
5339
+	{
5340
+		return $this->_indexes;
5341
+	}
5342
+
5343
+
5344
+
5345
+	/**
5346
+	 * Gets all the Unique Indexes on this model
5347
+	 *
5348
+	 * @return EE_Unique_Index[]
5349
+	 */
5350
+	public function unique_indexes()
5351
+	{
5352
+		$unique_indexes = array();
5353
+		foreach ($this->_indexes as $name => $index) {
5354
+			if ($index instanceof EE_Unique_Index) {
5355
+				$unique_indexes [$name] = $index;
5356
+			}
5357
+		}
5358
+		return $unique_indexes;
5359
+	}
5360
+
5361
+
5362
+
5363
+	/**
5364
+	 * Gets all the fields which, when combined, make the primary key.
5365
+	 * This is usually just an array with 1 element (the primary key), but in cases
5366
+	 * where there is no primary key, it's a combination of fields as defined
5367
+	 * on a primary index
5368
+	 *
5369
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5370
+	 * @throws \EE_Error
5371
+	 */
5372
+	public function get_combined_primary_key_fields()
5373
+	{
5374
+		foreach ($this->indexes() as $index) {
5375
+			if ($index instanceof EE_Primary_Key_Index) {
5376
+				return $index->fields();
5377
+			}
5378
+		}
5379
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5380
+	}
5381
+
5382
+
5383
+
5384
+	/**
5385
+	 * Used to build a primary key string (when the model has no primary key),
5386
+	 * which can be used a unique string to identify this model object.
5387
+	 *
5388
+	 * @param array $cols_n_values keys are field names, values are their values
5389
+	 * @return string
5390
+	 * @throws \EE_Error
5391
+	 */
5392
+	public function get_index_primary_key_string($cols_n_values)
5393
+	{
5394
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5395
+			$this->get_combined_primary_key_fields());
5396
+		return http_build_query($cols_n_values_for_primary_key_index);
5397
+	}
5398
+
5399
+
5400
+
5401
+	/**
5402
+	 * Gets the field values from the primary key string
5403
+	 *
5404
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5405
+	 * @param string $index_primary_key_string
5406
+	 * @return null|array
5407
+	 * @throws \EE_Error
5408
+	 */
5409
+	public function parse_index_primary_key_string($index_primary_key_string)
5410
+	{
5411
+		$key_fields = $this->get_combined_primary_key_fields();
5412
+		//check all of them are in the $id
5413
+		$key_vals_in_combined_pk = array();
5414
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5415
+		foreach ($key_fields as $key_field_name => $field_obj) {
5416
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5417
+				return null;
5418
+			}
5419
+		}
5420
+		return $key_vals_in_combined_pk;
5421
+	}
5422
+
5423
+
5424
+
5425
+	/**
5426
+	 * verifies that an array of key-value pairs for model fields has a key
5427
+	 * for each field comprising the primary key index
5428
+	 *
5429
+	 * @param array $key_vals
5430
+	 * @return boolean
5431
+	 * @throws \EE_Error
5432
+	 */
5433
+	public function has_all_combined_primary_key_fields($key_vals)
5434
+	{
5435
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5436
+		foreach ($keys_it_should_have as $key) {
5437
+			if (! isset($key_vals[$key])) {
5438
+				return false;
5439
+			}
5440
+		}
5441
+		return true;
5442
+	}
5443
+
5444
+
5445
+
5446
+	/**
5447
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5448
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5449
+	 *
5450
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5451
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5452
+	 * @throws EE_Error
5453
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5454
+	 *                                                              indexed)
5455
+	 */
5456
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5457
+	{
5458
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5459
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5460
+		} elseif (is_array($model_object_or_attributes_array)) {
5461
+			$attributes_array = $model_object_or_attributes_array;
5462
+		} else {
5463
+			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",
5464
+				"event_espresso"), $model_object_or_attributes_array));
5465
+		}
5466
+		//even copies obviously won't have the same ID, so remove the primary key
5467
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5468
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5469
+			unset($attributes_array[$this->primary_key_name()]);
5470
+		}
5471
+		if (isset($query_params[0])) {
5472
+			$query_params[0] = array_merge($attributes_array, $query_params);
5473
+		} else {
5474
+			$query_params[0] = $attributes_array;
5475
+		}
5476
+		return $this->get_all($query_params);
5477
+	}
5478
+
5479
+
5480
+
5481
+	/**
5482
+	 * Gets the first copy we find. See get_all_copies for more details
5483
+	 *
5484
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5485
+	 * @param array $query_params
5486
+	 * @return EE_Base_Class
5487
+	 * @throws \EE_Error
5488
+	 */
5489
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5490
+	{
5491
+		if (! is_array($query_params)) {
5492
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5493
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5494
+					gettype($query_params)), '4.6.0');
5495
+			$query_params = array();
5496
+		}
5497
+		$query_params['limit'] = 1;
5498
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5499
+		if (is_array($copies)) {
5500
+			return array_shift($copies);
5501
+		} else {
5502
+			return null;
5503
+		}
5504
+	}
5505
+
5506
+
5507
+
5508
+	/**
5509
+	 * Updates the item with the specified id. Ignores default query parameters because
5510
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5511
+	 *
5512
+	 * @param array      $fields_n_values keys are field names, values are their new values
5513
+	 * @param int|string $id              the value of the primary key to update
5514
+	 * @return int number of rows updated
5515
+	 * @throws \EE_Error
5516
+	 */
5517
+	public function update_by_ID($fields_n_values, $id)
5518
+	{
5519
+		$query_params = array(
5520
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5521
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5522
+		);
5523
+		return $this->update($fields_n_values, $query_params);
5524
+	}
5525
+
5526
+
5527
+
5528
+	/**
5529
+	 * Changes an operator which was supplied to the models into one usable in SQL
5530
+	 *
5531
+	 * @param string $operator_supplied
5532
+	 * @return string an operator which can be used in SQL
5533
+	 * @throws EE_Error
5534
+	 */
5535
+	private function _prepare_operator_for_sql($operator_supplied)
5536
+	{
5537
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5538
+			: null;
5539
+		if ($sql_operator) {
5540
+			return $sql_operator;
5541
+		} else {
5542
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5543
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5544
+		}
5545
+	}
5546
+
5547
+
5548
+
5549
+	/**
5550
+	 * Gets an array where keys are the primary keys and values are their 'names'
5551
+	 * (as determined by the model object's name() function, which is often overridden)
5552
+	 *
5553
+	 * @param array $query_params like get_all's
5554
+	 * @return string[]
5555
+	 * @throws \EE_Error
5556
+	 */
5557
+	public function get_all_names($query_params = array())
5558
+	{
5559
+		$objs = $this->get_all($query_params);
5560
+		$names = array();
5561
+		foreach ($objs as $obj) {
5562
+			$names[$obj->ID()] = $obj->name();
5563
+		}
5564
+		return $names;
5565
+	}
5566
+
5567
+
5568
+
5569
+	/**
5570
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5571
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5572
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5573
+	 * array_keys() on $model_objects.
5574
+	 *
5575
+	 * @param \EE_Base_Class[] $model_objects
5576
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5577
+	 *                                               in the returned array
5578
+	 * @return array
5579
+	 * @throws \EE_Error
5580
+	 */
5581
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5582
+	{
5583
+		if (! $this->has_primary_key_field()) {
5584
+			if (WP_DEBUG) {
5585
+				EE_Error::add_error(
5586
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5587
+					__FILE__,
5588
+					__FUNCTION__,
5589
+					__LINE__
5590
+				);
5591
+			}
5592
+		}
5593
+		$IDs = array();
5594
+		foreach ($model_objects as $model_object) {
5595
+			$id = $model_object->ID();
5596
+			if (! $id) {
5597
+				if ($filter_out_empty_ids) {
5598
+					continue;
5599
+				}
5600
+				if (WP_DEBUG) {
5601
+					EE_Error::add_error(
5602
+						__(
5603
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5604
+							'event_espresso'
5605
+						),
5606
+						__FILE__,
5607
+						__FUNCTION__,
5608
+						__LINE__
5609
+					);
5610
+				}
5611
+			}
5612
+			$IDs[] = $id;
5613
+		}
5614
+		return $IDs;
5615
+	}
5616
+
5617
+
5618
+
5619
+	/**
5620
+	 * Returns the string used in capabilities relating to this model. If there
5621
+	 * are no capabilities that relate to this model returns false
5622
+	 *
5623
+	 * @return string|false
5624
+	 */
5625
+	public function cap_slug()
5626
+	{
5627
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5628
+	}
5629
+
5630
+
5631
+
5632
+	/**
5633
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5634
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5635
+	 * only returns the cap restrictions array in that context (ie, the array
5636
+	 * at that key)
5637
+	 *
5638
+	 * @param string $context
5639
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5640
+	 * @throws \EE_Error
5641
+	 */
5642
+	public function cap_restrictions($context = EEM_Base::caps_read)
5643
+	{
5644
+		EEM_Base::verify_is_valid_cap_context($context);
5645
+		//check if we ought to run the restriction generator first
5646
+		if (
5647
+			isset($this->_cap_restriction_generators[$context])
5648
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5649
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5650
+		) {
5651
+			$this->_cap_restrictions[$context] = array_merge(
5652
+				$this->_cap_restrictions[$context],
5653
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5654
+			);
5655
+		}
5656
+		//and make sure we've finalized the construction of each restriction
5657
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5658
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5659
+				$where_conditions_obj->_finalize_construct($this);
5660
+			}
5661
+		}
5662
+		return $this->_cap_restrictions[$context];
5663
+	}
5664
+
5665
+
5666
+
5667
+	/**
5668
+	 * Indicating whether or not this model thinks its a wp core model
5669
+	 *
5670
+	 * @return boolean
5671
+	 */
5672
+	public function is_wp_core_model()
5673
+	{
5674
+		return $this->_wp_core_model;
5675
+	}
5676
+
5677
+
5678
+
5679
+	/**
5680
+	 * Gets all the caps that are missing which impose a restriction on
5681
+	 * queries made in this context
5682
+	 *
5683
+	 * @param string $context one of EEM_Base::caps_ constants
5684
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5685
+	 * @throws \EE_Error
5686
+	 */
5687
+	public function caps_missing($context = EEM_Base::caps_read)
5688
+	{
5689
+		$missing_caps = array();
5690
+		$cap_restrictions = $this->cap_restrictions($context);
5691
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5692
+			if (! EE_Capabilities::instance()
5693
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5694
+			) {
5695
+				$missing_caps[$cap] = $restriction_if_no_cap;
5696
+			}
5697
+		}
5698
+		return $missing_caps;
5699
+	}
5700
+
5701
+
5702
+
5703
+	/**
5704
+	 * Gets the mapping from capability contexts to action strings used in capability names
5705
+	 *
5706
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5707
+	 * one of 'read', 'edit', or 'delete'
5708
+	 */
5709
+	public function cap_contexts_to_cap_action_map()
5710
+	{
5711
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5712
+			$this);
5713
+	}
5714
+
5715
+
5716
+
5717
+	/**
5718
+	 * Gets the action string for the specified capability context
5719
+	 *
5720
+	 * @param string $context
5721
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5722
+	 * @throws \EE_Error
5723
+	 */
5724
+	public function cap_action_for_context($context)
5725
+	{
5726
+		$mapping = $this->cap_contexts_to_cap_action_map();
5727
+		if (isset($mapping[$context])) {
5728
+			return $mapping[$context];
5729
+		}
5730
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5731
+			return $action;
5732
+		}
5733
+		throw new EE_Error(
5734
+			sprintf(
5735
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5736
+				$context,
5737
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5738
+			)
5739
+		);
5740
+	}
5741
+
5742
+
5743
+
5744
+	/**
5745
+	 * Returns all the capability contexts which are valid when querying models
5746
+	 *
5747
+	 * @return array
5748
+	 */
5749
+	public static function valid_cap_contexts()
5750
+	{
5751
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5752
+			self::caps_read,
5753
+			self::caps_read_admin,
5754
+			self::caps_edit,
5755
+			self::caps_delete,
5756
+		));
5757
+	}
5758
+
5759
+
5760
+
5761
+	/**
5762
+	 * Returns all valid options for 'default_where_conditions'
5763
+	 *
5764
+	 * @return array
5765
+	 */
5766
+	public static function valid_default_where_conditions()
5767
+	{
5768
+		return array(
5769
+			EEM_Base::default_where_conditions_all,
5770
+			EEM_Base::default_where_conditions_this_only,
5771
+			EEM_Base::default_where_conditions_others_only,
5772
+			EEM_Base::default_where_conditions_minimum_all,
5773
+			EEM_Base::default_where_conditions_minimum_others,
5774
+			EEM_Base::default_where_conditions_none
5775
+		);
5776
+	}
5777
+
5778
+	// public static function default_where_conditions_full
5779
+	/**
5780
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5781
+	 *
5782
+	 * @param string $context
5783
+	 * @return bool
5784
+	 * @throws \EE_Error
5785
+	 */
5786
+	static public function verify_is_valid_cap_context($context)
5787
+	{
5788
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5789
+		if (in_array($context, $valid_cap_contexts)) {
5790
+			return true;
5791
+		} else {
5792
+			throw new EE_Error(
5793
+				sprintf(
5794
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5795
+						'event_espresso'),
5796
+					$context,
5797
+					'EEM_Base',
5798
+					implode(',', $valid_cap_contexts)
5799
+				)
5800
+			);
5801
+		}
5802
+	}
5803
+
5804
+
5805
+
5806
+	/**
5807
+	 * Clears all the models field caches. This is only useful when a sub-class
5808
+	 * might have added a field or something and these caches might be invalidated
5809
+	 */
5810
+	protected function _invalidate_field_caches()
5811
+	{
5812
+		$this->_cache_foreign_key_to_fields = array();
5813
+		$this->_cached_fields = null;
5814
+		$this->_cached_fields_non_db_only = null;
5815
+	}
5816
+
5817
+
5818
+
5819
+	/**
5820
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
5821
+	 * (eg "and", "or", "not").
5822
+	 *
5823
+	 * @return array
5824
+	 */
5825
+	public function logic_query_param_keys()
5826
+	{
5827
+		return $this->_logic_query_param_keys;
5828
+	}
5829
+
5830
+
5831
+
5832
+	/**
5833
+	 * Determines whether or not the where query param array key is for a logic query param.
5834
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5835
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5836
+	 *
5837
+	 * @param $query_param_key
5838
+	 * @return bool
5839
+	 */
5840
+	public function is_logic_query_param_key($query_param_key)
5841
+	{
5842
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5843
+			if ($query_param_key === $logic_query_param_key
5844
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
5845
+			) {
5846
+				return true;
5847
+			}
5848
+		}
5849
+		return false;
5850
+	}
5851 5851
 
5852 5852
 
5853 5853
 
Please login to merge, or discard this patch.
Spacing   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -516,8 +516,8 @@  discard block
 block discarded – undo
516 516
     protected function __construct($timezone = null)
517 517
     {
518 518
         // check that the model has not been loaded too soon
519
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
520
-            throw new EE_Error (
519
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
520
+            throw new EE_Error(
521 521
                 sprintf(
522 522
                     __('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.',
523 523
                         'event_espresso'),
@@ -537,7 +537,7 @@  discard block
 block discarded – undo
537 537
          *
538 538
          * @var EE_Table_Base[] $_tables
539 539
          */
540
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
+        $this->_tables = apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
541 541
         foreach ($this->_tables as $table_alias => $table_obj) {
542 542
             /** @var $table_obj EE_Table_Base */
543 543
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -552,10 +552,10 @@  discard block
 block discarded – undo
552 552
          *
553 553
          * @param EE_Model_Field_Base[] $_fields
554 554
          */
555
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
+        $this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
556 556
         $this->_invalidate_field_caches();
557 557
         foreach ($this->_fields as $table_alias => $fields_for_table) {
558
-            if (! array_key_exists($table_alias, $this->_tables)) {
558
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
559 559
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
560 560
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
561 561
             }
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
          *
584 584
          * @param EE_Model_Relation_Base[] $_model_relations
585 585
          */
586
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
+        $this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
587 587
             $this->_model_relations);
588 588
         foreach ($this->_model_relations as $model_name => $relation_obj) {
589 589
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -595,12 +595,12 @@  discard block
 block discarded – undo
595 595
         }
596 596
         $this->set_timezone($timezone);
597 597
         //finalize default where condition strategy, or set default
598
-        if (! $this->_default_where_conditions_strategy) {
598
+        if ( ! $this->_default_where_conditions_strategy) {
599 599
             //nothing was set during child constructor, so set default
600 600
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
601 601
         }
602 602
         $this->_default_where_conditions_strategy->_finalize_construct($this);
603
-        if (! $this->_minimum_where_conditions_strategy) {
603
+        if ( ! $this->_minimum_where_conditions_strategy) {
604 604
             //nothing was set during child constructor, so set default
605 605
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
606 606
         }
@@ -613,7 +613,7 @@  discard block
 block discarded – undo
613 613
         //initialize the standard cap restriction generators if none were specified by the child constructor
614 614
         if ($this->_cap_restriction_generators !== false) {
615 615
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
616
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
617 617
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
618 618
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
619 619
                         new EE_Restriction_Generator_Protected(),
@@ -626,10 +626,10 @@  discard block
 block discarded – undo
626 626
         //if there are cap restriction generators, use them to make the default cap restrictions
627 627
         if ($this->_cap_restriction_generators !== false) {
628 628
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
629
-                if (! $generator_object) {
629
+                if ( ! $generator_object) {
630 630
                     continue;
631 631
                 }
632
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
633 633
                     throw new EE_Error(
634 634
                         sprintf(
635 635
                             __('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.',
@@ -640,12 +640,12 @@  discard block
 block discarded – undo
640 640
                     );
641 641
                 }
642 642
                 $action = $this->cap_action_for_context($context);
643
-                if (! $generator_object->construction_finalized()) {
643
+                if ( ! $generator_object->construction_finalized()) {
644 644
                     $generator_object->_construct_finalize($this, $action);
645 645
                 }
646 646
             }
647 647
         }
648
-        do_action('AHEE__' . get_class($this) . '__construct__end');
648
+        do_action('AHEE__'.get_class($this).'__construct__end');
649 649
     }
650 650
 
651 651
 
@@ -680,7 +680,7 @@  discard block
 block discarded – undo
680 680
      */
681 681
     public static function set_model_query_blog_id($blog_id = 0)
682 682
     {
683
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
684 684
     }
685 685
 
686 686
 
@@ -710,7 +710,7 @@  discard block
 block discarded – undo
710 710
     public static function instance($timezone = null)
711 711
     {
712 712
         // check if instance of Espresso_model already exists
713
-        if (! static::$_instance instanceof static) {
713
+        if ( ! static::$_instance instanceof static) {
714 714
             // instantiate Espresso_model
715 715
             static::$_instance = new static($timezone);
716 716
         }
@@ -741,7 +741,7 @@  discard block
 block discarded – undo
741 741
             foreach ($r->getDefaultProperties() as $property => $value) {
742 742
                 //don't set instance to null like it was originally,
743 743
                 //but it's static anyways, and we're ignoring static properties (for now at least)
744
-                if (! isset($static_properties[$property])) {
744
+                if ( ! isset($static_properties[$property])) {
745 745
                     static::$_instance->{$property} = $value;
746 746
                 }
747 747
             }
@@ -764,7 +764,7 @@  discard block
 block discarded – undo
764 764
      */
765 765
     public function status_array($translated = false)
766 766
     {
767
-        if (! array_key_exists('Status', $this->_model_relations)) {
767
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
768 768
             return array();
769 769
         }
770 770
         $model_name = $this->get_this_model_name();
@@ -967,17 +967,17 @@  discard block
 block discarded – undo
967 967
     public function wp_user_field_name()
968 968
     {
969 969
         try {
970
-            if (! empty($this->_model_chain_to_wp_user)) {
970
+            if ( ! empty($this->_model_chain_to_wp_user)) {
971 971
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
972 972
                 $last_model_name = end($models_to_follow_to_wp_users);
973 973
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
974
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
975 975
             } else {
976 976
                 $model_with_fk_to_wp_users = $this;
977 977
                 $model_chain_to_wp_user = '';
978 978
             }
979 979
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
980
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
980
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
981 981
         } catch (EE_Error $e) {
982 982
             return false;
983 983
         }
@@ -1049,12 +1049,12 @@  discard block
 block discarded – undo
1049 1049
         // remember the custom selections, if any, and type cast as array
1050 1050
         // (unless $columns_to_select is an object, then just set as an empty array)
1051 1051
         // Note: (array) 'some string' === array( 'some string' )
1052
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
1053 1053
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1054 1054
         $select_expressions = $columns_to_select !== null
1055 1055
             ? $this->_construct_select_from_input($columns_to_select)
1056 1056
             : $this->_construct_default_select_sql($model_query_info);
1057
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1058 1058
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1059 1059
     }
1060 1060
 
@@ -1099,7 +1099,7 @@  discard block
 block discarded – undo
1099 1099
         if (is_array($columns_to_select)) {
1100 1100
             $select_sql_array = array();
1101 1101
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1102
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1103 1103
                     throw new EE_Error(
1104 1104
                         sprintf(
1105 1105
                             __(
@@ -1111,7 +1111,7 @@  discard block
 block discarded – undo
1111 1111
                         )
1112 1112
                     );
1113 1113
                 }
1114
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1115 1115
                     throw new EE_Error(
1116 1116
                         sprintf(
1117 1117
                             __(
@@ -1183,7 +1183,7 @@  discard block
 block discarded – undo
1183 1183
      */
1184 1184
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1185 1185
     {
1186
-        if (! isset($query_params[0])) {
1186
+        if ( ! isset($query_params[0])) {
1187 1187
             $query_params[0] = array();
1188 1188
         }
1189 1189
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1208,7 +1208,7 @@  discard block
 block discarded – undo
1208 1208
      */
1209 1209
     public function get_one($query_params = array())
1210 1210
     {
1211
-        if (! is_array($query_params)) {
1211
+        if ( ! is_array($query_params)) {
1212 1212
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1213 1213
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1214 1214
                     gettype($query_params)), '4.6.0');
@@ -1376,7 +1376,7 @@  discard block
 block discarded – undo
1376 1376
                 return array();
1377 1377
             }
1378 1378
         }
1379
-        if (! is_array($query_params)) {
1379
+        if ( ! is_array($query_params)) {
1380 1380
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1381 1381
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1382 1382
                     gettype($query_params)), '4.6.0');
@@ -1386,7 +1386,7 @@  discard block
 block discarded – undo
1386 1386
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1387 1387
         $query_params['limit'] = $limit;
1388 1388
         //set direction
1389
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1390 1390
         $query_params['order_by'] = $operand === '>'
1391 1391
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1392 1392
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1465,7 +1465,7 @@  discard block
 block discarded – undo
1465 1465
     {
1466 1466
         $field_settings = $this->field_settings_for($field_name);
1467 1467
         //if not a valid EE_Datetime_Field then throw error
1468
-        if (! $field_settings instanceof EE_Datetime_Field) {
1468
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1469 1469
             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.',
1470 1470
                 'event_espresso'), $field_name));
1471 1471
         }
@@ -1542,7 +1542,7 @@  discard block
 block discarded – undo
1542 1542
         //load EEH_DTT_Helper
1543 1543
         $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1544 1544
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1545
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1545
+        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)));
1546 1546
     }
1547 1547
 
1548 1548
 
@@ -1610,7 +1610,7 @@  discard block
 block discarded – undo
1610 1610
      */
1611 1611
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1612 1612
     {
1613
-        if (! is_array($query_params)) {
1613
+        if ( ! is_array($query_params)) {
1614 1614
             EE_Error::doing_it_wrong('EEM_Base::update',
1615 1615
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1616 1616
                     gettype($query_params)), '4.6.0');
@@ -1632,7 +1632,7 @@  discard block
 block discarded – undo
1632 1632
          * @param EEM_Base $model           the model being queried
1633 1633
          * @param array    $query_params    see EEM_Base::get_all()
1634 1634
          */
1635
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1635
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1636 1636
             $query_params);
1637 1637
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1638 1638
         //to do that, for each table, verify that it's PK isn't null.
@@ -1646,7 +1646,7 @@  discard block
 block discarded – undo
1646 1646
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1647 1647
         foreach ($wpdb_select_results as $wpdb_result) {
1648 1648
             // type cast stdClass as array
1649
-            $wpdb_result = (array)$wpdb_result;
1649
+            $wpdb_result = (array) $wpdb_result;
1650 1650
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1651 1651
             if ($this->has_primary_key_field()) {
1652 1652
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1663,13 +1663,13 @@  discard block
 block discarded – undo
1663 1663
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1664 1664
                     //if there is no private key for this table on the results, it means there's no entry
1665 1665
                     //in this table, right? so insert a row in the current table, using any fields available
1666
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1666
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1667 1667
                            && $wpdb_result[$this_table_pk_column])
1668 1668
                     ) {
1669 1669
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1670 1670
                             $main_table_pk_value);
1671 1671
                         //if we died here, report the error
1672
-                        if (! $success) {
1672
+                        if ( ! $success) {
1673 1673
                             return false;
1674 1674
                         }
1675 1675
                     }
@@ -1700,7 +1700,7 @@  discard block
 block discarded – undo
1700 1700
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1701 1701
                 }
1702 1702
             }
1703
-            if (! $model_objs_affected_ids) {
1703
+            if ( ! $model_objs_affected_ids) {
1704 1704
                 //wait wait wait- if nothing was affected let's stop here
1705 1705
                 return 0;
1706 1706
             }
@@ -1727,7 +1727,7 @@  discard block
 block discarded – undo
1727 1727
                . $model_query_info->get_full_join_sql()
1728 1728
                . " SET "
1729 1729
                . $this->_construct_update_sql($fields_n_values)
1730
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1730
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1731 1731
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1732 1732
         /**
1733 1733
          * Action called after a model update call has been made.
@@ -1738,7 +1738,7 @@  discard block
 block discarded – undo
1738 1738
          * @param int      $rows_affected
1739 1739
          */
1740 1740
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1741
-        return $rows_affected;//how many supposedly got updated
1741
+        return $rows_affected; //how many supposedly got updated
1742 1742
     }
1743 1743
 
1744 1744
 
@@ -1766,7 +1766,7 @@  discard block
 block discarded – undo
1766 1766
         }
1767 1767
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1768 1768
         $select_expressions = $field->get_qualified_column();
1769
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1769
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1770 1770
         return $this->_do_wpdb_query('get_col', array($SQL));
1771 1771
     }
1772 1772
 
@@ -1784,7 +1784,7 @@  discard block
 block discarded – undo
1784 1784
     {
1785 1785
         $query_params['limit'] = 1;
1786 1786
         $col = $this->get_col($query_params, $field_to_select);
1787
-        if (! empty($col)) {
1787
+        if ( ! empty($col)) {
1788 1788
             return reset($col);
1789 1789
         } else {
1790 1790
             return null;
@@ -1816,7 +1816,7 @@  discard block
 block discarded – undo
1816 1816
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1817 1817
             $value_sql = $prepared_value === null ? 'NULL'
1818 1818
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1819
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1819
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1820 1820
         }
1821 1821
         return implode(",", $cols_n_values);
1822 1822
     }
@@ -1948,7 +1948,7 @@  discard block
 block discarded – undo
1948 1948
          * @param int      $rows_deleted
1949 1949
          */
1950 1950
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1951
-        return $rows_deleted;//how many supposedly got deleted
1951
+        return $rows_deleted; //how many supposedly got deleted
1952 1952
     }
1953 1953
 
1954 1954
 
@@ -2041,7 +2041,7 @@  discard block
 block discarded – undo
2041 2041
                     $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2042 2042
                 }
2043 2043
                 //other tables
2044
-                if (! empty($other_tables)) {
2044
+                if ( ! empty($other_tables)) {
2045 2045
                     foreach ($other_tables as $ot) {
2046 2046
                         //first check if we've got the foreign key column here.
2047 2047
                         if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
@@ -2064,7 +2064,7 @@  discard block
 block discarded – undo
2064 2064
             foreach ($deletes as $column => $values) {
2065 2065
                 //make sure we have unique $values;
2066 2066
                 $values = array_unique($values);
2067
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2067
+                $query[] = $column.' IN('.implode(",", $values).')';
2068 2068
             }
2069 2069
             return ! empty($query) ? implode(' AND ', $query) : '';
2070 2070
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2080,7 +2080,7 @@  discard block
 block discarded – undo
2080 2080
                                                            . $delete_object[$cpk_field->get_qualified_column()];
2081 2081
                     }
2082 2082
                 }
2083
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2083
+                $ways_to_identify_a_row[] = "(".implode(" AND ", $values_for_each_cpk_for_a_row).")";
2084 2084
             }
2085 2085
             return implode(" OR ", $ways_to_identify_a_row);
2086 2086
         } else {
@@ -2129,9 +2129,9 @@  discard block
 block discarded – undo
2129 2129
                 $column_to_count = '*';
2130 2130
             }
2131 2131
         }
2132
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2133
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2134
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2132
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2133
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2134
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2135 2135
     }
2136 2136
 
2137 2137
 
@@ -2153,13 +2153,13 @@  discard block
 block discarded – undo
2153 2153
             $field_obj = $this->get_primary_key_field();
2154 2154
         }
2155 2155
         $column_to_count = $field_obj->get_qualified_column();
2156
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2156
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2157 2157
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2158 2158
         $data_type = $field_obj->get_wpdb_data_type();
2159 2159
         if ($data_type === '%d' || $data_type === '%s') {
2160
-            return (float)$return_value;
2160
+            return (float) $return_value;
2161 2161
         } else {//must be %f
2162
-            return (float)$return_value;
2162
+            return (float) $return_value;
2163 2163
         }
2164 2164
     }
2165 2165
 
@@ -2180,13 +2180,13 @@  discard block
 block discarded – undo
2180 2180
         //if we're in maintenance mode level 2, DON'T run any queries
2181 2181
         //because level 2 indicates the database needs updating and
2182 2182
         //is probably out of sync with the code
2183
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2183
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2184 2184
             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.",
2185 2185
                 "event_espresso")));
2186 2186
         }
2187 2187
         /** @type WPDB $wpdb */
2188 2188
         global $wpdb;
2189
-        if (! method_exists($wpdb, $wpdb_method)) {
2189
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2190 2190
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2191 2191
                 'event_espresso'), $wpdb_method));
2192 2192
         }
@@ -2198,7 +2198,7 @@  discard block
 block discarded – undo
2198 2198
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2199 2199
         if (WP_DEBUG) {
2200 2200
             $wpdb->show_errors($old_show_errors_value);
2201
-            if (! empty($wpdb->last_error)) {
2201
+            if ( ! empty($wpdb->last_error)) {
2202 2202
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2203 2203
             } elseif ($result === false) {
2204 2204
                 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"',
@@ -2258,7 +2258,7 @@  discard block
 block discarded – undo
2258 2258
                     return $result;
2259 2259
                     break;
2260 2260
             }
2261
-            if (! empty($error_message)) {
2261
+            if ( ! empty($error_message)) {
2262 2262
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2263 2263
                 trigger_error($error_message);
2264 2264
             }
@@ -2334,11 +2334,11 @@  discard block
 block discarded – undo
2334 2334
      */
2335 2335
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2336 2336
     {
2337
-        return " FROM " . $model_query_info->get_full_join_sql() .
2338
-               $model_query_info->get_where_sql() .
2339
-               $model_query_info->get_group_by_sql() .
2340
-               $model_query_info->get_having_sql() .
2341
-               $model_query_info->get_order_by_sql() .
2337
+        return " FROM ".$model_query_info->get_full_join_sql().
2338
+               $model_query_info->get_where_sql().
2339
+               $model_query_info->get_group_by_sql().
2340
+               $model_query_info->get_having_sql().
2341
+               $model_query_info->get_order_by_sql().
2342 2342
                $model_query_info->get_limit_sql();
2343 2343
     }
2344 2344
 
@@ -2534,12 +2534,12 @@  discard block
 block discarded – undo
2534 2534
         $related_model = $this->get_related_model_obj($model_name);
2535 2535
         //we're just going to use the query params on the related model's normal get_all query,
2536 2536
         //except add a condition to say to match the current mod
2537
-        if (! isset($query_params['default_where_conditions'])) {
2537
+        if ( ! isset($query_params['default_where_conditions'])) {
2538 2538
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2539 2539
         }
2540 2540
         $this_model_name = $this->get_this_model_name();
2541 2541
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2542
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2542
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2543 2543
         return $related_model->count($query_params, $field_to_count, $distinct);
2544 2544
     }
2545 2545
 
@@ -2559,7 +2559,7 @@  discard block
 block discarded – undo
2559 2559
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2560 2560
     {
2561 2561
         $related_model = $this->get_related_model_obj($model_name);
2562
-        if (! is_array($query_params)) {
2562
+        if ( ! is_array($query_params)) {
2563 2563
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2564 2564
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2565 2565
                     gettype($query_params)), '4.6.0');
@@ -2567,12 +2567,12 @@  discard block
 block discarded – undo
2567 2567
         }
2568 2568
         //we're just going to use the query params on the related model's normal get_all query,
2569 2569
         //except add a condition to say to match the current mod
2570
-        if (! isset($query_params['default_where_conditions'])) {
2570
+        if ( ! isset($query_params['default_where_conditions'])) {
2571 2571
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2572 2572
         }
2573 2573
         $this_model_name = $this->get_this_model_name();
2574 2574
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2575
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2575
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2576 2576
         return $related_model->sum($query_params, $field_to_sum);
2577 2577
     }
2578 2578
 
@@ -2626,7 +2626,7 @@  discard block
 block discarded – undo
2626 2626
                 $field_with_model_name = $field;
2627 2627
             }
2628 2628
         }
2629
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2629
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2630 2630
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2631 2631
                 $this->get_this_model_name()));
2632 2632
         }
@@ -2659,7 +2659,7 @@  discard block
 block discarded – undo
2659 2659
          * @param array    $fields_n_values keys are the fields and values are their new values
2660 2660
          * @param EEM_Base $model           the model used
2661 2661
          */
2662
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2662
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2663 2663
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2664 2664
             $main_table = $this->_get_main_table();
2665 2665
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2767,7 +2767,7 @@  discard block
 block discarded – undo
2767 2767
         }
2768 2768
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2769 2769
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2770
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2770
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2771 2771
         }
2772 2772
         //if there is nothing to base this search on, then we shouldn't find anything
2773 2773
         if (empty($query_params)) {
@@ -2854,7 +2854,7 @@  discard block
 block discarded – undo
2854 2854
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2855 2855
             //so add the fk to the main table as a column
2856 2856
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2857
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2857
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2858 2858
         }
2859 2859
         //insert the new entry
2860 2860
         $result = $this->_do_wpdb_query('insert',
@@ -2893,7 +2893,7 @@  discard block
 block discarded – undo
2893 2893
     protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2894 2894
     {
2895 2895
         //if this field doesn't allow nullable, don't allow it
2896
-        if (! $field_obj->is_nullable()
2896
+        if ( ! $field_obj->is_nullable()
2897 2897
             && (
2898 2898
                 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2899 2899
         ) {
@@ -3056,7 +3056,7 @@  discard block
 block discarded – undo
3056 3056
                     $query_info_carrier,
3057 3057
                     'group_by'
3058 3058
                 );
3059
-            } elseif (! empty ($query_params['group_by'])) {
3059
+            } elseif ( ! empty ($query_params['group_by'])) {
3060 3060
                 $this->_extract_related_model_info_from_query_param(
3061 3061
                     $query_params['group_by'],
3062 3062
                     $query_info_carrier,
@@ -3078,7 +3078,7 @@  discard block
 block discarded – undo
3078 3078
                     $query_info_carrier,
3079 3079
                     'order_by'
3080 3080
                 );
3081
-            } elseif (! empty($query_params['order_by'])) {
3081
+            } elseif ( ! empty($query_params['order_by'])) {
3082 3082
                 $this->_extract_related_model_info_from_query_param(
3083 3083
                     $query_params['order_by'],
3084 3084
                     $query_info_carrier,
@@ -3113,8 +3113,8 @@  discard block
 block discarded – undo
3113 3113
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3114 3114
         $query_param_type
3115 3115
     ) {
3116
-        if (! empty($sub_query_params)) {
3117
-            $sub_query_params = (array)$sub_query_params;
3116
+        if ( ! empty($sub_query_params)) {
3117
+            $sub_query_params = (array) $sub_query_params;
3118 3118
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3119 3119
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3120 3120
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3125,7 +3125,7 @@  discard block
 block discarded – undo
3125 3125
                 //of array('Registration.TXN_ID'=>23)
3126 3126
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3127 3127
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3128
-                    if (! is_array($possibly_array_of_params)) {
3128
+                    if ( ! is_array($possibly_array_of_params)) {
3129 3129
                         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'))",
3130 3130
                             "event_espresso"),
3131 3131
                             $param, $possibly_array_of_params));
@@ -3141,7 +3141,7 @@  discard block
 block discarded – undo
3141 3141
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3142 3142
                     //indicating that $possible_array_of_params[1] is actually a field name,
3143 3143
                     //from which we should extract query parameters!
3144
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3144
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3145 3145
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3146 3146
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3147 3147
                     }
@@ -3171,8 +3171,8 @@  discard block
 block discarded – undo
3171 3171
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3172 3172
         $query_param_type
3173 3173
     ) {
3174
-        if (! empty($sub_query_params)) {
3175
-            if (! is_array($sub_query_params)) {
3174
+        if ( ! empty($sub_query_params)) {
3175
+            if ( ! is_array($sub_query_params)) {
3176 3176
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3177 3177
                     $sub_query_params));
3178 3178
             }
@@ -3201,7 +3201,7 @@  discard block
 block discarded – undo
3201 3201
      */
3202 3202
     public function _create_model_query_info_carrier($query_params)
3203 3203
     {
3204
-        if (! is_array($query_params)) {
3204
+        if ( ! is_array($query_params)) {
3205 3205
             EE_Error::doing_it_wrong(
3206 3206
                 'EEM_Base::_create_model_query_info_carrier',
3207 3207
                 sprintf(
@@ -3277,7 +3277,7 @@  discard block
 block discarded – undo
3277 3277
         //set limit
3278 3278
         if (array_key_exists('limit', $query_params)) {
3279 3279
             if (is_array($query_params['limit'])) {
3280
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3280
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3281 3281
                     $e = sprintf(
3282 3282
                         __(
3283 3283
                             "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)",
@@ -3285,12 +3285,12 @@  discard block
 block discarded – undo
3285 3285
                         ),
3286 3286
                         http_build_query($query_params['limit'])
3287 3287
                     );
3288
-                    throw new EE_Error($e . "|" . $e);
3288
+                    throw new EE_Error($e."|".$e);
3289 3289
                 }
3290 3290
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3291
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3292
-            } elseif (! empty ($query_params['limit'])) {
3293
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3291
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3292
+            } elseif ( ! empty ($query_params['limit'])) {
3293
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3294 3294
             }
3295 3295
         }
3296 3296
         //set order by
@@ -3322,10 +3322,10 @@  discard block
 block discarded – undo
3322 3322
                 $order_array = array();
3323 3323
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3324 3324
                     $order = $this->_extract_order($order);
3325
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3325
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3326 3326
                 }
3327
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3328
-            } elseif (! empty ($query_params['order_by'])) {
3327
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3328
+            } elseif ( ! empty ($query_params['order_by'])) {
3329 3329
                 $this->_extract_related_model_info_from_query_param(
3330 3330
                     $query_params['order_by'],
3331 3331
                     $query_object,
@@ -3336,18 +3336,18 @@  discard block
 block discarded – undo
3336 3336
                     ? $this->_extract_order($query_params['order'])
3337 3337
                     : 'DESC';
3338 3338
                 $query_object->set_order_by_sql(
3339
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3339
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3340 3340
                 );
3341 3341
             }
3342 3342
         }
3343 3343
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3344
-        if (! array_key_exists('order_by', $query_params)
3344
+        if ( ! array_key_exists('order_by', $query_params)
3345 3345
             && array_key_exists('order', $query_params)
3346 3346
             && ! empty($query_params['order'])
3347 3347
         ) {
3348 3348
             $pk_field = $this->get_primary_key_field();
3349 3349
             $order = $this->_extract_order($query_params['order']);
3350
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3350
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3351 3351
         }
3352 3352
         //set group by
3353 3353
         if (array_key_exists('group_by', $query_params)) {
@@ -3357,10 +3357,10 @@  discard block
 block discarded – undo
3357 3357
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3358 3358
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3359 3359
                 }
3360
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3361
-            } elseif (! empty ($query_params['group_by'])) {
3360
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3361
+            } elseif ( ! empty ($query_params['group_by'])) {
3362 3362
                 $query_object->set_group_by_sql(
3363
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3363
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3364 3364
                 );
3365 3365
             }
3366 3366
         }
@@ -3370,7 +3370,7 @@  discard block
 block discarded – undo
3370 3370
         }
3371 3371
         //now, just verify they didn't pass anything wack
3372 3372
         foreach ($query_params as $query_key => $query_value) {
3373
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3373
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3374 3374
                 throw new EE_Error(
3375 3375
                     sprintf(
3376 3376
                         __(
@@ -3464,22 +3464,22 @@  discard block
 block discarded – undo
3464 3464
         $where_query_params = array()
3465 3465
     ) {
3466 3466
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3467
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3467
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3468 3468
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3469 3469
                 "event_espresso"), $use_default_where_conditions,
3470 3470
                 implode(", ", $allowed_used_default_where_conditions_values)));
3471 3471
         }
3472 3472
         $universal_query_params = array();
3473
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3473
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3474 3474
             $universal_query_params = $this->_get_default_where_conditions();
3475
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3475
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3476 3476
             $universal_query_params = $this->_get_minimum_where_conditions();
3477 3477
         }
3478 3478
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3479 3479
             $related_model = $this->get_related_model_obj($model_name);
3480
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3480
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3481 3481
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3482
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3482
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3483 3483
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3484 3484
             } else {
3485 3485
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3512,7 +3512,7 @@  discard block
 block discarded – undo
3512 3512
      * @param bool $for_this_model false means this is for OTHER related models
3513 3513
      * @return bool
3514 3514
      */
3515
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3515
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3516 3516
     {
3517 3517
         return (
3518 3518
                    $for_this_model
@@ -3591,7 +3591,7 @@  discard block
 block discarded – undo
3591 3591
     ) {
3592 3592
         $null_friendly_where_conditions = array();
3593 3593
         $none_overridden = true;
3594
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3594
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3595 3595
         foreach ($default_where_conditions as $key => $val) {
3596 3596
             if (isset($provided_where_conditions[$key])) {
3597 3597
                 $none_overridden = false;
@@ -3709,7 +3709,7 @@  discard block
 block discarded – undo
3709 3709
             foreach ($tables as $table_obj) {
3710 3710
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3711 3711
                                        . $table_obj->get_fully_qualified_pk_column();
3712
-                if (! in_array($qualified_pk_column, $selects)) {
3712
+                if ( ! in_array($qualified_pk_column, $selects)) {
3713 3713
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3714 3714
                 }
3715 3715
             }
@@ -3795,9 +3795,9 @@  discard block
 block discarded – undo
3795 3795
         //and
3796 3796
         //check if it's a field on a related model
3797 3797
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3798
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3798
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3799 3799
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3800
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3800
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3801 3801
                 if ($query_param === '') {
3802 3802
                     //nothing left to $query_param
3803 3803
                     //we should actually end in a field name, not a model like this!
@@ -3883,7 +3883,7 @@  discard block
 block discarded – undo
3883 3883
     {
3884 3884
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3885 3885
         if ($SQL) {
3886
-            return " WHERE " . $SQL;
3886
+            return " WHERE ".$SQL;
3887 3887
         } else {
3888 3888
             return '';
3889 3889
         }
@@ -3903,7 +3903,7 @@  discard block
 block discarded – undo
3903 3903
     {
3904 3904
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3905 3905
         if ($SQL) {
3906
-            return " HAVING " . $SQL;
3906
+            return " HAVING ".$SQL;
3907 3907
         } else {
3908 3908
             return '';
3909 3909
         }
@@ -3923,11 +3923,11 @@  discard block
 block discarded – undo
3923 3923
      */
3924 3924
     protected function _get_field_on_model($field_name, $model_name)
3925 3925
     {
3926
-        $model_class = 'EEM_' . $model_name;
3927
-        $model_filepath = $model_class . ".model.php";
3926
+        $model_class = 'EEM_'.$model_name;
3927
+        $model_filepath = $model_class.".model.php";
3928 3928
         if (is_readable($model_filepath)) {
3929 3929
             require_once($model_filepath);
3930
-            $model_instance = call_user_func($model_name . "::instance");
3930
+            $model_instance = call_user_func($model_name."::instance");
3931 3931
             /* @var $model_instance EEM_Base */
3932 3932
             return $model_instance->field_settings_for($field_name);
3933 3933
         } else {
@@ -3951,7 +3951,7 @@  discard block
 block discarded – undo
3951 3951
     {
3952 3952
         $where_clauses = array();
3953 3953
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3954
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3954
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
3955 3955
             if (in_array($query_param, $this->_logic_query_param_keys)) {
3956 3956
                 switch ($query_param) {
3957 3957
                     case 'not':
@@ -3979,7 +3979,7 @@  discard block
 block discarded – undo
3979 3979
             } else {
3980 3980
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
3981 3981
                 //if it's not a normal field, maybe it's a custom selection?
3982
-                if (! $field_obj) {
3982
+                if ( ! $field_obj) {
3983 3983
                     if (isset($this->_custom_selections[$query_param][1])) {
3984 3984
                         $field_obj = $this->_custom_selections[$query_param][1];
3985 3985
                     } else {
@@ -3988,7 +3988,7 @@  discard block
 block discarded – undo
3988 3988
                     }
3989 3989
                 }
3990 3990
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3991
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3991
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
3992 3992
             }
3993 3993
         }
3994 3994
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4009,7 +4009,7 @@  discard block
 block discarded – undo
4009 4009
         if ($field) {
4010 4010
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4011 4011
                 $query_param);
4012
-            return $table_alias_prefix . $field->get_qualified_column();
4012
+            return $table_alias_prefix.$field->get_qualified_column();
4013 4013
         } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4014 4014
             //maybe it's custom selection item?
4015 4015
             //if so, just use it as the "column name"
@@ -4056,7 +4056,7 @@  discard block
 block discarded – undo
4056 4056
     {
4057 4057
         if (is_array($op_and_value)) {
4058 4058
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4059
-            if (! $operator) {
4059
+            if ( ! $operator) {
4060 4060
                 $php_array_like_string = array();
4061 4061
                 foreach ($op_and_value as $key => $value) {
4062 4062
                     $php_array_like_string[] = "$key=>$value";
@@ -4078,13 +4078,13 @@  discard block
 block discarded – undo
4078 4078
         }
4079 4079
         //check to see if the value is actually another field
4080 4080
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4081
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4081
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4082 4082
         } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4083 4083
             //in this case, the value should be an array, or at least a comma-separated list
4084 4084
             //it will need to handle a little differently
4085 4085
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4086 4086
             //note: $cleaned_value has already been run through $wpdb->prepare()
4087
-            return $operator . SP . $cleaned_value;
4087
+            return $operator.SP.$cleaned_value;
4088 4088
         } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4089 4089
             //the value should be an array with count of two.
4090 4090
             if (count($value) !== 2) {
@@ -4099,7 +4099,7 @@  discard block
 block discarded – undo
4099 4099
                 );
4100 4100
             }
4101 4101
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4102
-            return $operator . SP . $cleaned_value;
4102
+            return $operator.SP.$cleaned_value;
4103 4103
         } elseif (in_array($operator, $this->_null_style_operators)) {
4104 4104
             if ($value !== null) {
4105 4105
                 throw new EE_Error(
@@ -4117,9 +4117,9 @@  discard block
 block discarded – undo
4117 4117
         } elseif ($operator === 'LIKE' && ! is_array($value)) {
4118 4118
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4119 4119
             //remove other junk. So just treat it as a string.
4120
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4121
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4122
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4120
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4121
+        } elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4122
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4123 4123
         } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4124 4124
             throw new EE_Error(
4125 4125
                 sprintf(
@@ -4131,7 +4131,7 @@  discard block
 block discarded – undo
4131 4131
                     $operator
4132 4132
                 )
4133 4133
             );
4134
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4134
+        } elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4135 4135
             throw new EE_Error(
4136 4136
                 sprintf(
4137 4137
                     __(
@@ -4172,7 +4172,7 @@  discard block
 block discarded – undo
4172 4172
         foreach ($values as $value) {
4173 4173
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4174 4174
         }
4175
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4175
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4176 4176
     }
4177 4177
 
4178 4178
 
@@ -4213,7 +4213,7 @@  discard block
 block discarded – undo
4213 4213
                                 . $main_table->get_table_name()
4214 4214
                                 . " WHERE FALSE";
4215 4215
         }
4216
-        return "(" . implode(",", $cleaned_values) . ")";
4216
+        return "(".implode(",", $cleaned_values).")";
4217 4217
     }
4218 4218
 
4219 4219
 
@@ -4232,7 +4232,7 @@  discard block
 block discarded – undo
4232 4232
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4233 4233
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4234 4234
         } else {//$field_obj should really just be a data type
4235
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4235
+            if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4236 4236
                 throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4237 4237
                     $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4238 4238
             }
@@ -4352,10 +4352,10 @@  discard block
 block discarded – undo
4352 4352
      */
4353 4353
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4354 4354
     {
4355
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4355
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4356 4356
         $qualified_columns = array();
4357 4357
         foreach ($this->field_settings() as $field_name => $field) {
4358
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4358
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4359 4359
         }
4360 4360
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4361 4361
     }
@@ -4379,11 +4379,11 @@  discard block
 block discarded – undo
4379 4379
             if ($table_obj instanceof EE_Primary_Table) {
4380 4380
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4381 4381
                     ? $table_obj->get_select_join_limit($limit)
4382
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4382
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4383 4383
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4384 4384
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4385 4385
                     ? $table_obj->get_select_join_limit_join($limit)
4386
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4386
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4387 4387
             }
4388 4388
         }
4389 4389
         return $SQL;
@@ -4471,12 +4471,12 @@  discard block
 block discarded – undo
4471 4471
      */
4472 4472
     public function get_related_model_obj($model_name)
4473 4473
     {
4474
-        $model_classname = "EEM_" . $model_name;
4475
-        if (! class_exists($model_classname)) {
4474
+        $model_classname = "EEM_".$model_name;
4475
+        if ( ! class_exists($model_classname)) {
4476 4476
             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",
4477 4477
                 'event_espresso'), $model_name, $model_classname));
4478 4478
         }
4479
-        return call_user_func($model_classname . "::instance");
4479
+        return call_user_func($model_classname."::instance");
4480 4480
     }
4481 4481
 
4482 4482
 
@@ -4523,7 +4523,7 @@  discard block
 block discarded – undo
4523 4523
     public function related_settings_for($relation_name)
4524 4524
     {
4525 4525
         $relatedModels = $this->relation_settings();
4526
-        if (! array_key_exists($relation_name, $relatedModels)) {
4526
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4527 4527
             throw new EE_Error(
4528 4528
                 sprintf(
4529 4529
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4550,7 +4550,7 @@  discard block
 block discarded – undo
4550 4550
     public function field_settings_for($fieldName)
4551 4551
     {
4552 4552
         $fieldSettings = $this->field_settings(true);
4553
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4553
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4554 4554
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4555 4555
                 get_class($this)));
4556 4556
         }
@@ -4625,7 +4625,7 @@  discard block
 block discarded – undo
4625 4625
                     break;
4626 4626
                 }
4627 4627
             }
4628
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4628
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4629 4629
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4630 4630
                     get_class($this)));
4631 4631
             }
@@ -4684,7 +4684,7 @@  discard block
 block discarded – undo
4684 4684
      */
4685 4685
     public function get_foreign_key_to($model_name)
4686 4686
     {
4687
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4687
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4688 4688
             foreach ($this->field_settings() as $field) {
4689 4689
                 if (
4690 4690
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4694,7 +4694,7 @@  discard block
 block discarded – undo
4694 4694
                     break;
4695 4695
                 }
4696 4696
             }
4697
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4697
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4698 4698
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4699 4699
                     'event_espresso'), $model_name, get_class($this)));
4700 4700
             }
@@ -4745,7 +4745,7 @@  discard block
 block discarded – undo
4745 4745
                 foreach ($this->_fields as $fields_corresponding_to_table) {
4746 4746
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4747 4747
                         /** @var $field_obj EE_Model_Field_Base */
4748
-                        if (! $field_obj->is_db_only_field()) {
4748
+                        if ( ! $field_obj->is_db_only_field()) {
4749 4749
                             $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4750 4750
                         }
4751 4751
                     }
@@ -4775,7 +4775,7 @@  discard block
 block discarded – undo
4775 4775
         $count_if_model_has_no_primary_key = 0;
4776 4776
         $has_primary_key = $this->has_primary_key_field();
4777 4777
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4778
-        foreach ((array)$rows as $row) {
4778
+        foreach ((array) $rows as $row) {
4779 4779
             if (empty($row)) {
4780 4780
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4781 4781
                 return array();
@@ -4793,7 +4793,7 @@  discard block
 block discarded – undo
4793 4793
                 }
4794 4794
             }
4795 4795
             $classInstance = $this->instantiate_class_from_array_or_object($row);
4796
-            if (! $classInstance) {
4796
+            if ( ! $classInstance) {
4797 4797
                 throw new EE_Error(
4798 4798
                     sprintf(
4799 4799
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -4862,7 +4862,7 @@  discard block
 block discarded – undo
4862 4862
      */
4863 4863
     public function instantiate_class_from_array_or_object($cols_n_values)
4864 4864
     {
4865
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4865
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4866 4866
             $cols_n_values = get_object_vars($cols_n_values);
4867 4867
         }
4868 4868
         $primary_key = null;
@@ -4887,7 +4887,7 @@  discard block
 block discarded – undo
4887 4887
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4888 4888
         if ($primary_key) {
4889 4889
             $classInstance = $this->get_from_entity_map($primary_key);
4890
-            if (! $classInstance) {
4890
+            if ( ! $classInstance) {
4891 4891
                 $classInstance = EE_Registry::instance()
4892 4892
                                             ->load_class($className,
4893 4893
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -4938,12 +4938,12 @@  discard block
 block discarded – undo
4938 4938
     public function add_to_entity_map(EE_Base_Class $object)
4939 4939
     {
4940 4940
         $className = $this->_get_class_name();
4941
-        if (! $object instanceof $className) {
4941
+        if ( ! $object instanceof $className) {
4942 4942
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4943 4943
                 is_object($object) ? get_class($object) : $object, $className));
4944 4944
         }
4945 4945
         /** @var $object EE_Base_Class */
4946
-        if (! $object->ID()) {
4946
+        if ( ! $object->ID()) {
4947 4947
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4948 4948
                 "event_espresso"), get_class($this)));
4949 4949
         }
@@ -5013,7 +5013,7 @@  discard block
 block discarded – undo
5013 5013
             //there is a primary key on this table and its not set. Use defaults for all its columns
5014 5014
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5015 5015
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5016
-                    if (! $field_obj->is_db_only_field()) {
5016
+                    if ( ! $field_obj->is_db_only_field()) {
5017 5017
                         //prepare field as if its coming from db
5018 5018
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5019 5019
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5022,7 +5022,7 @@  discard block
 block discarded – undo
5022 5022
             } else {
5023 5023
                 //the table's rows existed. Use their values
5024 5024
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5025
-                    if (! $field_obj->is_db_only_field()) {
5025
+                    if ( ! $field_obj->is_db_only_field()) {
5026 5026
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5027 5027
                             $cols_n_values, $field_obj->get_qualified_column(),
5028 5028
                             $field_obj->get_table_column()
@@ -5139,7 +5139,7 @@  discard block
 block discarded – undo
5139 5139
      */
5140 5140
     private function _get_class_name()
5141 5141
     {
5142
-        return "EE_" . $this->get_this_model_name();
5142
+        return "EE_".$this->get_this_model_name();
5143 5143
     }
5144 5144
 
5145 5145
 
@@ -5154,7 +5154,7 @@  discard block
 block discarded – undo
5154 5154
      */
5155 5155
     public function item_name($quantity = 1)
5156 5156
     {
5157
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5157
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5158 5158
     }
5159 5159
 
5160 5160
 
@@ -5187,7 +5187,7 @@  discard block
 block discarded – undo
5187 5187
     {
5188 5188
         $className = get_class($this);
5189 5189
         $tagName = "FHEE__{$className}__{$methodName}";
5190
-        if (! has_filter($tagName)) {
5190
+        if ( ! has_filter($tagName)) {
5191 5191
             throw new EE_Error(
5192 5192
                 sprintf(
5193 5193
                     __('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 );',
@@ -5413,7 +5413,7 @@  discard block
 block discarded – undo
5413 5413
         $key_vals_in_combined_pk = array();
5414 5414
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5415 5415
         foreach ($key_fields as $key_field_name => $field_obj) {
5416
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5416
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5417 5417
                 return null;
5418 5418
             }
5419 5419
         }
@@ -5434,7 +5434,7 @@  discard block
 block discarded – undo
5434 5434
     {
5435 5435
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5436 5436
         foreach ($keys_it_should_have as $key) {
5437
-            if (! isset($key_vals[$key])) {
5437
+            if ( ! isset($key_vals[$key])) {
5438 5438
                 return false;
5439 5439
             }
5440 5440
         }
@@ -5488,7 +5488,7 @@  discard block
 block discarded – undo
5488 5488
      */
5489 5489
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5490 5490
     {
5491
-        if (! is_array($query_params)) {
5491
+        if ( ! is_array($query_params)) {
5492 5492
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5493 5493
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5494 5494
                     gettype($query_params)), '4.6.0');
@@ -5580,7 +5580,7 @@  discard block
 block discarded – undo
5580 5580
      */
5581 5581
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5582 5582
     {
5583
-        if (! $this->has_primary_key_field()) {
5583
+        if ( ! $this->has_primary_key_field()) {
5584 5584
             if (WP_DEBUG) {
5585 5585
                 EE_Error::add_error(
5586 5586
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5593,7 +5593,7 @@  discard block
 block discarded – undo
5593 5593
         $IDs = array();
5594 5594
         foreach ($model_objects as $model_object) {
5595 5595
             $id = $model_object->ID();
5596
-            if (! $id) {
5596
+            if ( ! $id) {
5597 5597
                 if ($filter_out_empty_ids) {
5598 5598
                     continue;
5599 5599
                 }
@@ -5689,8 +5689,8 @@  discard block
 block discarded – undo
5689 5689
         $missing_caps = array();
5690 5690
         $cap_restrictions = $this->cap_restrictions($context);
5691 5691
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5692
-            if (! EE_Capabilities::instance()
5693
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5692
+            if ( ! EE_Capabilities::instance()
5693
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5694 5694
             ) {
5695 5695
                 $missing_caps[$cap] = $restriction_if_no_cap;
5696 5696
             }
@@ -5841,7 +5841,7 @@  discard block
 block discarded – undo
5841 5841
     {
5842 5842
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5843 5843
             if ($query_param_key === $logic_query_param_key
5844
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5844
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
5845 5845
             ) {
5846 5846
                 return true;
5847 5847
             }
Please login to merge, or discard this patch.
core/wordpress-shims.php 2 patches
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -5,51 +5,51 @@
 block discarded – undo
5 5
  * it does not override any existing definition of the function in WP.
6 6
  */
7 7
 if ( ! function_exists( 'get_preview_post_link' ) ) {
8
-    /**
9
-     * Function was added in WordPress 4.4.0
10
-     * @param null   $post
11
-     * @param array  $query_args
12
-     * @param string $preview_link
13
-     * @return mixed
14
-     */
15
-    function get_preview_post_link($post = null, $query_args = array(), $preview_link = '')
16
-    {
17
-        $post = get_post($post);
18
-        if (! $post) {
19
-            return '';
20
-        }
8
+	/**
9
+	 * Function was added in WordPress 4.4.0
10
+	 * @param null   $post
11
+	 * @param array  $query_args
12
+	 * @param string $preview_link
13
+	 * @return mixed
14
+	 */
15
+	function get_preview_post_link($post = null, $query_args = array(), $preview_link = '')
16
+	{
17
+		$post = get_post($post);
18
+		if (! $post) {
19
+			return '';
20
+		}
21 21
 
22
-        $post_type_object = get_post_type_object($post->post_type);
23
-        if (is_post_type_viewable($post_type_object)) {
24
-            if (! $preview_link) {
25
-                $preview_link = set_url_scheme(get_permalink($post));
26
-            }
22
+		$post_type_object = get_post_type_object($post->post_type);
23
+		if (is_post_type_viewable($post_type_object)) {
24
+			if (! $preview_link) {
25
+				$preview_link = set_url_scheme(get_permalink($post));
26
+			}
27 27
 
28
-            $query_args['preview'] = 'true';
29
-            $preview_link          = add_query_arg($query_args, $preview_link);
30
-        }
28
+			$query_args['preview'] = 'true';
29
+			$preview_link          = add_query_arg($query_args, $preview_link);
30
+		}
31 31
 
32
-        /**
33
-         * Filters the URL used for a post preview.
34
-         *
35
-         * @since 2.0.5
36
-         * @since 4.0.0 Added the `$post` parameter.
37
-         * @param string  $preview_link URL used for the post preview.
38
-         * @param WP_Post $post         Post object.
39
-         */
40
-        return apply_filters('preview_post_link', $preview_link, $post);
41
-    }
32
+		/**
33
+		 * Filters the URL used for a post preview.
34
+		 *
35
+		 * @since 2.0.5
36
+		 * @since 4.0.0 Added the `$post` parameter.
37
+		 * @param string  $preview_link URL used for the post preview.
38
+		 * @param WP_Post $post         Post object.
39
+		 */
40
+		return apply_filters('preview_post_link', $preview_link, $post);
41
+	}
42 42
 }
43 43
 
44 44
 if ( ! function_exists( 'is_post_type_viewable' ) ) {
45
-    function is_post_type_viewable( $post_type ) {
46
-        if ( is_scalar( $post_type ) ) {
47
-            $post_type = get_post_type_object( $post_type );
48
-            if ( ! $post_type ) {
49
-                return false;
50
-            }
51
-        }
45
+	function is_post_type_viewable( $post_type ) {
46
+		if ( is_scalar( $post_type ) ) {
47
+			$post_type = get_post_type_object( $post_type );
48
+			if ( ! $post_type ) {
49
+				return false;
50
+			}
51
+		}
52 52
      
53
-        return $post_type->publicly_queryable || ( $post_type->_builtin && $post_type->public );
54
-    }
53
+		return $post_type->publicly_queryable || ( $post_type->_builtin && $post_type->public );
54
+	}
55 55
 }
56 56
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
  * Note: this file should only be required right before calling the function the shim is for.  This is to ensure that
5 5
  * it does not override any existing definition of the function in WP.
6 6
  */
7
-if ( ! function_exists( 'get_preview_post_link' ) ) {
7
+if ( ! function_exists('get_preview_post_link')) {
8 8
     /**
9 9
      * Function was added in WordPress 4.4.0
10 10
      * @param null   $post
@@ -15,13 +15,13 @@  discard block
 block discarded – undo
15 15
     function get_preview_post_link($post = null, $query_args = array(), $preview_link = '')
16 16
     {
17 17
         $post = get_post($post);
18
-        if (! $post) {
18
+        if ( ! $post) {
19 19
             return '';
20 20
         }
21 21
 
22 22
         $post_type_object = get_post_type_object($post->post_type);
23 23
         if (is_post_type_viewable($post_type_object)) {
24
-            if (! $preview_link) {
24
+            if ( ! $preview_link) {
25 25
                 $preview_link = set_url_scheme(get_permalink($post));
26 26
             }
27 27
 
@@ -41,15 +41,15 @@  discard block
 block discarded – undo
41 41
     }
42 42
 }
43 43
 
44
-if ( ! function_exists( 'is_post_type_viewable' ) ) {
45
-    function is_post_type_viewable( $post_type ) {
46
-        if ( is_scalar( $post_type ) ) {
47
-            $post_type = get_post_type_object( $post_type );
48
-            if ( ! $post_type ) {
44
+if ( ! function_exists('is_post_type_viewable')) {
45
+    function is_post_type_viewable($post_type) {
46
+        if (is_scalar($post_type)) {
47
+            $post_type = get_post_type_object($post_type);
48
+            if ( ! $post_type) {
49 49
                 return false;
50 50
             }
51 51
         }
52 52
      
53
-        return $post_type->publicly_queryable || ( $post_type->_builtin && $post_type->public );
53
+        return $post_type->publicly_queryable || ($post_type->_builtin && $post_type->public);
54 54
     }
55 55
 }
56 56
\ No newline at end of file
Please login to merge, or discard this patch.
core/admin/EE_Admin_Page_CPT.core.php 2 patches
Indentation   +1388 added lines, -1388 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 /**
@@ -24,445 +24,445 @@  discard block
 block discarded – undo
24 24
 {
25 25
 
26 26
 
27
-    /**
28
-     * This gets set in _setup_cpt
29
-     * It will contain the object for the custom post type.
30
-     *
31
-     * @var object
32
-     */
33
-    protected $_cpt_object;
34
-
35
-
36
-
37
-    /**
38
-     * a boolean flag to set whether the current route is a cpt route or not.
39
-     *
40
-     * @var bool
41
-     */
42
-    protected $_cpt_route = false;
43
-
44
-
45
-
46
-    /**
47
-     * This property allows cpt classes to define multiple routes as cpt routes.
48
-     * //in this array we define what the custom post type for this route is.
49
-     * array(
50
-     * 'route_name' => 'custom_post_type_slug'
51
-     * )
52
-     *
53
-     * @var array
54
-     */
55
-    protected $_cpt_routes = array();
56
-
27
+	/**
28
+	 * This gets set in _setup_cpt
29
+	 * It will contain the object for the custom post type.
30
+	 *
31
+	 * @var object
32
+	 */
33
+	protected $_cpt_object;
34
+
35
+
36
+
37
+	/**
38
+	 * a boolean flag to set whether the current route is a cpt route or not.
39
+	 *
40
+	 * @var bool
41
+	 */
42
+	protected $_cpt_route = false;
43
+
44
+
45
+
46
+	/**
47
+	 * This property allows cpt classes to define multiple routes as cpt routes.
48
+	 * //in this array we define what the custom post type for this route is.
49
+	 * array(
50
+	 * 'route_name' => 'custom_post_type_slug'
51
+	 * )
52
+	 *
53
+	 * @var array
54
+	 */
55
+	protected $_cpt_routes = array();
56
+
57 57
 
58 58
 
59
-    /**
60
-     * This simply defines what the corresponding routes WP will be redirected to after completing a post save/update.
61
-     * in this format:
62
-     * array(
63
-     * 'post_type_slug' => 'edit_route'
64
-     * )
65
-     *
66
-     * @var array
67
-     */
68
-    protected $_cpt_edit_routes = array();
69
-
70
-
71
-
72
-    /**
73
-     * If child classes set the name of their main model via the $_cpt_obj_models property, EE_Admin_Page_CPT will
74
-     * attempt to retrieve the related object model for the edit pages and assign it to _cpt_page_object. the
75
-     * _cpt_model_names property should be in the following format: array(
76
-     * 'route_defined_by_action_param' => 'Model_Name')
77
-     *
78
-     * @var array $_cpt_model_names
79
-     */
80
-    protected $_cpt_model_names = array();
81
-
82
-
83
-    /**
84
-     * @var EE_CPT_Base
85
-     */
86
-    protected $_cpt_model_obj = false;
87
-
88
-
89
-
90
-    /**
91
-     * This will hold an array of autosave containers that will be used to obtain input values and hook into the WP
92
-     * autosave so we can save our inputs on the save_post hook!  Children classes should add to this array by using
93
-     * the _register_autosave_containers() method so that we don't override any other containers already registered.
94
-     * Registration of containers should be done before load_page_dependencies() is run.
95
-     *
96
-     * @var array()
97
-     */
98
-    protected $_autosave_containers = array();
99
-    protected $_autosave_fields = array();
100
-
101
-    /**
102
-     * Array mapping from admin actions to their equivalent wp core pages for custom post types. So when a user visits
103
-     * a page for an action, it will appear as if they were visiting the wp core page for that custom post type
104
-     *
105
-     * @var array
106
-     */
107
-    protected $_pagenow_map = null;
108
-
109
-
110
-
111
-    /**
112
-     * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
113
-     * saved.  Child classes are required to declare this method.  Typically you would use this to save any additional
114
-     * data. Keep in mind also that "save_post" runs on EVERY post update to the database. ALSO very important.  When a
115
-     * post transitions from scheduled to published, the save_post action is fired but you will NOT have any _POST data
116
-     * containing any extra info you may have from other meta saves.  So MAKE sure that you handle this accordingly.
117
-     *
118
-     * @access protected
119
-     * @abstract
120
-     * @param  string $post_id The ID of the cpt that was saved (so you can link relationally)
121
-     * @param  object $post    The post object of the cpt that was saved.
122
-     * @return void
123
-     */
124
-    abstract protected function _insert_update_cpt_item($post_id, $post);
125
-
126
-
127
-
128
-    /**
129
-     * This is hooked into the WordPress do_action('trashed_post') hook and runs after a cpt has been trashed.
130
-     *
131
-     * @abstract
132
-     * @access public
133
-     * @param  string $post_id The ID of the cpt that was trashed
134
-     * @return void
135
-     */
136
-    abstract public function trash_cpt_item($post_id);
137
-
138
-
139
-
140
-    /**
141
-     * This is hooked into the WordPress do_action('untrashed_post') hook and runs after a cpt has been untrashed
142
-     *
143
-     * @param  string $post_id theID of the cpt that was untrashed
144
-     * @return void
145
-     */
146
-    abstract public function restore_cpt_item($post_id);
147
-
148
-
149
-
150
-    /**
151
-     * This is hooked into the WordPress do_action('delete_cpt_item') hook and runs after a cpt has been fully deleted
152
-     * from the db
153
-     *
154
-     * @param  string $post_id the ID of the cpt that was deleted
155
-     * @return void
156
-     */
157
-    abstract public function delete_cpt_item($post_id);
158
-
159
-
160
-
161
-    /**
162
-     * Just utilizing the method EE_Admin exposes for doing things before page setup.
163
-     *
164
-     * @access protected
165
-     * @return void
166
-     */
167
-    protected function _before_page_setup()
168
-    {
169
-        $page = isset($this->_req_data['page']) ? $this->_req_data['page'] : $this->page_slug;
170
-        $this->_cpt_routes = array_merge(array(
171
-            'create_new' => $this->page_slug,
172
-            'edit'       => $this->page_slug,
173
-            'trash'      => $this->page_slug,
174
-        ), $this->_cpt_routes);
175
-        //let's see if the current route has a value for cpt_object_slug if it does we use that instead of the page
176
-        $this->_cpt_object = isset($this->_req_data['action']) && isset($this->_cpt_routes[$this->_req_data['action']])
177
-            ? get_post_type_object($this->_cpt_routes[$this->_req_data['action']])
178
-            : get_post_type_object($page);
179
-        //tweak pagenow for page loading.
180
-        if ( ! $this->_pagenow_map) {
181
-            $this->_pagenow_map = array(
182
-                'create_new' => 'post-new.php',
183
-                'edit'       => 'post.php',
184
-                'trash'      => 'post.php',
185
-            );
186
-        }
187
-        add_action('current_screen', array($this, 'modify_pagenow'));
188
-        //TODO the below will need to be reworked to account for the cpt routes that are NOT based off of page but action param.
189
-        //get current page from autosave
190
-        $current_page = isset($this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page'])
191
-            ? $this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page']
192
-            : null;
193
-        $this->_current_page = isset($this->_req_data['current_page'])
194
-            ? $this->_req_data['current_page']
195
-            : $current_page;
196
-        //autosave... make sure its only for the correct page
197
-        if ( ! empty($this->_current_page) && $this->_current_page == $this->page_slug) {
198
-            //setup autosave ajax hook
199
-            //add_action('wp_ajax_ee-autosave', array( $this, 'do_extra_autosave_stuff' ), 10 ); //TODO reactivate when 4.2 autosave is implemented
200
-        }
201
-    }
202
-
203
-
204
-
205
-    /**
206
-     * Simply ensure that we simulate the correct post route for cpt screens
207
-     *
208
-     * @param WP_Screen $current_screen
209
-     * @return void
210
-     */
211
-    public function modify_pagenow($current_screen)
212
-    {
213
-        global $pagenow, $hook_suffix;
214
-        //possibly reset pagenow.
215
-        if ( ! empty($this->_req_data['page'])
216
-             && $this->_req_data['page'] == $this->page_slug
217
-             && ! empty($this->_req_data['action'])
218
-             && isset($this->_pagenow_map[$this->_req_data['action']])
219
-        ) {
220
-            $pagenow = $this->_pagenow_map[$this->_req_data['action']];
221
-            $hook_suffix = $pagenow;
222
-        }
223
-    }
224
-
225
-
226
-
227
-    /**
228
-     * This method is used to register additional autosave containers to the _autosave_containers property.
229
-     *
230
-     * @todo We should automate this at some point by creating a wrapper for add_post_metabox and in our wrapper we
231
-     *       automatically register the id for the post metabox as a container.
232
-     * @param  array $ids an array of ids for containers that hold form inputs we want autosave to pickup.  Typically
233
-     *                    you would send along the id of a metabox container.
234
-     * @return void
235
-     */
236
-    protected function _register_autosave_containers($ids)
237
-    {
238
-        $this->_autosave_containers = array_merge($this->_autosave_fields, (array)$ids);
239
-    }
240
-
241
-
242
-
243
-    /**
244
-     * Something nifty.  We're going to loop through all the registered metaboxes and if the CALLBACK is an instance of
245
-     * EE_Admin_Page OR EE_Admin_Hooks, then we'll add the id to our _autosave_containers array.
246
-     */
247
-    protected function _set_autosave_containers()
248
-    {
249
-        global $wp_meta_boxes;
250
-        $containers = array();
251
-        if (empty($wp_meta_boxes)) {
252
-            return;
253
-        }
254
-        $current_metaboxes = isset($wp_meta_boxes[$this->page_slug]) ? $wp_meta_boxes[$this->page_slug] : array();
255
-        foreach ($current_metaboxes as $box_context) {
256
-            foreach ($box_context as $box_details) {
257
-                foreach ($box_details as $box) {
258
-                    if (is_array($box['callback'])
259
-                        && ($box['callback'][0] instanceof EE_Admin_Page
260
-                            || $box['callback'][0] instanceof EE_Admin_Hooks)
261
-                    ) {
262
-                        $containers[] = $box['id'];
263
-                    }
264
-                }
265
-            }
266
-        }
267
-        $this->_autosave_containers = array_merge($this->_autosave_containers, $containers);
268
-        //add hidden inputs container
269
-        $this->_autosave_containers[] = 'ee-cpt-hidden-inputs';
270
-    }
271
-
272
-
273
-
274
-    protected function _load_autosave_scripts_styles()
275
-    {
276
-        /*wp_register_script('cpt-autosave', EE_ADMIN_URL . 'assets/ee-cpt-autosave.js', array('ee-serialize-full-array', 'event_editor_js'), EVENT_ESPRESSO_VERSION, TRUE );
59
+	/**
60
+	 * This simply defines what the corresponding routes WP will be redirected to after completing a post save/update.
61
+	 * in this format:
62
+	 * array(
63
+	 * 'post_type_slug' => 'edit_route'
64
+	 * )
65
+	 *
66
+	 * @var array
67
+	 */
68
+	protected $_cpt_edit_routes = array();
69
+
70
+
71
+
72
+	/**
73
+	 * If child classes set the name of their main model via the $_cpt_obj_models property, EE_Admin_Page_CPT will
74
+	 * attempt to retrieve the related object model for the edit pages and assign it to _cpt_page_object. the
75
+	 * _cpt_model_names property should be in the following format: array(
76
+	 * 'route_defined_by_action_param' => 'Model_Name')
77
+	 *
78
+	 * @var array $_cpt_model_names
79
+	 */
80
+	protected $_cpt_model_names = array();
81
+
82
+
83
+	/**
84
+	 * @var EE_CPT_Base
85
+	 */
86
+	protected $_cpt_model_obj = false;
87
+
88
+
89
+
90
+	/**
91
+	 * This will hold an array of autosave containers that will be used to obtain input values and hook into the WP
92
+	 * autosave so we can save our inputs on the save_post hook!  Children classes should add to this array by using
93
+	 * the _register_autosave_containers() method so that we don't override any other containers already registered.
94
+	 * Registration of containers should be done before load_page_dependencies() is run.
95
+	 *
96
+	 * @var array()
97
+	 */
98
+	protected $_autosave_containers = array();
99
+	protected $_autosave_fields = array();
100
+
101
+	/**
102
+	 * Array mapping from admin actions to their equivalent wp core pages for custom post types. So when a user visits
103
+	 * a page for an action, it will appear as if they were visiting the wp core page for that custom post type
104
+	 *
105
+	 * @var array
106
+	 */
107
+	protected $_pagenow_map = null;
108
+
109
+
110
+
111
+	/**
112
+	 * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
113
+	 * saved.  Child classes are required to declare this method.  Typically you would use this to save any additional
114
+	 * data. Keep in mind also that "save_post" runs on EVERY post update to the database. ALSO very important.  When a
115
+	 * post transitions from scheduled to published, the save_post action is fired but you will NOT have any _POST data
116
+	 * containing any extra info you may have from other meta saves.  So MAKE sure that you handle this accordingly.
117
+	 *
118
+	 * @access protected
119
+	 * @abstract
120
+	 * @param  string $post_id The ID of the cpt that was saved (so you can link relationally)
121
+	 * @param  object $post    The post object of the cpt that was saved.
122
+	 * @return void
123
+	 */
124
+	abstract protected function _insert_update_cpt_item($post_id, $post);
125
+
126
+
127
+
128
+	/**
129
+	 * This is hooked into the WordPress do_action('trashed_post') hook and runs after a cpt has been trashed.
130
+	 *
131
+	 * @abstract
132
+	 * @access public
133
+	 * @param  string $post_id The ID of the cpt that was trashed
134
+	 * @return void
135
+	 */
136
+	abstract public function trash_cpt_item($post_id);
137
+
138
+
139
+
140
+	/**
141
+	 * This is hooked into the WordPress do_action('untrashed_post') hook and runs after a cpt has been untrashed
142
+	 *
143
+	 * @param  string $post_id theID of the cpt that was untrashed
144
+	 * @return void
145
+	 */
146
+	abstract public function restore_cpt_item($post_id);
147
+
148
+
149
+
150
+	/**
151
+	 * This is hooked into the WordPress do_action('delete_cpt_item') hook and runs after a cpt has been fully deleted
152
+	 * from the db
153
+	 *
154
+	 * @param  string $post_id the ID of the cpt that was deleted
155
+	 * @return void
156
+	 */
157
+	abstract public function delete_cpt_item($post_id);
158
+
159
+
160
+
161
+	/**
162
+	 * Just utilizing the method EE_Admin exposes for doing things before page setup.
163
+	 *
164
+	 * @access protected
165
+	 * @return void
166
+	 */
167
+	protected function _before_page_setup()
168
+	{
169
+		$page = isset($this->_req_data['page']) ? $this->_req_data['page'] : $this->page_slug;
170
+		$this->_cpt_routes = array_merge(array(
171
+			'create_new' => $this->page_slug,
172
+			'edit'       => $this->page_slug,
173
+			'trash'      => $this->page_slug,
174
+		), $this->_cpt_routes);
175
+		//let's see if the current route has a value for cpt_object_slug if it does we use that instead of the page
176
+		$this->_cpt_object = isset($this->_req_data['action']) && isset($this->_cpt_routes[$this->_req_data['action']])
177
+			? get_post_type_object($this->_cpt_routes[$this->_req_data['action']])
178
+			: get_post_type_object($page);
179
+		//tweak pagenow for page loading.
180
+		if ( ! $this->_pagenow_map) {
181
+			$this->_pagenow_map = array(
182
+				'create_new' => 'post-new.php',
183
+				'edit'       => 'post.php',
184
+				'trash'      => 'post.php',
185
+			);
186
+		}
187
+		add_action('current_screen', array($this, 'modify_pagenow'));
188
+		//TODO the below will need to be reworked to account for the cpt routes that are NOT based off of page but action param.
189
+		//get current page from autosave
190
+		$current_page = isset($this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page'])
191
+			? $this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page']
192
+			: null;
193
+		$this->_current_page = isset($this->_req_data['current_page'])
194
+			? $this->_req_data['current_page']
195
+			: $current_page;
196
+		//autosave... make sure its only for the correct page
197
+		if ( ! empty($this->_current_page) && $this->_current_page == $this->page_slug) {
198
+			//setup autosave ajax hook
199
+			//add_action('wp_ajax_ee-autosave', array( $this, 'do_extra_autosave_stuff' ), 10 ); //TODO reactivate when 4.2 autosave is implemented
200
+		}
201
+	}
202
+
203
+
204
+
205
+	/**
206
+	 * Simply ensure that we simulate the correct post route for cpt screens
207
+	 *
208
+	 * @param WP_Screen $current_screen
209
+	 * @return void
210
+	 */
211
+	public function modify_pagenow($current_screen)
212
+	{
213
+		global $pagenow, $hook_suffix;
214
+		//possibly reset pagenow.
215
+		if ( ! empty($this->_req_data['page'])
216
+			 && $this->_req_data['page'] == $this->page_slug
217
+			 && ! empty($this->_req_data['action'])
218
+			 && isset($this->_pagenow_map[$this->_req_data['action']])
219
+		) {
220
+			$pagenow = $this->_pagenow_map[$this->_req_data['action']];
221
+			$hook_suffix = $pagenow;
222
+		}
223
+	}
224
+
225
+
226
+
227
+	/**
228
+	 * This method is used to register additional autosave containers to the _autosave_containers property.
229
+	 *
230
+	 * @todo We should automate this at some point by creating a wrapper for add_post_metabox and in our wrapper we
231
+	 *       automatically register the id for the post metabox as a container.
232
+	 * @param  array $ids an array of ids for containers that hold form inputs we want autosave to pickup.  Typically
233
+	 *                    you would send along the id of a metabox container.
234
+	 * @return void
235
+	 */
236
+	protected function _register_autosave_containers($ids)
237
+	{
238
+		$this->_autosave_containers = array_merge($this->_autosave_fields, (array)$ids);
239
+	}
240
+
241
+
242
+
243
+	/**
244
+	 * Something nifty.  We're going to loop through all the registered metaboxes and if the CALLBACK is an instance of
245
+	 * EE_Admin_Page OR EE_Admin_Hooks, then we'll add the id to our _autosave_containers array.
246
+	 */
247
+	protected function _set_autosave_containers()
248
+	{
249
+		global $wp_meta_boxes;
250
+		$containers = array();
251
+		if (empty($wp_meta_boxes)) {
252
+			return;
253
+		}
254
+		$current_metaboxes = isset($wp_meta_boxes[$this->page_slug]) ? $wp_meta_boxes[$this->page_slug] : array();
255
+		foreach ($current_metaboxes as $box_context) {
256
+			foreach ($box_context as $box_details) {
257
+				foreach ($box_details as $box) {
258
+					if (is_array($box['callback'])
259
+						&& ($box['callback'][0] instanceof EE_Admin_Page
260
+							|| $box['callback'][0] instanceof EE_Admin_Hooks)
261
+					) {
262
+						$containers[] = $box['id'];
263
+					}
264
+				}
265
+			}
266
+		}
267
+		$this->_autosave_containers = array_merge($this->_autosave_containers, $containers);
268
+		//add hidden inputs container
269
+		$this->_autosave_containers[] = 'ee-cpt-hidden-inputs';
270
+	}
271
+
272
+
273
+
274
+	protected function _load_autosave_scripts_styles()
275
+	{
276
+		/*wp_register_script('cpt-autosave', EE_ADMIN_URL . 'assets/ee-cpt-autosave.js', array('ee-serialize-full-array', 'event_editor_js'), EVENT_ESPRESSO_VERSION, TRUE );
277 277
         wp_enqueue_script('cpt-autosave');/**/ //todo re-enable when we start doing autosave again in 4.2
278 278
 
279
-        //filter _autosave_containers
280
-        $containers = apply_filters('FHEE__EE_Admin_Page_CPT___load_autosave_scripts_styles__containers',
281
-            $this->_autosave_containers, $this);
282
-        $containers = apply_filters('FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
283
-            $containers, $this);
284
-
285
-        wp_localize_script('event_editor_js', 'EE_AUTOSAVE_IDS',
286
-            $containers); //todo once we enable autosaves, this needs to be switched to localize with "cpt-autosave"
287
-
288
-        $unsaved_data_msg = array(
289
-            'eventmsg'     => sprintf(__("The changes you made to this %s will be lost if you navigate away from this page.",
290
-                'event_espresso'), $this->_cpt_object->labels->singular_name),
291
-            'inputChanged' => 0,
292
-        );
293
-        wp_localize_script('event_editor_js', 'UNSAVED_DATA_MSG', $unsaved_data_msg);
294
-    }
295
-
296
-
297
-
298
-    public function load_page_dependencies()
299
-    {
300
-        try {
301
-            $this->_load_page_dependencies();
302
-        } catch (EE_Error $e) {
303
-            $e->get_error();
304
-        }
305
-    }
306
-
307
-
308
-
309
-    /**
310
-     * overloading the EE_Admin_Page parent load_page_dependencies so we can get the cpt stuff added in appropriately
311
-     *
312
-     * @access protected
313
-     * @return void
314
-     */
315
-    protected function _load_page_dependencies()
316
-    {
317
-        //we only add stuff if this is a cpt_route!
318
-        if ( ! $this->_cpt_route) {
319
-            parent::_load_page_dependencies();
320
-            return;
321
-        }
322
-        //now let's do some automatic filters into the wp_system and we'll check to make sure the CHILD class automatically has the required methods in place.
323
-        //the following filters are for setting all the redirects on DEFAULT WP custom post type actions
324
-        //let's add a hidden input to the post-edit form so we know when we have to trigger our custom redirects!  Otherwise the redirects will happen on ALL post saves which wouldn't be good of course!
325
-        add_action('edit_form_after_title', array($this, 'cpt_post_form_hidden_input'));
326
-        //inject our Admin page nav tabs...
327
-        //let's make sure the nav tabs are set if they aren't already
328
-        //if ( empty( $this->_nav_tabs ) ) $this->_set_nav_tabs();
329
-        add_action('post_edit_form_tag', array($this, 'inject_nav_tabs'));
330
-        //modify the post_updated messages array
331
-        add_action('post_updated_messages', array($this, 'post_update_messages'), 10);
332
-        //add shortlink button to cpt edit screens.  We can do this as a universal thing BECAUSE, cpts use the same format for shortlinks as posts!
333
-        add_filter('pre_get_shortlink', array($this, 'add_shortlink_button_to_editor'), 10, 4);
334
-        //This basically allows us to change the title of the "publish" metabox area on CPT pages by setting a 'publishbox' value in the $_labels property array in the child class.
335
-        if ( ! empty($this->_labels['publishbox'])) {
336
-            $box_label = is_array($this->_labels['publishbox'])
337
-                         && isset($this->_labels['publishbox'][$this->_req_action])
338
-                ? $this->_labels['publishbox'][$this->_req_action] : $this->_labels['publishbox'];
339
-            remove_meta_box('submitdiv', __('Publish'), 'post_submit_meta_box', $this->_cpt_routes[$this->_req_action],
340
-                'side', 'core');
341
-            add_meta_box('submitdiv', $box_label, 'post_submit_meta_box', $this->_cpt_routes[$this->_req_action],
342
-                'side', 'core');
343
-        }
344
-        //let's add page_templates metabox if this cpt added support for it.
345
-        if ($this->_supports_page_templates($this->_cpt_object->name)) {
346
-            add_meta_box('page_templates', __('Page Template', 'event_espresso'),
347
-                array($this, 'page_template_meta_box'), $this->_cpt_routes[$this->_req_action], 'side', 'default');
348
-        }
349
-        //this is a filter that allows the addition of extra html after the permalink field on the wp post edit-form
350
-        if (method_exists($this, 'extra_permalink_field_buttons')) {
351
-            add_filter('get_sample_permalink_html', array($this, 'extra_permalink_field_buttons'), 10, 4);
352
-        }
353
-        //add preview button
354
-        add_filter('get_sample_permalink_html', array($this, 'preview_button_html'), 5, 4);
355
-        //insert our own post_stati dropdown
356
-        add_action('post_submitbox_misc_actions', array($this, 'custom_post_stati_dropdown'), 10);
357
-        //This allows adding additional information to the publish post submitbox on the wp post edit form
358
-        if (method_exists($this, 'extra_misc_actions_publish_box')) {
359
-            add_action('post_submitbox_misc_actions', array($this, 'extra_misc_actions_publish_box'), 10);
360
-        }
361
-        //This allows for adding additional stuff after the title field on the wp post edit form.  This is also before the wp_editor for post description field.
362
-        if (method_exists($this, 'edit_form_after_title')) {
363
-            add_action('edit_form_after_title', array($this, 'edit_form_after_title'), 10);
364
-        }
365
-        /**
366
-         * Filtering WP's esc_url to capture urls pointing to core wp routes so they point to our route.
367
-         */
368
-        add_filter('clean_url', array($this, 'switch_core_wp_urls_with_ours'), 10, 3);
369
-        parent::_load_page_dependencies();
370
-        //notice we are ALSO going to load the pagenow hook set for this route (see _before_page_setup for the reset of the pagenow global ). This is for any plugins that are doing things properly and hooking into the load page hook for core wp cpt routes.
371
-        global $pagenow;
372
-        do_action('load-' . $pagenow);
373
-        $this->modify_current_screen();
374
-        add_action('admin_enqueue_scripts', array($this, 'setup_autosave_hooks'), 30);
375
-        //we route REALLY early.
376
-        try {
377
-            $this->_route_admin_request();
378
-        } catch (EE_Error $e) {
379
-            $e->get_error();
380
-        }
381
-    }
382
-
383
-
384
-
385
-    /**
386
-     * Since we don't want users going to default core wp routes, this will check any wp urls run through the
387
-     * esc_url() method and if we see a url matching a pattern for our routes, we'll modify it to point to OUR
388
-     * route instead.
389
-     *
390
-     * @param string $good_protocol_url The escaped url.
391
-     * @param string $original_url      The original url.
392
-     * @param string $_context          The context sendt to the esc_url method.
393
-     * @return string possibly a new url for our route.
394
-     */
395
-    public function switch_core_wp_urls_with_ours($good_protocol_url, $original_url, $_context)
396
-    {
397
-        $routes_to_match = array(
398
-            0 => array(
399
-                'edit.php?post_type=espresso_attendees',
400
-                'admin.php?page=espresso_registrations&action=contact_list',
401
-            ),
402
-            1 => array(
403
-                'edit.php?post_type=' . $this->_cpt_object->name,
404
-                'admin.php?page=' . $this->_cpt_object->name,
405
-            ),
406
-        );
407
-        foreach ($routes_to_match as $route_matches) {
408
-            if (strpos($good_protocol_url, $route_matches[0]) !== false) {
409
-                return str_replace($route_matches[0], $route_matches[1], $good_protocol_url);
410
-            }
411
-        }
412
-        return $good_protocol_url;
413
-    }
414
-
415
-
416
-
417
-    /**
418
-     * Determine whether the current cpt supports page templates or not.
419
-     *
420
-     * @since %VER%
421
-     * @param string $cpt_name The cpt slug we're checking on.
422
-     * @return bool True supported, false not.
423
-     */
424
-    private function _supports_page_templates($cpt_name)
425
-    {
426
-
427
-        $cpt_args = EE_Register_CPTs::get_CPTs();
428
-        $cpt_args = isset($cpt_args[$cpt_name]) ? $cpt_args[$cpt_name]['args'] : array();
429
-        $cpt_has_support = ! empty($cpt_args['page_templates']);
430
-
431
-        //if the installed version of WP is > 4.7 we do some additional checks.
432
-        if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
433
-            $post_templates = wp_get_theme()->get_post_templates();
434
-            //if there are $post_templates for this cpt, then we return false for this method because
435
-            //that means we aren't going to load our page template manager and leave that up to the native
436
-            //cpt template manager.
437
-            $cpt_has_support = ! isset($post_templates[$cpt_name]) ? $cpt_has_support : false;
438
-        }
439
-
440
-        return $cpt_has_support;
441
-    }
442
-
443
-
444
-    /**
445
-     * Callback for the page_templates metabox selector.
446
-     *
447
-     * @since %VER%
448
-     * @return string html
449
-     */
450
-    public function page_template_meta_box()
451
-    {
452
-        global $post;
453
-        $template = '';
454
-
455
-        if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
456
-            $page_template_count = count(get_page_templates());
457
-        } else {
458
-            $page_template_count = count(get_page_templates($post));
459
-        };
460
-
461
-        if ($page_template_count) {
462
-            $page_template = get_post_meta($post->ID, '_wp_page_template', true);
463
-            $template      = ! empty($page_template) ? $page_template : '';
464
-        }
465
-        ?>
279
+		//filter _autosave_containers
280
+		$containers = apply_filters('FHEE__EE_Admin_Page_CPT___load_autosave_scripts_styles__containers',
281
+			$this->_autosave_containers, $this);
282
+		$containers = apply_filters('FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
283
+			$containers, $this);
284
+
285
+		wp_localize_script('event_editor_js', 'EE_AUTOSAVE_IDS',
286
+			$containers); //todo once we enable autosaves, this needs to be switched to localize with "cpt-autosave"
287
+
288
+		$unsaved_data_msg = array(
289
+			'eventmsg'     => sprintf(__("The changes you made to this %s will be lost if you navigate away from this page.",
290
+				'event_espresso'), $this->_cpt_object->labels->singular_name),
291
+			'inputChanged' => 0,
292
+		);
293
+		wp_localize_script('event_editor_js', 'UNSAVED_DATA_MSG', $unsaved_data_msg);
294
+	}
295
+
296
+
297
+
298
+	public function load_page_dependencies()
299
+	{
300
+		try {
301
+			$this->_load_page_dependencies();
302
+		} catch (EE_Error $e) {
303
+			$e->get_error();
304
+		}
305
+	}
306
+
307
+
308
+
309
+	/**
310
+	 * overloading the EE_Admin_Page parent load_page_dependencies so we can get the cpt stuff added in appropriately
311
+	 *
312
+	 * @access protected
313
+	 * @return void
314
+	 */
315
+	protected function _load_page_dependencies()
316
+	{
317
+		//we only add stuff if this is a cpt_route!
318
+		if ( ! $this->_cpt_route) {
319
+			parent::_load_page_dependencies();
320
+			return;
321
+		}
322
+		//now let's do some automatic filters into the wp_system and we'll check to make sure the CHILD class automatically has the required methods in place.
323
+		//the following filters are for setting all the redirects on DEFAULT WP custom post type actions
324
+		//let's add a hidden input to the post-edit form so we know when we have to trigger our custom redirects!  Otherwise the redirects will happen on ALL post saves which wouldn't be good of course!
325
+		add_action('edit_form_after_title', array($this, 'cpt_post_form_hidden_input'));
326
+		//inject our Admin page nav tabs...
327
+		//let's make sure the nav tabs are set if they aren't already
328
+		//if ( empty( $this->_nav_tabs ) ) $this->_set_nav_tabs();
329
+		add_action('post_edit_form_tag', array($this, 'inject_nav_tabs'));
330
+		//modify the post_updated messages array
331
+		add_action('post_updated_messages', array($this, 'post_update_messages'), 10);
332
+		//add shortlink button to cpt edit screens.  We can do this as a universal thing BECAUSE, cpts use the same format for shortlinks as posts!
333
+		add_filter('pre_get_shortlink', array($this, 'add_shortlink_button_to_editor'), 10, 4);
334
+		//This basically allows us to change the title of the "publish" metabox area on CPT pages by setting a 'publishbox' value in the $_labels property array in the child class.
335
+		if ( ! empty($this->_labels['publishbox'])) {
336
+			$box_label = is_array($this->_labels['publishbox'])
337
+						 && isset($this->_labels['publishbox'][$this->_req_action])
338
+				? $this->_labels['publishbox'][$this->_req_action] : $this->_labels['publishbox'];
339
+			remove_meta_box('submitdiv', __('Publish'), 'post_submit_meta_box', $this->_cpt_routes[$this->_req_action],
340
+				'side', 'core');
341
+			add_meta_box('submitdiv', $box_label, 'post_submit_meta_box', $this->_cpt_routes[$this->_req_action],
342
+				'side', 'core');
343
+		}
344
+		//let's add page_templates metabox if this cpt added support for it.
345
+		if ($this->_supports_page_templates($this->_cpt_object->name)) {
346
+			add_meta_box('page_templates', __('Page Template', 'event_espresso'),
347
+				array($this, 'page_template_meta_box'), $this->_cpt_routes[$this->_req_action], 'side', 'default');
348
+		}
349
+		//this is a filter that allows the addition of extra html after the permalink field on the wp post edit-form
350
+		if (method_exists($this, 'extra_permalink_field_buttons')) {
351
+			add_filter('get_sample_permalink_html', array($this, 'extra_permalink_field_buttons'), 10, 4);
352
+		}
353
+		//add preview button
354
+		add_filter('get_sample_permalink_html', array($this, 'preview_button_html'), 5, 4);
355
+		//insert our own post_stati dropdown
356
+		add_action('post_submitbox_misc_actions', array($this, 'custom_post_stati_dropdown'), 10);
357
+		//This allows adding additional information to the publish post submitbox on the wp post edit form
358
+		if (method_exists($this, 'extra_misc_actions_publish_box')) {
359
+			add_action('post_submitbox_misc_actions', array($this, 'extra_misc_actions_publish_box'), 10);
360
+		}
361
+		//This allows for adding additional stuff after the title field on the wp post edit form.  This is also before the wp_editor for post description field.
362
+		if (method_exists($this, 'edit_form_after_title')) {
363
+			add_action('edit_form_after_title', array($this, 'edit_form_after_title'), 10);
364
+		}
365
+		/**
366
+		 * Filtering WP's esc_url to capture urls pointing to core wp routes so they point to our route.
367
+		 */
368
+		add_filter('clean_url', array($this, 'switch_core_wp_urls_with_ours'), 10, 3);
369
+		parent::_load_page_dependencies();
370
+		//notice we are ALSO going to load the pagenow hook set for this route (see _before_page_setup for the reset of the pagenow global ). This is for any plugins that are doing things properly and hooking into the load page hook for core wp cpt routes.
371
+		global $pagenow;
372
+		do_action('load-' . $pagenow);
373
+		$this->modify_current_screen();
374
+		add_action('admin_enqueue_scripts', array($this, 'setup_autosave_hooks'), 30);
375
+		//we route REALLY early.
376
+		try {
377
+			$this->_route_admin_request();
378
+		} catch (EE_Error $e) {
379
+			$e->get_error();
380
+		}
381
+	}
382
+
383
+
384
+
385
+	/**
386
+	 * Since we don't want users going to default core wp routes, this will check any wp urls run through the
387
+	 * esc_url() method and if we see a url matching a pattern for our routes, we'll modify it to point to OUR
388
+	 * route instead.
389
+	 *
390
+	 * @param string $good_protocol_url The escaped url.
391
+	 * @param string $original_url      The original url.
392
+	 * @param string $_context          The context sendt to the esc_url method.
393
+	 * @return string possibly a new url for our route.
394
+	 */
395
+	public function switch_core_wp_urls_with_ours($good_protocol_url, $original_url, $_context)
396
+	{
397
+		$routes_to_match = array(
398
+			0 => array(
399
+				'edit.php?post_type=espresso_attendees',
400
+				'admin.php?page=espresso_registrations&action=contact_list',
401
+			),
402
+			1 => array(
403
+				'edit.php?post_type=' . $this->_cpt_object->name,
404
+				'admin.php?page=' . $this->_cpt_object->name,
405
+			),
406
+		);
407
+		foreach ($routes_to_match as $route_matches) {
408
+			if (strpos($good_protocol_url, $route_matches[0]) !== false) {
409
+				return str_replace($route_matches[0], $route_matches[1], $good_protocol_url);
410
+			}
411
+		}
412
+		return $good_protocol_url;
413
+	}
414
+
415
+
416
+
417
+	/**
418
+	 * Determine whether the current cpt supports page templates or not.
419
+	 *
420
+	 * @since %VER%
421
+	 * @param string $cpt_name The cpt slug we're checking on.
422
+	 * @return bool True supported, false not.
423
+	 */
424
+	private function _supports_page_templates($cpt_name)
425
+	{
426
+
427
+		$cpt_args = EE_Register_CPTs::get_CPTs();
428
+		$cpt_args = isset($cpt_args[$cpt_name]) ? $cpt_args[$cpt_name]['args'] : array();
429
+		$cpt_has_support = ! empty($cpt_args['page_templates']);
430
+
431
+		//if the installed version of WP is > 4.7 we do some additional checks.
432
+		if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
433
+			$post_templates = wp_get_theme()->get_post_templates();
434
+			//if there are $post_templates for this cpt, then we return false for this method because
435
+			//that means we aren't going to load our page template manager and leave that up to the native
436
+			//cpt template manager.
437
+			$cpt_has_support = ! isset($post_templates[$cpt_name]) ? $cpt_has_support : false;
438
+		}
439
+
440
+		return $cpt_has_support;
441
+	}
442
+
443
+
444
+	/**
445
+	 * Callback for the page_templates metabox selector.
446
+	 *
447
+	 * @since %VER%
448
+	 * @return string html
449
+	 */
450
+	public function page_template_meta_box()
451
+	{
452
+		global $post;
453
+		$template = '';
454
+
455
+		if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
456
+			$page_template_count = count(get_page_templates());
457
+		} else {
458
+			$page_template_count = count(get_page_templates($post));
459
+		};
460
+
461
+		if ($page_template_count) {
462
+			$page_template = get_post_meta($post->ID, '_wp_page_template', true);
463
+			$template      = ! empty($page_template) ? $page_template : '';
464
+		}
465
+		?>
466 466
         <p><strong><?php _e('Template') ?></strong></p>
467 467
         <label class="screen-reader-text" for="page_template"><?php _e('Page Template') ?></label><select
468 468
             name="page_template" id="page_template">
@@ -470,437 +470,437 @@  discard block
 block discarded – undo
470 470
         <?php page_template_dropdown($template); ?>
471 471
     </select>
472 472
         <?php
473
-    }
474
-
475
-
476
-
477
-    /**
478
-     * if this post is a draft or scheduled post then we provide a preview button for user to click
479
-     * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
480
-     *
481
-     * @param  string $return    the current html
482
-     * @param  int    $id        the post id for the page
483
-     * @param  string $new_title What the title is
484
-     * @param  string $new_slug  what the slug is
485
-     * @return string            The new html string for the permalink area
486
-     */
487
-    public function preview_button_html($return, $id, $new_title, $new_slug)
488
-    {
489
-        $post = get_post($id);
490
-        if ('publish' != get_post_status($post)) {
491
-            //include shims for the `get_preview_post_link` function
492
-            require_once( EE_CORE . 'wordpress-shims.php' );
493
-            $return .= '<span_id="view-post-btn"><a target="_blank" href="'
494
-                       . get_preview_post_link($id)
495
-                       . '" class="button button-small">'
496
-                       . __('Preview', 'event_espresso')
497
-                       . '</a></span>'
498
-                       . "\n";
499
-        }
500
-        return $return;
501
-    }
502
-
503
-
504
-
505
-    /**
506
-     * add our custom post stati dropdown on the wp post page for this cpt
507
-     *
508
-     * @return string html for dropdown
509
-     */
510
-    public function custom_post_stati_dropdown()
511
-    {
512
-
513
-        $statuses         = $this->_cpt_model_obj->get_custom_post_statuses();
514
-        $cur_status_label = array_key_exists($this->_cpt_model_obj->status(), $statuses)
515
-            ? $statuses[$this->_cpt_model_obj->status()]
516
-            : '';
517
-        $template_args    = array(
518
-            'cur_status'            => $this->_cpt_model_obj->status(),
519
-            'statuses'              => $statuses,
520
-            'cur_status_label'      => $cur_status_label,
521
-            'localized_status_save' => sprintf(__('Save %s', 'event_espresso'), $cur_status_label),
522
-        );
523
-        //we'll add a trash post status (WP doesn't add one for some reason)
524
-        if ($this->_cpt_model_obj->status() == 'trash') {
525
-            $template_args['cur_status_label'] = __('Trashed', 'event_espresso');
526
-            $statuses['trash']                 = __('Trashed', 'event_espresso');
527
-            $template_args['statuses']         = $statuses;
528
-        }
529
-
530
-        $template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
531
-        EEH_Template::display_template($template, $template_args);
532
-    }
533
-
534
-
535
-
536
-    public function setup_autosave_hooks()
537
-    {
538
-        $this->_set_autosave_containers();
539
-        $this->_load_autosave_scripts_styles();
540
-    }
541
-
542
-
543
-
544
-    /**
545
-     * This is run on all WordPress autosaves AFTER the autosave is complete and sends along a $_POST object (available
546
-     * in $this->_req_data) containing: post_ID of the saved post autosavenonce for the saved post We'll do the check
547
-     * for the nonce in here, but then this method looks for two things:
548
-     * 1. Execute a method (if exists) matching 'ee_autosave_' and appended with the given route. OR
549
-     * 2. do_actions() for global or class specific actions that have been registered (for plugins/addons not in an
550
-     * EE_Admin_Page class. PLEASE NOTE: Data will be returned using the _return_json() object and so the
551
-     * $_template_args property should be used to hold the $data array.  We're expecting the following things set in
552
-     * template args.
553
-     *    1. $template_args['error'] = IF there is an error you can add the message in here.
554
-     *    2. $template_args['data']['items'] = an array of items that are setup in key index pairs of 'where_values_go'
555
-     *    => 'values_to_add'.  In other words, for the datetime metabox we'll have something like
556
-     *    $this->_template_args['data']['items'] = array(
557
-     *        'event-datetime-ids' => '1,2,3';
558
-     *    );
559
-     *    Keep in mind the following things:
560
-     *    - "where" index is for the input with the id as that string.
561
-     *    - "what" index is what will be used for the value of that input.
562
-     *
563
-     * @return void
564
-     */
565
-    public function do_extra_autosave_stuff()
566
-    {
567
-        //next let's check for the autosave nonce (we'll use _verify_nonce )
568
-        $nonce = isset($this->_req_data['autosavenonce']) ? $this->_req_data['autosavenonce'] : null;
569
-        $this->_verify_nonce($nonce, 'autosave');
570
-        //make sure we define doing autosave (cause WP isn't triggering this we want to make sure we define it)
571
-        if ( ! defined('DOING_AUTOSAVE')) {
572
-            define('DOING_AUTOSAVE', true);
573
-        }
574
-        //if we made it here then the nonce checked out.  Let's run our methods and actions
575
-        if (method_exists($this, '_ee_autosave_' . $this->_current_view)) {
576
-            call_user_func(array($this, '_ee_autosave_' . $this->_current_view));
577
-        } else {
578
-            $this->_template_args['success'] = true;
579
-        }
580
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
581
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
582
-        //now let's return json
583
-        $this->_return_json();
584
-    }
585
-
586
-
587
-
588
-    /**
589
-     * This takes care of setting up default routes and pages that utilize the core WP admin pages.
590
-     * Child classes can override the defaults (in cases for adding metaboxes etc.)
591
-     * but take care that you include the defaults here otherwise your core WP admin pages for the cpt won't work!
592
-     *
593
-     * @access protected
594
-     * @throws EE_Error
595
-     * @return void
596
-     */
597
-    protected function _extend_page_config_for_cpt()
598
-    {
599
-        //before doing anything we need to make sure this runs ONLY when the loaded page matches the set page_slug
600
-        if ((isset($this->_req_data['page']) && $this->_req_data['page'] != $this->page_slug)) {
601
-            return;
602
-        }
603
-        //set page routes and page config but ONLY if we're not viewing a custom setup cpt route as defined in _cpt_routes
604
-        if ( ! empty($this->_cpt_object)) {
605
-            $this->_page_routes = array_merge(array(
606
-                'create_new' => '_create_new_cpt_item',
607
-                'edit'       => '_edit_cpt_item',
608
-            ), $this->_page_routes);
609
-            $this->_page_config = array_merge(array(
610
-                'create_new' => array(
611
-                    'nav'           => array(
612
-                        'label' => $this->_cpt_object->labels->add_new_item,
613
-                        'order' => 5,
614
-                    ),
615
-                    'require_nonce' => false,
616
-                ),
617
-                'edit'       => array(
618
-                    'nav'           => array(
619
-                        'label'      => $this->_cpt_object->labels->edit_item,
620
-                        'order'      => 5,
621
-                        'persistent' => false,
622
-                        'url'        => '',
623
-                    ),
624
-                    'require_nonce' => false,
625
-                ),
626
-            ),
627
-                $this->_page_config
628
-            );
629
-        }
630
-        //load the next section only if this is a matching cpt route as set in the cpt routes array.
631
-        if ( ! isset($this->_cpt_routes[$this->_req_action])) {
632
-            return;
633
-        }
634
-        $this->_cpt_route = isset($this->_cpt_routes[$this->_req_action]) ? true : false;
635
-        //add_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', array( $this, 'modify_current_screen') );
636
-        if (empty($this->_cpt_object)) {
637
-            $msg = sprintf(__('This page has been set as being related to a registered custom post type, however, the custom post type object could not be retrieved. There are two possible reasons for this:  1. The "%s" does not match a registered post type. or 2. The custom post type is not registered for the "%s" action as indexed in the "$_cpt_routes" property on this class (%s).'),
638
-                $this->page_slug, $this->_req_action, get_class($this));
639
-            throw new EE_Error($msg);
640
-        }
641
-        if ($this->_cpt_route) {
642
-            $id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
643
-            $this->_set_model_object($id);
644
-        }
645
-    }
646
-
647
-
648
-
649
-    /**
650
-     * Sets the _cpt_model_object property using what has been set for the _cpt_model_name and a given id.
651
-     *
652
-     * @access protected
653
-     * @param int  $id The id to retrieve the model object for. If empty we set a default object.
654
-     * @param bool $ignore_route_check
655
-     */
656
-    protected function _set_model_object($id = null, $ignore_route_check = false)
657
-    {
658
-        $model = null;
659
-        if (
660
-            empty($this->_cpt_model_names)
661
-            || (
662
-                ! $ignore_route_check
663
-                && ! isset($this->_cpt_routes[$this->_req_action])
664
-            ) || (
665
-                $this->_cpt_model_obj instanceof EE_CPT_Base
666
-                && $this->_cpt_model_obj->ID() === $id
667
-            )
668
-        ) {
669
-            //get out cuz we either don't have a model name OR the object has already been set and it has the same id as what has been sent.
670
-            return;
671
-        }
672
-        //if ignore_route_check is true, then get the model name via EE_Register_CPTs
673
-        if ($ignore_route_check) {
674
-            $model_names = EE_Register_CPTs::get_cpt_model_names();
675
-            $post_type   = get_post_type($id);
676
-            if (isset($model_names[$post_type])) {
677
-                $model = EE_Registry::instance()->load_model($model_names[$post_type]);
678
-            }
679
-        } else {
680
-            $model = EE_Registry::instance()->load_model($this->_cpt_model_names[$this->_req_action]);
681
-        }
682
-        if ($model instanceof EEM_Base) {
683
-            $this->_cpt_model_obj = ! empty($id) ? $model->get_one_by_ID($id) : $model->create_default_object();
684
-        }
685
-        do_action('AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object');
686
-    }
687
-
688
-
689
-
690
-    /**
691
-     * admin_init_global
692
-     * This runs all the code that we want executed within the WP admin_init hook.
693
-     * This method executes for ALL EE Admin pages.
694
-     *
695
-     * @access public
696
-     * @return void
697
-     */
698
-    public function admin_init_global()
699
-    {
700
-        $post = isset($this->_req_data['post']) ? get_post($this->_req_data['post']) : null;
701
-        //its possible this is a new save so let's catch that instead
702
-        $post = isset($this->_req_data['post_ID']) ? get_post($this->_req_data['post_ID']) : $post;
703
-        $post_type = $post ? $post->post_type : false;
704
-        $current_route = isset($this->_req_data['current_route']) ? $this->_req_data['current_route']
705
-            : 'shouldneverwork';
706
-        $route_to_check = $post_type && isset($this->_cpt_routes[$current_route]) ? $this->_cpt_routes[$current_route]
707
-            : '';
708
-        add_filter('get_delete_post_link', array($this, 'modify_delete_post_link'), 10, 3);
709
-        add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 3);
710
-        if ($post_type === $route_to_check) {
711
-            add_filter('redirect_post_location', array($this, 'cpt_post_location_redirect'), 10, 2);
712
-            //catch trashed wp redirect
713
-            add_filter('wp_redirect', array($this, 'cpt_trash_post_location_redirect'), 10, 2);
714
-        }
715
-        //now let's filter redirect if we're on a revision page and the revision is for an event CPT.
716
-        $revision = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
717
-        if ( ! empty($revision)) {
718
-            $action = isset($this->_req_data['action']) ? $this->_req_data['action'] : null;
719
-            //doing a restore?
720
-            if ( ! empty($action) && $action == 'restore') {
721
-                //get post for revision
722
-                $rev_post = get_post($revision);
723
-                $rev_parent = get_post($rev_post->post_parent);
724
-                //only do our redirect filter AND our restore revision action if the post_type for the parent is one of our cpts.
725
-                if ($rev_parent && $rev_parent->post_type == $this->page_slug) {
726
-                    add_filter('wp_redirect', array($this, 'revision_redirect'), 10, 2);
727
-                    //restores of revisions
728
-                    add_action('wp_restore_post_revision', array($this, 'restore_revision'), 10, 2);
729
-                }
730
-            }
731
-        }
732
-        //NOTE we ONLY want to run these hooks if we're on the right class for the given post type.  Otherwise we could see some really freaky things happen!
733
-        if ($post_type && $post_type === $route_to_check) {
734
-            //$post_id, $post
735
-            add_action('save_post', array($this, 'insert_update'), 10, 3);
736
-            //$post_id
737
-            add_action('trashed_post', array($this, 'before_trash_cpt_item'), 10);
738
-            add_action('trashed_post', array($this, 'dont_permanently_delete_ee_cpts'), 10);
739
-            add_action('untrashed_post', array($this, 'before_restore_cpt_item'), 10);
740
-            add_action('after_delete_post', array($this, 'before_delete_cpt_item'), 10);
741
-        }
742
-    }
743
-
744
-
745
-
746
-    /**
747
-     * Callback for the WordPress trashed_post hook.
748
-     * Execute some basic checks before calling the trash_cpt_item declared in the child class.
749
-     *
750
-     * @param int $post_id
751
-     */
752
-    public function before_trash_cpt_item($post_id)
753
-    {
754
-        $this->_set_model_object($post_id, true);
755
-        //if our cpt object isn't existent then get out immediately.
756
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
757
-            return;
758
-        }
759
-        $this->trash_cpt_item($post_id);
760
-    }
761
-
762
-
763
-
764
-    /**
765
-     * Callback for the WordPress untrashed_post hook.
766
-     * Execute some basic checks before calling the restore_cpt_method in the child class.
767
-     *
768
-     * @param $post_id
769
-     */
770
-    public function before_restore_cpt_item($post_id)
771
-    {
772
-        $this->_set_model_object($post_id, true);
773
-        //if our cpt object isn't existent then get out immediately.
774
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
775
-            return;
776
-        }
777
-        $this->restore_cpt_item($post_id);
778
-    }
779
-
780
-
781
-
782
-    /**
783
-     * Callback for the WordPress after_delete_post hook.
784
-     * Execute some basic checks before calling the delete_cpt_item method in the child class.
785
-     *
786
-     * @param $post_id
787
-     */
788
-    public function before_delete_cpt_item($post_id)
789
-    {
790
-        $this->_set_model_object($post_id, true);
791
-        //if our cpt object isn't existent then get out immediately.
792
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
793
-            return;
794
-        }
795
-        $this->delete_cpt_item($post_id);
796
-    }
797
-
798
-
799
-
800
-    /**
801
-     * This simply verifies if the cpt_model_object is instantiated for the given page and throws an error message
802
-     * accordingly.
803
-     *
804
-     * @access public
805
-     * @throws EE_Error
806
-     * @return void
807
-     */
808
-    public function verify_cpt_object()
809
-    {
810
-        $label = ! empty($this->_cpt_object) ? $this->_cpt_object->labels->singular_name : $this->page_label;
811
-        // verify event object
812
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
813
-            throw new EE_Error(sprintf(__('Something has gone wrong with the page load because we are unable to set up the object for the %1$s.  This usually happens when the given id for the page route is NOT for the correct custom post type for this page',
814
-                'event_espresso'), $label));
815
-        }
816
-        //if auto-draft then throw an error
817
-        if ($this->_cpt_model_obj->get('status') == 'auto-draft') {
818
-            EE_Error::overwrite_errors();
819
-            EE_Error::add_error(sprintf(__('This %1$s was saved without a title, description, or excerpt which means that none of the extra details you added were saved properly.  All autodrafts will show up in the "draft" view of your event list table.  You can delete them from there. Please click the "Add %1$s" button to refresh and restart.'),
820
-                $label), __FILE__, __FUNCTION__, __LINE__);
821
-        }
822
-    }
823
-
824
-
825
-
826
-    /**
827
-     * admin_footer_scripts_global
828
-     * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
829
-     * will apply on ALL EE_Admin pages.
830
-     *
831
-     * @access public
832
-     * @return void
833
-     */
834
-    public function admin_footer_scripts_global()
835
-    {
836
-        $this->_add_admin_page_ajax_loading_img();
837
-        $this->_add_admin_page_overlay();
838
-    }
839
-
840
-
841
-
842
-    /**
843
-     * add in any global scripts for cpt routes
844
-     *
845
-     * @return void
846
-     */
847
-    public function load_global_scripts_styles()
848
-    {
849
-        parent::load_global_scripts_styles();
850
-        if ($this->_cpt_model_obj instanceof EE_CPT_Base) {
851
-            //setup custom post status object for localize script but only if we've got a cpt object
852
-            $statuses = $this->_cpt_model_obj->get_custom_post_statuses();
853
-            if ( ! empty($statuses)) {
854
-                //get ALL statuses!
855
-                $statuses = $this->_cpt_model_obj->get_all_post_statuses();
856
-                //setup object
857
-                $ee_cpt_statuses = array();
858
-                foreach ($statuses as $status => $label) {
859
-                    $ee_cpt_statuses[$status] = array(
860
-                        'label'      => $label,
861
-                        'save_label' => sprintf(__('Save as %s', 'event_espresso'), $label),
862
-                    );
863
-                }
864
-                wp_localize_script('ee_admin_js', 'eeCPTstatuses', $ee_cpt_statuses);
865
-            }
866
-        }
867
-    }
868
-
869
-
870
-
871
-    /**
872
-     * This is a wrapper for the insert/update routes for cpt items so we can add things that are common to ALL
873
-     * insert/updates
874
-     *
875
-     * @param  int     $post_id ID of post being updated
876
-     * @param  WP_Post $post    Post object from WP
877
-     * @param  bool    $update  Whether this is an update or a new save.
878
-     * @return void
879
-     */
880
-    public function insert_update($post_id, $post, $update)
881
-    {
882
-        //make sure that if this is a revision OR trash action that we don't do any updates!
883
-        if (
884
-            isset($this->_req_data['action'])
885
-            && (
886
-                $this->_req_data['action'] == 'restore'
887
-                || $this->_req_data['action'] == 'trash'
888
-            )
889
-        ) {
890
-            return;
891
-        }
892
-        $this->_set_model_object($post_id, true);
893
-        //if our cpt object is not instantiated and its NOT the same post_id as what is triggering this callback, then exit.
894
-        if ($update
895
-            && (
896
-                ! $this->_cpt_model_obj instanceof EE_CPT_Base
897
-                || $this->_cpt_model_obj->ID() !== $post_id
898
-            )
899
-        ) {
900
-            return;
901
-        }
902
-        //check for autosave and update our req_data property accordingly.
903
-        /*if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE && isset( $this->_req_data['ee_autosave_data'] ) ) {
473
+	}
474
+
475
+
476
+
477
+	/**
478
+	 * if this post is a draft or scheduled post then we provide a preview button for user to click
479
+	 * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
480
+	 *
481
+	 * @param  string $return    the current html
482
+	 * @param  int    $id        the post id for the page
483
+	 * @param  string $new_title What the title is
484
+	 * @param  string $new_slug  what the slug is
485
+	 * @return string            The new html string for the permalink area
486
+	 */
487
+	public function preview_button_html($return, $id, $new_title, $new_slug)
488
+	{
489
+		$post = get_post($id);
490
+		if ('publish' != get_post_status($post)) {
491
+			//include shims for the `get_preview_post_link` function
492
+			require_once( EE_CORE . 'wordpress-shims.php' );
493
+			$return .= '<span_id="view-post-btn"><a target="_blank" href="'
494
+					   . get_preview_post_link($id)
495
+					   . '" class="button button-small">'
496
+					   . __('Preview', 'event_espresso')
497
+					   . '</a></span>'
498
+					   . "\n";
499
+		}
500
+		return $return;
501
+	}
502
+
503
+
504
+
505
+	/**
506
+	 * add our custom post stati dropdown on the wp post page for this cpt
507
+	 *
508
+	 * @return string html for dropdown
509
+	 */
510
+	public function custom_post_stati_dropdown()
511
+	{
512
+
513
+		$statuses         = $this->_cpt_model_obj->get_custom_post_statuses();
514
+		$cur_status_label = array_key_exists($this->_cpt_model_obj->status(), $statuses)
515
+			? $statuses[$this->_cpt_model_obj->status()]
516
+			: '';
517
+		$template_args    = array(
518
+			'cur_status'            => $this->_cpt_model_obj->status(),
519
+			'statuses'              => $statuses,
520
+			'cur_status_label'      => $cur_status_label,
521
+			'localized_status_save' => sprintf(__('Save %s', 'event_espresso'), $cur_status_label),
522
+		);
523
+		//we'll add a trash post status (WP doesn't add one for some reason)
524
+		if ($this->_cpt_model_obj->status() == 'trash') {
525
+			$template_args['cur_status_label'] = __('Trashed', 'event_espresso');
526
+			$statuses['trash']                 = __('Trashed', 'event_espresso');
527
+			$template_args['statuses']         = $statuses;
528
+		}
529
+
530
+		$template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
531
+		EEH_Template::display_template($template, $template_args);
532
+	}
533
+
534
+
535
+
536
+	public function setup_autosave_hooks()
537
+	{
538
+		$this->_set_autosave_containers();
539
+		$this->_load_autosave_scripts_styles();
540
+	}
541
+
542
+
543
+
544
+	/**
545
+	 * This is run on all WordPress autosaves AFTER the autosave is complete and sends along a $_POST object (available
546
+	 * in $this->_req_data) containing: post_ID of the saved post autosavenonce for the saved post We'll do the check
547
+	 * for the nonce in here, but then this method looks for two things:
548
+	 * 1. Execute a method (if exists) matching 'ee_autosave_' and appended with the given route. OR
549
+	 * 2. do_actions() for global or class specific actions that have been registered (for plugins/addons not in an
550
+	 * EE_Admin_Page class. PLEASE NOTE: Data will be returned using the _return_json() object and so the
551
+	 * $_template_args property should be used to hold the $data array.  We're expecting the following things set in
552
+	 * template args.
553
+	 *    1. $template_args['error'] = IF there is an error you can add the message in here.
554
+	 *    2. $template_args['data']['items'] = an array of items that are setup in key index pairs of 'where_values_go'
555
+	 *    => 'values_to_add'.  In other words, for the datetime metabox we'll have something like
556
+	 *    $this->_template_args['data']['items'] = array(
557
+	 *        'event-datetime-ids' => '1,2,3';
558
+	 *    );
559
+	 *    Keep in mind the following things:
560
+	 *    - "where" index is for the input with the id as that string.
561
+	 *    - "what" index is what will be used for the value of that input.
562
+	 *
563
+	 * @return void
564
+	 */
565
+	public function do_extra_autosave_stuff()
566
+	{
567
+		//next let's check for the autosave nonce (we'll use _verify_nonce )
568
+		$nonce = isset($this->_req_data['autosavenonce']) ? $this->_req_data['autosavenonce'] : null;
569
+		$this->_verify_nonce($nonce, 'autosave');
570
+		//make sure we define doing autosave (cause WP isn't triggering this we want to make sure we define it)
571
+		if ( ! defined('DOING_AUTOSAVE')) {
572
+			define('DOING_AUTOSAVE', true);
573
+		}
574
+		//if we made it here then the nonce checked out.  Let's run our methods and actions
575
+		if (method_exists($this, '_ee_autosave_' . $this->_current_view)) {
576
+			call_user_func(array($this, '_ee_autosave_' . $this->_current_view));
577
+		} else {
578
+			$this->_template_args['success'] = true;
579
+		}
580
+		do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
581
+		do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
582
+		//now let's return json
583
+		$this->_return_json();
584
+	}
585
+
586
+
587
+
588
+	/**
589
+	 * This takes care of setting up default routes and pages that utilize the core WP admin pages.
590
+	 * Child classes can override the defaults (in cases for adding metaboxes etc.)
591
+	 * but take care that you include the defaults here otherwise your core WP admin pages for the cpt won't work!
592
+	 *
593
+	 * @access protected
594
+	 * @throws EE_Error
595
+	 * @return void
596
+	 */
597
+	protected function _extend_page_config_for_cpt()
598
+	{
599
+		//before doing anything we need to make sure this runs ONLY when the loaded page matches the set page_slug
600
+		if ((isset($this->_req_data['page']) && $this->_req_data['page'] != $this->page_slug)) {
601
+			return;
602
+		}
603
+		//set page routes and page config but ONLY if we're not viewing a custom setup cpt route as defined in _cpt_routes
604
+		if ( ! empty($this->_cpt_object)) {
605
+			$this->_page_routes = array_merge(array(
606
+				'create_new' => '_create_new_cpt_item',
607
+				'edit'       => '_edit_cpt_item',
608
+			), $this->_page_routes);
609
+			$this->_page_config = array_merge(array(
610
+				'create_new' => array(
611
+					'nav'           => array(
612
+						'label' => $this->_cpt_object->labels->add_new_item,
613
+						'order' => 5,
614
+					),
615
+					'require_nonce' => false,
616
+				),
617
+				'edit'       => array(
618
+					'nav'           => array(
619
+						'label'      => $this->_cpt_object->labels->edit_item,
620
+						'order'      => 5,
621
+						'persistent' => false,
622
+						'url'        => '',
623
+					),
624
+					'require_nonce' => false,
625
+				),
626
+			),
627
+				$this->_page_config
628
+			);
629
+		}
630
+		//load the next section only if this is a matching cpt route as set in the cpt routes array.
631
+		if ( ! isset($this->_cpt_routes[$this->_req_action])) {
632
+			return;
633
+		}
634
+		$this->_cpt_route = isset($this->_cpt_routes[$this->_req_action]) ? true : false;
635
+		//add_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', array( $this, 'modify_current_screen') );
636
+		if (empty($this->_cpt_object)) {
637
+			$msg = sprintf(__('This page has been set as being related to a registered custom post type, however, the custom post type object could not be retrieved. There are two possible reasons for this:  1. The "%s" does not match a registered post type. or 2. The custom post type is not registered for the "%s" action as indexed in the "$_cpt_routes" property on this class (%s).'),
638
+				$this->page_slug, $this->_req_action, get_class($this));
639
+			throw new EE_Error($msg);
640
+		}
641
+		if ($this->_cpt_route) {
642
+			$id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
643
+			$this->_set_model_object($id);
644
+		}
645
+	}
646
+
647
+
648
+
649
+	/**
650
+	 * Sets the _cpt_model_object property using what has been set for the _cpt_model_name and a given id.
651
+	 *
652
+	 * @access protected
653
+	 * @param int  $id The id to retrieve the model object for. If empty we set a default object.
654
+	 * @param bool $ignore_route_check
655
+	 */
656
+	protected function _set_model_object($id = null, $ignore_route_check = false)
657
+	{
658
+		$model = null;
659
+		if (
660
+			empty($this->_cpt_model_names)
661
+			|| (
662
+				! $ignore_route_check
663
+				&& ! isset($this->_cpt_routes[$this->_req_action])
664
+			) || (
665
+				$this->_cpt_model_obj instanceof EE_CPT_Base
666
+				&& $this->_cpt_model_obj->ID() === $id
667
+			)
668
+		) {
669
+			//get out cuz we either don't have a model name OR the object has already been set and it has the same id as what has been sent.
670
+			return;
671
+		}
672
+		//if ignore_route_check is true, then get the model name via EE_Register_CPTs
673
+		if ($ignore_route_check) {
674
+			$model_names = EE_Register_CPTs::get_cpt_model_names();
675
+			$post_type   = get_post_type($id);
676
+			if (isset($model_names[$post_type])) {
677
+				$model = EE_Registry::instance()->load_model($model_names[$post_type]);
678
+			}
679
+		} else {
680
+			$model = EE_Registry::instance()->load_model($this->_cpt_model_names[$this->_req_action]);
681
+		}
682
+		if ($model instanceof EEM_Base) {
683
+			$this->_cpt_model_obj = ! empty($id) ? $model->get_one_by_ID($id) : $model->create_default_object();
684
+		}
685
+		do_action('AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object');
686
+	}
687
+
688
+
689
+
690
+	/**
691
+	 * admin_init_global
692
+	 * This runs all the code that we want executed within the WP admin_init hook.
693
+	 * This method executes for ALL EE Admin pages.
694
+	 *
695
+	 * @access public
696
+	 * @return void
697
+	 */
698
+	public function admin_init_global()
699
+	{
700
+		$post = isset($this->_req_data['post']) ? get_post($this->_req_data['post']) : null;
701
+		//its possible this is a new save so let's catch that instead
702
+		$post = isset($this->_req_data['post_ID']) ? get_post($this->_req_data['post_ID']) : $post;
703
+		$post_type = $post ? $post->post_type : false;
704
+		$current_route = isset($this->_req_data['current_route']) ? $this->_req_data['current_route']
705
+			: 'shouldneverwork';
706
+		$route_to_check = $post_type && isset($this->_cpt_routes[$current_route]) ? $this->_cpt_routes[$current_route]
707
+			: '';
708
+		add_filter('get_delete_post_link', array($this, 'modify_delete_post_link'), 10, 3);
709
+		add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 3);
710
+		if ($post_type === $route_to_check) {
711
+			add_filter('redirect_post_location', array($this, 'cpt_post_location_redirect'), 10, 2);
712
+			//catch trashed wp redirect
713
+			add_filter('wp_redirect', array($this, 'cpt_trash_post_location_redirect'), 10, 2);
714
+		}
715
+		//now let's filter redirect if we're on a revision page and the revision is for an event CPT.
716
+		$revision = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
717
+		if ( ! empty($revision)) {
718
+			$action = isset($this->_req_data['action']) ? $this->_req_data['action'] : null;
719
+			//doing a restore?
720
+			if ( ! empty($action) && $action == 'restore') {
721
+				//get post for revision
722
+				$rev_post = get_post($revision);
723
+				$rev_parent = get_post($rev_post->post_parent);
724
+				//only do our redirect filter AND our restore revision action if the post_type for the parent is one of our cpts.
725
+				if ($rev_parent && $rev_parent->post_type == $this->page_slug) {
726
+					add_filter('wp_redirect', array($this, 'revision_redirect'), 10, 2);
727
+					//restores of revisions
728
+					add_action('wp_restore_post_revision', array($this, 'restore_revision'), 10, 2);
729
+				}
730
+			}
731
+		}
732
+		//NOTE we ONLY want to run these hooks if we're on the right class for the given post type.  Otherwise we could see some really freaky things happen!
733
+		if ($post_type && $post_type === $route_to_check) {
734
+			//$post_id, $post
735
+			add_action('save_post', array($this, 'insert_update'), 10, 3);
736
+			//$post_id
737
+			add_action('trashed_post', array($this, 'before_trash_cpt_item'), 10);
738
+			add_action('trashed_post', array($this, 'dont_permanently_delete_ee_cpts'), 10);
739
+			add_action('untrashed_post', array($this, 'before_restore_cpt_item'), 10);
740
+			add_action('after_delete_post', array($this, 'before_delete_cpt_item'), 10);
741
+		}
742
+	}
743
+
744
+
745
+
746
+	/**
747
+	 * Callback for the WordPress trashed_post hook.
748
+	 * Execute some basic checks before calling the trash_cpt_item declared in the child class.
749
+	 *
750
+	 * @param int $post_id
751
+	 */
752
+	public function before_trash_cpt_item($post_id)
753
+	{
754
+		$this->_set_model_object($post_id, true);
755
+		//if our cpt object isn't existent then get out immediately.
756
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
757
+			return;
758
+		}
759
+		$this->trash_cpt_item($post_id);
760
+	}
761
+
762
+
763
+
764
+	/**
765
+	 * Callback for the WordPress untrashed_post hook.
766
+	 * Execute some basic checks before calling the restore_cpt_method in the child class.
767
+	 *
768
+	 * @param $post_id
769
+	 */
770
+	public function before_restore_cpt_item($post_id)
771
+	{
772
+		$this->_set_model_object($post_id, true);
773
+		//if our cpt object isn't existent then get out immediately.
774
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
775
+			return;
776
+		}
777
+		$this->restore_cpt_item($post_id);
778
+	}
779
+
780
+
781
+
782
+	/**
783
+	 * Callback for the WordPress after_delete_post hook.
784
+	 * Execute some basic checks before calling the delete_cpt_item method in the child class.
785
+	 *
786
+	 * @param $post_id
787
+	 */
788
+	public function before_delete_cpt_item($post_id)
789
+	{
790
+		$this->_set_model_object($post_id, true);
791
+		//if our cpt object isn't existent then get out immediately.
792
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
793
+			return;
794
+		}
795
+		$this->delete_cpt_item($post_id);
796
+	}
797
+
798
+
799
+
800
+	/**
801
+	 * This simply verifies if the cpt_model_object is instantiated for the given page and throws an error message
802
+	 * accordingly.
803
+	 *
804
+	 * @access public
805
+	 * @throws EE_Error
806
+	 * @return void
807
+	 */
808
+	public function verify_cpt_object()
809
+	{
810
+		$label = ! empty($this->_cpt_object) ? $this->_cpt_object->labels->singular_name : $this->page_label;
811
+		// verify event object
812
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
813
+			throw new EE_Error(sprintf(__('Something has gone wrong with the page load because we are unable to set up the object for the %1$s.  This usually happens when the given id for the page route is NOT for the correct custom post type for this page',
814
+				'event_espresso'), $label));
815
+		}
816
+		//if auto-draft then throw an error
817
+		if ($this->_cpt_model_obj->get('status') == 'auto-draft') {
818
+			EE_Error::overwrite_errors();
819
+			EE_Error::add_error(sprintf(__('This %1$s was saved without a title, description, or excerpt which means that none of the extra details you added were saved properly.  All autodrafts will show up in the "draft" view of your event list table.  You can delete them from there. Please click the "Add %1$s" button to refresh and restart.'),
820
+				$label), __FILE__, __FUNCTION__, __LINE__);
821
+		}
822
+	}
823
+
824
+
825
+
826
+	/**
827
+	 * admin_footer_scripts_global
828
+	 * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
829
+	 * will apply on ALL EE_Admin pages.
830
+	 *
831
+	 * @access public
832
+	 * @return void
833
+	 */
834
+	public function admin_footer_scripts_global()
835
+	{
836
+		$this->_add_admin_page_ajax_loading_img();
837
+		$this->_add_admin_page_overlay();
838
+	}
839
+
840
+
841
+
842
+	/**
843
+	 * add in any global scripts for cpt routes
844
+	 *
845
+	 * @return void
846
+	 */
847
+	public function load_global_scripts_styles()
848
+	{
849
+		parent::load_global_scripts_styles();
850
+		if ($this->_cpt_model_obj instanceof EE_CPT_Base) {
851
+			//setup custom post status object for localize script but only if we've got a cpt object
852
+			$statuses = $this->_cpt_model_obj->get_custom_post_statuses();
853
+			if ( ! empty($statuses)) {
854
+				//get ALL statuses!
855
+				$statuses = $this->_cpt_model_obj->get_all_post_statuses();
856
+				//setup object
857
+				$ee_cpt_statuses = array();
858
+				foreach ($statuses as $status => $label) {
859
+					$ee_cpt_statuses[$status] = array(
860
+						'label'      => $label,
861
+						'save_label' => sprintf(__('Save as %s', 'event_espresso'), $label),
862
+					);
863
+				}
864
+				wp_localize_script('ee_admin_js', 'eeCPTstatuses', $ee_cpt_statuses);
865
+			}
866
+		}
867
+	}
868
+
869
+
870
+
871
+	/**
872
+	 * This is a wrapper for the insert/update routes for cpt items so we can add things that are common to ALL
873
+	 * insert/updates
874
+	 *
875
+	 * @param  int     $post_id ID of post being updated
876
+	 * @param  WP_Post $post    Post object from WP
877
+	 * @param  bool    $update  Whether this is an update or a new save.
878
+	 * @return void
879
+	 */
880
+	public function insert_update($post_id, $post, $update)
881
+	{
882
+		//make sure that if this is a revision OR trash action that we don't do any updates!
883
+		if (
884
+			isset($this->_req_data['action'])
885
+			&& (
886
+				$this->_req_data['action'] == 'restore'
887
+				|| $this->_req_data['action'] == 'trash'
888
+			)
889
+		) {
890
+			return;
891
+		}
892
+		$this->_set_model_object($post_id, true);
893
+		//if our cpt object is not instantiated and its NOT the same post_id as what is triggering this callback, then exit.
894
+		if ($update
895
+			&& (
896
+				! $this->_cpt_model_obj instanceof EE_CPT_Base
897
+				|| $this->_cpt_model_obj->ID() !== $post_id
898
+			)
899
+		) {
900
+			return;
901
+		}
902
+		//check for autosave and update our req_data property accordingly.
903
+		/*if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE && isset( $this->_req_data['ee_autosave_data'] ) ) {
904 904
             foreach( (array) $this->_req_data['ee_autosave_data'] as $id => $values ) {
905 905
 
906 906
                 foreach ( (array) $values as $key => $value ) {
@@ -910,536 +910,536 @@  discard block
 block discarded – undo
910 910
 
911 911
         }/**/ //TODO reactivate after autosave is implemented in 4.2
912 912
 
913
-        //take care of updating any selected page_template IF this cpt supports it.
914
-        if ($this->_supports_page_templates($post->post_type) && ! empty($this->_req_data['page_template'])) {
915
-            //wp version aware.
916
-            if (EE_Recommended_Versions::check_wp_version('4.7', '>=')) {
917
-                $page_templates = wp_get_theme()->get_page_templates();
918
-            } else {
919
-                $post->page_template = $this->_req_data['page_template'];
920
-                $page_templates      = wp_get_theme()->get_page_templates($post);
921
-            }
922
-            if ('default' != $this->_req_data['page_template'] && ! isset($page_templates[$this->_req_data['page_template']])) {
923
-                EE_Error::add_error(__('Invalid Page Template.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
924
-            } else {
925
-                update_post_meta($post_id, '_wp_page_template', $this->_req_data['page_template']);
926
-            }
927
-        }
928
-        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
929
-            return;
930
-        } //TODO we'll remove this after reimplementing autosave in 4.2
931
-        $this->_insert_update_cpt_item($post_id, $post);
932
-    }
933
-
934
-
935
-
936
-    /**
937
-     * This hooks into the wp_trash_post() function and removes the `_wp_trash_meta_status` and `_wp_trash_meta_time`
938
-     * post meta IF the trashed post is one of our CPT's - note this method should only be called with our cpt routes
939
-     * so we don't have to check for our CPT.
940
-     *
941
-     * @param  int $post_id ID of the post
942
-     * @return void
943
-     */
944
-    public function dont_permanently_delete_ee_cpts($post_id)
945
-    {
946
-        //only do this if we're actually processing one of our CPTs
947
-        //if our cpt object isn't existent then get out immediately.
948
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
949
-            return;
950
-        }
951
-        delete_post_meta($post_id, '_wp_trash_meta_status');
952
-        delete_post_meta($post_id, '_wp_trash_meta_time');
953
-        //our cpts may have comments so let's take care of that too
954
-        delete_post_meta($post_id, '_wp_trash_meta_comments_status');
955
-    }
956
-
957
-
958
-
959
-    /**
960
-     * This is a wrapper for the restore_cpt_revision route for cpt items so we can make sure that when a revision is
961
-     * triggered that we restore related items.  In order to work cpt classes MUST have a restore_cpt_revision method
962
-     * in them.  We also have our OWN action in here so addons can hook into the restore process easily.
963
-     *
964
-     * @param  int $post_id     ID of cpt item
965
-     * @param  int $revision_id ID of revision being restored
966
-     * @return void
967
-     */
968
-    public function restore_revision($post_id, $revision_id)
969
-    {
970
-        $this->_restore_cpt_item($post_id, $revision_id);
971
-        //global action
972
-        do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
973
-        //class specific action so you can limit hooking into a specific page.
974
-        do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
975
-    }
976
-
977
-
978
-
979
-    /**
980
-     * @see restore_revision() for details
981
-     * @param  int $post_id     ID of cpt item
982
-     * @param  int $revision_id ID of revision for item
983
-     * @return void
984
-     */
985
-    abstract protected function _restore_cpt_item($post_id, $revision_id);
986
-
987
-
988
-
989
-    /**
990
-     * Execution of this method is added to the end of the load_page_dependencies method in the parent
991
-     * so that we can fix a bug where default core metaboxes were not being called in the sidebar.
992
-     * To fix we have to reset the current_screen using the page_slug
993
-     * (which is identical - or should be - to our registered_post_type id.)
994
-     * Also, since the core WP file loads the admin_header.php for WP
995
-     * (and there are a bunch of other things edit-form-advanced.php loads that need to happen really early)
996
-     * we need to load it NOW, hence our _route_admin_request in here. (Otherwise screen options won't be set).
997
-     *
998
-     * @return void
999
-     */
1000
-    public function modify_current_screen()
1001
-    {
1002
-        //ONLY do this if the current page_route IS a cpt route
1003
-        if ( ! $this->_cpt_route) {
1004
-            return;
1005
-        }
1006
-        //routing things REALLY early b/c this is a cpt admin page
1007
-        set_current_screen($this->_cpt_routes[$this->_req_action]);
1008
-        $this->_current_screen       = get_current_screen();
1009
-        $this->_current_screen->base = 'event-espresso';
1010
-        $this->_add_help_tabs(); //we make sure we add any help tabs back in!
1011
-        /*try {
913
+		//take care of updating any selected page_template IF this cpt supports it.
914
+		if ($this->_supports_page_templates($post->post_type) && ! empty($this->_req_data['page_template'])) {
915
+			//wp version aware.
916
+			if (EE_Recommended_Versions::check_wp_version('4.7', '>=')) {
917
+				$page_templates = wp_get_theme()->get_page_templates();
918
+			} else {
919
+				$post->page_template = $this->_req_data['page_template'];
920
+				$page_templates      = wp_get_theme()->get_page_templates($post);
921
+			}
922
+			if ('default' != $this->_req_data['page_template'] && ! isset($page_templates[$this->_req_data['page_template']])) {
923
+				EE_Error::add_error(__('Invalid Page Template.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
924
+			} else {
925
+				update_post_meta($post_id, '_wp_page_template', $this->_req_data['page_template']);
926
+			}
927
+		}
928
+		if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
929
+			return;
930
+		} //TODO we'll remove this after reimplementing autosave in 4.2
931
+		$this->_insert_update_cpt_item($post_id, $post);
932
+	}
933
+
934
+
935
+
936
+	/**
937
+	 * This hooks into the wp_trash_post() function and removes the `_wp_trash_meta_status` and `_wp_trash_meta_time`
938
+	 * post meta IF the trashed post is one of our CPT's - note this method should only be called with our cpt routes
939
+	 * so we don't have to check for our CPT.
940
+	 *
941
+	 * @param  int $post_id ID of the post
942
+	 * @return void
943
+	 */
944
+	public function dont_permanently_delete_ee_cpts($post_id)
945
+	{
946
+		//only do this if we're actually processing one of our CPTs
947
+		//if our cpt object isn't existent then get out immediately.
948
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
949
+			return;
950
+		}
951
+		delete_post_meta($post_id, '_wp_trash_meta_status');
952
+		delete_post_meta($post_id, '_wp_trash_meta_time');
953
+		//our cpts may have comments so let's take care of that too
954
+		delete_post_meta($post_id, '_wp_trash_meta_comments_status');
955
+	}
956
+
957
+
958
+
959
+	/**
960
+	 * This is a wrapper for the restore_cpt_revision route for cpt items so we can make sure that when a revision is
961
+	 * triggered that we restore related items.  In order to work cpt classes MUST have a restore_cpt_revision method
962
+	 * in them.  We also have our OWN action in here so addons can hook into the restore process easily.
963
+	 *
964
+	 * @param  int $post_id     ID of cpt item
965
+	 * @param  int $revision_id ID of revision being restored
966
+	 * @return void
967
+	 */
968
+	public function restore_revision($post_id, $revision_id)
969
+	{
970
+		$this->_restore_cpt_item($post_id, $revision_id);
971
+		//global action
972
+		do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
973
+		//class specific action so you can limit hooking into a specific page.
974
+		do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
975
+	}
976
+
977
+
978
+
979
+	/**
980
+	 * @see restore_revision() for details
981
+	 * @param  int $post_id     ID of cpt item
982
+	 * @param  int $revision_id ID of revision for item
983
+	 * @return void
984
+	 */
985
+	abstract protected function _restore_cpt_item($post_id, $revision_id);
986
+
987
+
988
+
989
+	/**
990
+	 * Execution of this method is added to the end of the load_page_dependencies method in the parent
991
+	 * so that we can fix a bug where default core metaboxes were not being called in the sidebar.
992
+	 * To fix we have to reset the current_screen using the page_slug
993
+	 * (which is identical - or should be - to our registered_post_type id.)
994
+	 * Also, since the core WP file loads the admin_header.php for WP
995
+	 * (and there are a bunch of other things edit-form-advanced.php loads that need to happen really early)
996
+	 * we need to load it NOW, hence our _route_admin_request in here. (Otherwise screen options won't be set).
997
+	 *
998
+	 * @return void
999
+	 */
1000
+	public function modify_current_screen()
1001
+	{
1002
+		//ONLY do this if the current page_route IS a cpt route
1003
+		if ( ! $this->_cpt_route) {
1004
+			return;
1005
+		}
1006
+		//routing things REALLY early b/c this is a cpt admin page
1007
+		set_current_screen($this->_cpt_routes[$this->_req_action]);
1008
+		$this->_current_screen       = get_current_screen();
1009
+		$this->_current_screen->base = 'event-espresso';
1010
+		$this->_add_help_tabs(); //we make sure we add any help tabs back in!
1011
+		/*try {
1012 1012
             $this->_route_admin_request();
1013 1013
         } catch ( EE_Error $e ) {
1014 1014
             $e->get_error();
1015 1015
         }/**/
1016
-    }
1017
-
1018
-
1019
-
1020
-    /**
1021
-     * This allows child classes to modify the default editor title that appears when people add a new or edit an
1022
-     * existing CPT item.     * This uses the _labels property set by the child class via _define_page_props. Just make
1023
-     * sure you have a key in _labels property that equals 'editor_title' and the value can be whatever you want the
1024
-     * default to be.
1025
-     *
1026
-     * @param string $title The new title (or existing if there is no editor_title defined)
1027
-     * @return string
1028
-     */
1029
-    public function add_custom_editor_default_title($title)
1030
-    {
1031
-        return isset($this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]])
1032
-            ? $this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]]
1033
-            : $title;
1034
-    }
1035
-
1036
-
1037
-
1038
-    /**
1039
-     * hooks into the wp_get_shortlink button and makes sure that the shortlink gets generated
1040
-     *
1041
-     * @param string $shortlink   The already generated shortlink
1042
-     * @param int    $id          Post ID for this item
1043
-     * @param string $context     The context for the link
1044
-     * @param bool   $allow_slugs Whether to allow post slugs in the shortlink.
1045
-     * @return string
1046
-     */
1047
-    public function add_shortlink_button_to_editor($shortlink, $id, $context, $allow_slugs)
1048
-    {
1049
-        if ( ! empty($id) && '' != get_option('permalink_structure')) {
1050
-            $post = get_post($id);
1051
-            if (isset($post->post_type) && $this->page_slug == $post->post_type) {
1052
-                $shortlink = home_url('?p=' . $post->ID);
1053
-            }
1054
-        }
1055
-        return $shortlink;
1056
-    }
1057
-
1058
-
1059
-
1060
-    /**
1061
-     * overriding the parent route_admin_request method so we DON'T run the route twice on cpt core page loads (it's
1062
-     * already run in modify_current_screen())
1063
-     *
1064
-     * @return void
1065
-     */
1066
-    public function route_admin_request()
1067
-    {
1068
-        if ($this->_cpt_route) {
1069
-            return;
1070
-        }
1071
-        try {
1072
-            $this->_route_admin_request();
1073
-        } catch (EE_Error $e) {
1074
-            $e->get_error();
1075
-        }
1076
-    }
1077
-
1078
-
1079
-
1080
-    /**
1081
-     * Add a hidden form input to cpt core pages so that we know to do redirects to our routes on saves
1082
-     *
1083
-     * @return string html
1084
-     */
1085
-    public function cpt_post_form_hidden_input()
1086
-    {
1087
-        echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="' . $this->_admin_base_url . '" />';
1088
-        //we're also going to add the route value and the current page so we can direct autosave parsing correctly
1089
-        echo '<div id="ee-cpt-hidden-inputs">';
1090
-        echo '<input type="hidden" id="current_route" name="current_route" value="' . $this->_current_view . '" />';
1091
-        echo '<input type="hidden" id="current_page" name="current_page" value="' . $this->page_slug . '" />';
1092
-        echo '</div>';
1093
-    }
1094
-
1095
-
1096
-
1097
-    /**
1098
-     * This allows us to redirect the location of revision restores when they happen so it goes to our CPT routes.
1099
-     *
1100
-     * @param  string $location Original location url
1101
-     * @param  int    $status   Status for http header
1102
-     * @return string           new (or original) url to redirect to.
1103
-     */
1104
-    public function revision_redirect($location, $status)
1105
-    {
1106
-        //get revision
1107
-        $rev_id = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
1108
-        //can't do anything without revision so let's get out if not present
1109
-        if (empty($rev_id)) {
1110
-            return $location;
1111
-        }
1112
-        //get rev_post_data
1113
-        $rev = get_post($rev_id);
1114
-        $admin_url = $this->_admin_base_url;
1115
-        $query_args = array(
1116
-            'action'   => 'edit',
1117
-            'post'     => $rev->post_parent,
1118
-            'revision' => $rev_id,
1119
-            'message'  => 5,
1120
-        );
1121
-        $this->_process_notices($query_args, true);
1122
-        return self::add_query_args_and_nonce($query_args, $admin_url);
1123
-    }
1124
-
1125
-
1126
-
1127
-    /**
1128
-     * Modify the edit post link generated by wp core function so that EE CPTs get setup differently.
1129
-     *
1130
-     * @param  string $link    the original generated link
1131
-     * @param  int    $id      post id
1132
-     * @param  string $context optional, defaults to display.  How to write the '&'
1133
-     * @return string          the link
1134
-     */
1135
-    public function modify_edit_post_link($link, $id, $context)
1136
-    {
1137
-        $post = get_post($id);
1138
-        if ( ! isset($this->_req_data['action'])
1139
-             || ! isset($this->_cpt_routes[$this->_req_data['action']])
1140
-             || $post->post_type !== $this->_cpt_routes[$this->_req_data['action']]
1141
-        ) {
1142
-            return $link;
1143
-        }
1144
-        $query_args = array(
1145
-            'action' => isset($this->_cpt_edit_routes[$post->post_type])
1146
-                ? $this->_cpt_edit_routes[$post->post_type]
1147
-                : 'edit',
1148
-            'post'   => $id,
1149
-        );
1150
-        return self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1151
-    }
1152
-
1153
-
1154
-
1155
-    /**
1156
-     * Modify the trash link on our cpt edit pages so it has the required query var for triggering redirect properly on
1157
-     * our routes.
1158
-     *
1159
-     * @param  string $delete_link  original delete link
1160
-     * @param  int    $post_id      id of cpt object
1161
-     * @param  bool   $force_delete whether this is forcing a hard delete instead of trash
1162
-     * @return string               new delete link
1163
-     */
1164
-    public function modify_delete_post_link($delete_link, $post_id, $force_delete)
1165
-    {
1166
-        $post = get_post($post_id);
1167
-        if ( ! isset($this->_req_data['action'])
1168
-             || (isset($this->_cpt_routes[$this->_req_data['action']])
1169
-                 && $post->post_type !== $this->_cpt_routes[$this->_req_data['action']])
1170
-        ) {
1171
-            return $delete_link;
1172
-        }
1173
-        return add_query_arg(array('current_route' => 'trash'), $delete_link);
1174
-    }
1175
-
1176
-
1177
-
1178
-    /**
1179
-     * This hooks into the wp_redirect filter and if trashed is detected, then we'll redirect to the appropriate EE
1180
-     * route
1181
-     *
1182
-     * @param  string $location url
1183
-     * @param  string $status   status
1184
-     * @return string           url to redirect to
1185
-     */
1186
-    public function cpt_trash_post_location_redirect($location, $status)
1187
-    {
1188
-        if (isset($this->_req_data['action']) && $this->_req_data['action'] !== 'trash' && empty($this->_req_data['post'])) {
1189
-            return $location;
1190
-        }
1191
-
1192
-        $post              = get_post($this->_req_data['post']);
1193
-        $query_args        = array('action' => 'default');
1194
-        $this->_cpt_object = get_post_type_object($post->post_type);
1195
-        EE_Error::add_success(sprintf(__('%s trashed.', 'event_espresso'), $this->_cpt_object->labels->singular_name));
1196
-        $this->_process_notices($query_args, true);
1197
-        return self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1198
-    }
1199
-
1200
-
1201
-
1202
-    /**
1203
-     * This is the callback for the 'redirect_post_location' filter in wp-admin/post.php
1204
-     * so that we can hijack the default redirect locations for wp custom post types
1205
-     * that WE'RE using and send back to OUR routes.  This should only be hooked in on the right route.
1206
-     *
1207
-     * @param  string $location This is the incoming currently set redirect location
1208
-     * @param  string $post_id  This is the 'ID' value of the wp_posts table
1209
-     * @return string           the new location to redirect to
1210
-     */
1211
-    public function cpt_post_location_redirect($location, $post_id)
1212
-    {
1213
-        //we DO have a match so let's setup the url
1214
-        //we have to get the post to determine our route
1215
-        $post       = get_post($post_id);
1216
-        $edit_route = $this->_cpt_edit_routes[$post->post_type];
1217
-        //shared query_args
1218
-        $query_args = array('action' => $edit_route, 'post' => $post_id);
1219
-        $admin_url  = $this->_admin_base_url;
1220
-        if (isset($this->_req_data['save']) || isset($this->_req_data['publish'])) {
1221
-            $status = get_post_status($post_id);
1222
-            if (isset($this->_req_data['publish'])) {
1223
-                switch ($status) {
1224
-                    case 'pending':
1225
-                        $message = 8;
1226
-                        break;
1227
-                    case 'future':
1228
-                        $message = 9;
1229
-                        break;
1230
-                    default:
1231
-                        $message = 6;
1232
-                }
1233
-            } else {
1234
-                $message = 'draft' == $status ? 10 : 1;
1235
-            }
1236
-        } else if (isset($this->_req_data['addmeta']) && $this->_req_data['addmeta']) {
1237
-            $message = 2;
1238
-            //			$append = '#postcustom';
1239
-        } else if (isset($this->_req_data['deletemeta']) && $this->_req_data['deletemeta']) {
1240
-            $message = 3;
1241
-            //			$append = '#postcustom';
1242
-        } elseif ($this->_req_data['action'] == 'post-quickpress-save-cont') {
1243
-            $message = 7;
1244
-        } else {
1245
-            $message = 4;
1246
-        }
1247
-        //change the message if the post type is not viewable on the frontend
1248
-        $this->_cpt_object = get_post_type_object($post->post_type);
1249
-        $message           = $message === 1 && ! $this->_cpt_object->publicly_queryable ? 4 : $message;
1250
-        $query_args = array_merge(array('message' => $message), $query_args);
1251
-        $this->_process_notices($query_args, true);
1252
-        return self::add_query_args_and_nonce($query_args, $admin_url);
1253
-    }
1254
-
1255
-
1256
-
1257
-    /**
1258
-     * This method is called to inject nav tabs on core WP cpt pages
1259
-     *
1260
-     * @access public
1261
-     * @return string html
1262
-     */
1263
-    public function inject_nav_tabs()
1264
-    {
1265
-        //can we hijack and insert the nav_tabs?
1266
-        $nav_tabs = $this->_get_main_nav_tabs();
1267
-        //first close off existing form tag
1268
-        $html = '>';
1269
-        $html .= $nav_tabs;
1270
-        //now let's handle the remaining tag ( missing ">" is CORRECT )
1271
-        $html .= '<span></span';
1272
-        echo $html;
1273
-    }
1274
-
1275
-
1276
-
1277
-    /**
1278
-     * This just sets up the post update messages when an update form is loaded
1279
-     *
1280
-     * @access public
1281
-     * @param  array $messages the original messages array
1282
-     * @return array           the new messages array
1283
-     */
1284
-    public function post_update_messages($messages)
1285
-    {
1286
-        global $post;
1287
-        $id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1288
-        $id = empty($id) && is_object($post) ? $post->ID : null;
1289
-        //		$post_type = $post ? $post->post_type : false;
1290
-        /*$current_route = isset($this->_req_data['current_route']) ? $this->_req_data['current_route'] : 'shouldneverwork';
1016
+	}
1017
+
1018
+
1019
+
1020
+	/**
1021
+	 * This allows child classes to modify the default editor title that appears when people add a new or edit an
1022
+	 * existing CPT item.     * This uses the _labels property set by the child class via _define_page_props. Just make
1023
+	 * sure you have a key in _labels property that equals 'editor_title' and the value can be whatever you want the
1024
+	 * default to be.
1025
+	 *
1026
+	 * @param string $title The new title (or existing if there is no editor_title defined)
1027
+	 * @return string
1028
+	 */
1029
+	public function add_custom_editor_default_title($title)
1030
+	{
1031
+		return isset($this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]])
1032
+			? $this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]]
1033
+			: $title;
1034
+	}
1035
+
1036
+
1037
+
1038
+	/**
1039
+	 * hooks into the wp_get_shortlink button and makes sure that the shortlink gets generated
1040
+	 *
1041
+	 * @param string $shortlink   The already generated shortlink
1042
+	 * @param int    $id          Post ID for this item
1043
+	 * @param string $context     The context for the link
1044
+	 * @param bool   $allow_slugs Whether to allow post slugs in the shortlink.
1045
+	 * @return string
1046
+	 */
1047
+	public function add_shortlink_button_to_editor($shortlink, $id, $context, $allow_slugs)
1048
+	{
1049
+		if ( ! empty($id) && '' != get_option('permalink_structure')) {
1050
+			$post = get_post($id);
1051
+			if (isset($post->post_type) && $this->page_slug == $post->post_type) {
1052
+				$shortlink = home_url('?p=' . $post->ID);
1053
+			}
1054
+		}
1055
+		return $shortlink;
1056
+	}
1057
+
1058
+
1059
+
1060
+	/**
1061
+	 * overriding the parent route_admin_request method so we DON'T run the route twice on cpt core page loads (it's
1062
+	 * already run in modify_current_screen())
1063
+	 *
1064
+	 * @return void
1065
+	 */
1066
+	public function route_admin_request()
1067
+	{
1068
+		if ($this->_cpt_route) {
1069
+			return;
1070
+		}
1071
+		try {
1072
+			$this->_route_admin_request();
1073
+		} catch (EE_Error $e) {
1074
+			$e->get_error();
1075
+		}
1076
+	}
1077
+
1078
+
1079
+
1080
+	/**
1081
+	 * Add a hidden form input to cpt core pages so that we know to do redirects to our routes on saves
1082
+	 *
1083
+	 * @return string html
1084
+	 */
1085
+	public function cpt_post_form_hidden_input()
1086
+	{
1087
+		echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="' . $this->_admin_base_url . '" />';
1088
+		//we're also going to add the route value and the current page so we can direct autosave parsing correctly
1089
+		echo '<div id="ee-cpt-hidden-inputs">';
1090
+		echo '<input type="hidden" id="current_route" name="current_route" value="' . $this->_current_view . '" />';
1091
+		echo '<input type="hidden" id="current_page" name="current_page" value="' . $this->page_slug . '" />';
1092
+		echo '</div>';
1093
+	}
1094
+
1095
+
1096
+
1097
+	/**
1098
+	 * This allows us to redirect the location of revision restores when they happen so it goes to our CPT routes.
1099
+	 *
1100
+	 * @param  string $location Original location url
1101
+	 * @param  int    $status   Status for http header
1102
+	 * @return string           new (or original) url to redirect to.
1103
+	 */
1104
+	public function revision_redirect($location, $status)
1105
+	{
1106
+		//get revision
1107
+		$rev_id = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
1108
+		//can't do anything without revision so let's get out if not present
1109
+		if (empty($rev_id)) {
1110
+			return $location;
1111
+		}
1112
+		//get rev_post_data
1113
+		$rev = get_post($rev_id);
1114
+		$admin_url = $this->_admin_base_url;
1115
+		$query_args = array(
1116
+			'action'   => 'edit',
1117
+			'post'     => $rev->post_parent,
1118
+			'revision' => $rev_id,
1119
+			'message'  => 5,
1120
+		);
1121
+		$this->_process_notices($query_args, true);
1122
+		return self::add_query_args_and_nonce($query_args, $admin_url);
1123
+	}
1124
+
1125
+
1126
+
1127
+	/**
1128
+	 * Modify the edit post link generated by wp core function so that EE CPTs get setup differently.
1129
+	 *
1130
+	 * @param  string $link    the original generated link
1131
+	 * @param  int    $id      post id
1132
+	 * @param  string $context optional, defaults to display.  How to write the '&'
1133
+	 * @return string          the link
1134
+	 */
1135
+	public function modify_edit_post_link($link, $id, $context)
1136
+	{
1137
+		$post = get_post($id);
1138
+		if ( ! isset($this->_req_data['action'])
1139
+			 || ! isset($this->_cpt_routes[$this->_req_data['action']])
1140
+			 || $post->post_type !== $this->_cpt_routes[$this->_req_data['action']]
1141
+		) {
1142
+			return $link;
1143
+		}
1144
+		$query_args = array(
1145
+			'action' => isset($this->_cpt_edit_routes[$post->post_type])
1146
+				? $this->_cpt_edit_routes[$post->post_type]
1147
+				: 'edit',
1148
+			'post'   => $id,
1149
+		);
1150
+		return self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1151
+	}
1152
+
1153
+
1154
+
1155
+	/**
1156
+	 * Modify the trash link on our cpt edit pages so it has the required query var for triggering redirect properly on
1157
+	 * our routes.
1158
+	 *
1159
+	 * @param  string $delete_link  original delete link
1160
+	 * @param  int    $post_id      id of cpt object
1161
+	 * @param  bool   $force_delete whether this is forcing a hard delete instead of trash
1162
+	 * @return string               new delete link
1163
+	 */
1164
+	public function modify_delete_post_link($delete_link, $post_id, $force_delete)
1165
+	{
1166
+		$post = get_post($post_id);
1167
+		if ( ! isset($this->_req_data['action'])
1168
+			 || (isset($this->_cpt_routes[$this->_req_data['action']])
1169
+				 && $post->post_type !== $this->_cpt_routes[$this->_req_data['action']])
1170
+		) {
1171
+			return $delete_link;
1172
+		}
1173
+		return add_query_arg(array('current_route' => 'trash'), $delete_link);
1174
+	}
1175
+
1176
+
1177
+
1178
+	/**
1179
+	 * This hooks into the wp_redirect filter and if trashed is detected, then we'll redirect to the appropriate EE
1180
+	 * route
1181
+	 *
1182
+	 * @param  string $location url
1183
+	 * @param  string $status   status
1184
+	 * @return string           url to redirect to
1185
+	 */
1186
+	public function cpt_trash_post_location_redirect($location, $status)
1187
+	{
1188
+		if (isset($this->_req_data['action']) && $this->_req_data['action'] !== 'trash' && empty($this->_req_data['post'])) {
1189
+			return $location;
1190
+		}
1191
+
1192
+		$post              = get_post($this->_req_data['post']);
1193
+		$query_args        = array('action' => 'default');
1194
+		$this->_cpt_object = get_post_type_object($post->post_type);
1195
+		EE_Error::add_success(sprintf(__('%s trashed.', 'event_espresso'), $this->_cpt_object->labels->singular_name));
1196
+		$this->_process_notices($query_args, true);
1197
+		return self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1198
+	}
1199
+
1200
+
1201
+
1202
+	/**
1203
+	 * This is the callback for the 'redirect_post_location' filter in wp-admin/post.php
1204
+	 * so that we can hijack the default redirect locations for wp custom post types
1205
+	 * that WE'RE using and send back to OUR routes.  This should only be hooked in on the right route.
1206
+	 *
1207
+	 * @param  string $location This is the incoming currently set redirect location
1208
+	 * @param  string $post_id  This is the 'ID' value of the wp_posts table
1209
+	 * @return string           the new location to redirect to
1210
+	 */
1211
+	public function cpt_post_location_redirect($location, $post_id)
1212
+	{
1213
+		//we DO have a match so let's setup the url
1214
+		//we have to get the post to determine our route
1215
+		$post       = get_post($post_id);
1216
+		$edit_route = $this->_cpt_edit_routes[$post->post_type];
1217
+		//shared query_args
1218
+		$query_args = array('action' => $edit_route, 'post' => $post_id);
1219
+		$admin_url  = $this->_admin_base_url;
1220
+		if (isset($this->_req_data['save']) || isset($this->_req_data['publish'])) {
1221
+			$status = get_post_status($post_id);
1222
+			if (isset($this->_req_data['publish'])) {
1223
+				switch ($status) {
1224
+					case 'pending':
1225
+						$message = 8;
1226
+						break;
1227
+					case 'future':
1228
+						$message = 9;
1229
+						break;
1230
+					default:
1231
+						$message = 6;
1232
+				}
1233
+			} else {
1234
+				$message = 'draft' == $status ? 10 : 1;
1235
+			}
1236
+		} else if (isset($this->_req_data['addmeta']) && $this->_req_data['addmeta']) {
1237
+			$message = 2;
1238
+			//			$append = '#postcustom';
1239
+		} else if (isset($this->_req_data['deletemeta']) && $this->_req_data['deletemeta']) {
1240
+			$message = 3;
1241
+			//			$append = '#postcustom';
1242
+		} elseif ($this->_req_data['action'] == 'post-quickpress-save-cont') {
1243
+			$message = 7;
1244
+		} else {
1245
+			$message = 4;
1246
+		}
1247
+		//change the message if the post type is not viewable on the frontend
1248
+		$this->_cpt_object = get_post_type_object($post->post_type);
1249
+		$message           = $message === 1 && ! $this->_cpt_object->publicly_queryable ? 4 : $message;
1250
+		$query_args = array_merge(array('message' => $message), $query_args);
1251
+		$this->_process_notices($query_args, true);
1252
+		return self::add_query_args_and_nonce($query_args, $admin_url);
1253
+	}
1254
+
1255
+
1256
+
1257
+	/**
1258
+	 * This method is called to inject nav tabs on core WP cpt pages
1259
+	 *
1260
+	 * @access public
1261
+	 * @return string html
1262
+	 */
1263
+	public function inject_nav_tabs()
1264
+	{
1265
+		//can we hijack and insert the nav_tabs?
1266
+		$nav_tabs = $this->_get_main_nav_tabs();
1267
+		//first close off existing form tag
1268
+		$html = '>';
1269
+		$html .= $nav_tabs;
1270
+		//now let's handle the remaining tag ( missing ">" is CORRECT )
1271
+		$html .= '<span></span';
1272
+		echo $html;
1273
+	}
1274
+
1275
+
1276
+
1277
+	/**
1278
+	 * This just sets up the post update messages when an update form is loaded
1279
+	 *
1280
+	 * @access public
1281
+	 * @param  array $messages the original messages array
1282
+	 * @return array           the new messages array
1283
+	 */
1284
+	public function post_update_messages($messages)
1285
+	{
1286
+		global $post;
1287
+		$id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1288
+		$id = empty($id) && is_object($post) ? $post->ID : null;
1289
+		//		$post_type = $post ? $post->post_type : false;
1290
+		/*$current_route = isset($this->_req_data['current_route']) ? $this->_req_data['current_route'] : 'shouldneverwork';
1291 1291
 
1292 1292
         $route_to_check = $post_type && isset( $this->_cpt_routes[$current_route]) ? $this->_cpt_routes[$current_route] : '';/**/
1293
-        $messages[$post->post_type] = array(
1294
-            0 => '', //Unused. Messages start at index 1.
1295
-            1 => sprintf(
1296
-                __('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1297
-                $this->_cpt_object->labels->singular_name,
1298
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1299
-                '</a>'
1300
-            ),
1301
-            2 => __('Custom field updated'),
1302
-            3 => __('Custom field deleted.'),
1303
-            4 => sprintf(__('%1$s updated.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1304
-            5 => isset($_GET['revision']) ? sprintf(__('%s restored to revision from %s', 'event_espresso'),
1305
-                $this->_cpt_object->labels->singular_name, wp_post_revision_title((int)$_GET['revision'], false))
1306
-                : false,
1307
-            6 => sprintf(
1308
-                __('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1309
-                $this->_cpt_object->labels->singular_name,
1310
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1311
-                '</a>'
1312
-            ),
1313
-            7 => sprintf(__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1314
-            8 => sprintf(
1315
-                __('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1316
-                $this->_cpt_object->labels->singular_name,
1317
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1318
-                '</a>'
1319
-            ),
1320
-            9 => sprintf(
1321
-                __('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1322
-                $this->_cpt_object->labels->singular_name,
1323
-                '<strong>' . date_i18n(__('M j, Y @ G:i'), strtotime($post->post_date)) . '</strong>',
1324
-                '<a target="_blank" href="' . esc_url(get_permalink($id)),
1325
-                '</a>'
1326
-            ),
1327
-            10 => sprintf(
1328
-                __('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1329
-                $this->_cpt_object->labels->singular_name,
1330
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1331
-                '</a>'
1332
-            ),
1333
-        );
1334
-        return $messages;
1335
-    }
1336
-
1337
-
1338
-
1339
-    /**
1340
-     * default method for the 'create_new' route for cpt admin pages.
1341
-     * For reference what to include in here, see wp-admin/post-new.php
1342
-     *
1343
-     * @access  protected
1344
-     * @return string template for add new cpt form
1345
-     */
1346
-    protected function _create_new_cpt_item()
1347
-    {
1348
-        global $post, $title, $is_IE, $post_type, $post_type_object;
1349
-        $post_type        = $this->_cpt_routes[$this->_req_action];
1350
-        $post_type_object = $this->_cpt_object;
1351
-        $title            = $post_type_object->labels->add_new_item;
1352
-        $editing          = true;
1353
-        wp_enqueue_script('autosave');
1354
-        $post    = $post = get_default_post_to_edit($this->_cpt_routes[$this->_req_action], true);
1355
-        $post_ID = $post->ID;
1356
-        $is_IE   = $is_IE;
1357
-        add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1358
-        //modify the default editor title field with default title.
1359
-        add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1360
-        include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1361
-    }
1362
-
1363
-
1364
-
1365
-    public function add_new_admin_page_global()
1366
-    {
1367
-        $admin_page = ! empty($this->_req_data['post']) ? 'post-php' : 'post-new-php';
1368
-        ?>
1293
+		$messages[$post->post_type] = array(
1294
+			0 => '', //Unused. Messages start at index 1.
1295
+			1 => sprintf(
1296
+				__('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1297
+				$this->_cpt_object->labels->singular_name,
1298
+				'<a href="' . esc_url(get_permalink($id)) . '">',
1299
+				'</a>'
1300
+			),
1301
+			2 => __('Custom field updated'),
1302
+			3 => __('Custom field deleted.'),
1303
+			4 => sprintf(__('%1$s updated.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1304
+			5 => isset($_GET['revision']) ? sprintf(__('%s restored to revision from %s', 'event_espresso'),
1305
+				$this->_cpt_object->labels->singular_name, wp_post_revision_title((int)$_GET['revision'], false))
1306
+				: false,
1307
+			6 => sprintf(
1308
+				__('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1309
+				$this->_cpt_object->labels->singular_name,
1310
+				'<a href="' . esc_url(get_permalink($id)) . '">',
1311
+				'</a>'
1312
+			),
1313
+			7 => sprintf(__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1314
+			8 => sprintf(
1315
+				__('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1316
+				$this->_cpt_object->labels->singular_name,
1317
+				'<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1318
+				'</a>'
1319
+			),
1320
+			9 => sprintf(
1321
+				__('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1322
+				$this->_cpt_object->labels->singular_name,
1323
+				'<strong>' . date_i18n(__('M j, Y @ G:i'), strtotime($post->post_date)) . '</strong>',
1324
+				'<a target="_blank" href="' . esc_url(get_permalink($id)),
1325
+				'</a>'
1326
+			),
1327
+			10 => sprintf(
1328
+				__('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1329
+				$this->_cpt_object->labels->singular_name,
1330
+				'<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1331
+				'</a>'
1332
+			),
1333
+		);
1334
+		return $messages;
1335
+	}
1336
+
1337
+
1338
+
1339
+	/**
1340
+	 * default method for the 'create_new' route for cpt admin pages.
1341
+	 * For reference what to include in here, see wp-admin/post-new.php
1342
+	 *
1343
+	 * @access  protected
1344
+	 * @return string template for add new cpt form
1345
+	 */
1346
+	protected function _create_new_cpt_item()
1347
+	{
1348
+		global $post, $title, $is_IE, $post_type, $post_type_object;
1349
+		$post_type        = $this->_cpt_routes[$this->_req_action];
1350
+		$post_type_object = $this->_cpt_object;
1351
+		$title            = $post_type_object->labels->add_new_item;
1352
+		$editing          = true;
1353
+		wp_enqueue_script('autosave');
1354
+		$post    = $post = get_default_post_to_edit($this->_cpt_routes[$this->_req_action], true);
1355
+		$post_ID = $post->ID;
1356
+		$is_IE   = $is_IE;
1357
+		add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1358
+		//modify the default editor title field with default title.
1359
+		add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1360
+		include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1361
+	}
1362
+
1363
+
1364
+
1365
+	public function add_new_admin_page_global()
1366
+	{
1367
+		$admin_page = ! empty($this->_req_data['post']) ? 'post-php' : 'post-new-php';
1368
+		?>
1369 1369
         <script type="text/javascript">
1370 1370
             adminpage = '<?php echo $admin_page; ?>';
1371 1371
         </script>
1372 1372
         <?php
1373
-    }
1374
-
1375
-
1376
-
1377
-    /**
1378
-     * default method for the 'edit' route for cpt admin pages
1379
-     * For reference on what to put in here, refer to wp-admin/post.php
1380
-     *
1381
-     * @access protected
1382
-     * @return string   template for edit cpt form
1383
-     */
1384
-    protected function _edit_cpt_item()
1385
-    {
1386
-        global $post, $title, $is_IE, $post_type, $post_type_object;
1387
-        $post_id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1388
-        $post = ! empty($post_id) ? get_post($post_id, OBJECT, 'edit') : null;
1389
-        if (empty ($post)) {
1390
-            wp_die(__('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?'));
1391
-        }
1392
-        if ( ! empty($_GET['get-post-lock'])) {
1393
-            wp_set_post_lock($post_id);
1394
-            wp_redirect(get_edit_post_link($post_id, 'url'));
1395
-            exit();
1396
-        }
1397
-
1398
-        // template vars
1399
-        $editing          = true;
1400
-        $post_ID          = $post_id;
1401
-        $post_type        = $this->_cpt_routes[$this->_req_action];
1402
-        $post_type_object = $this->_cpt_object;
1403
-
1404
-        if ( ! wp_check_post_lock($post->ID)) {
1405
-            $active_post_lock = wp_set_post_lock($post->ID);
1406
-            //wp_enqueue_script('autosave');
1407
-        }
1408
-        $title = $this->_cpt_object->labels->edit_item;
1409
-        add_action('admin_footer', '_admin_notice_post_locked');
1410
-        if (isset($this->_cpt_routes[$this->_req_data['action']])
1411
-            && ! isset($this->_labels['hide_add_button_on_cpt_route'][$this->_req_data['action']])
1412
-        ) {
1413
-            $create_new_action = apply_filters('FHEE__EE_Admin_Page_CPT___edit_cpt_item__create_new_action',
1414
-                'create_new', $this);
1415
-            $post_new_file = EE_Admin_Page::add_query_args_and_nonce(array(
1416
-                'action' => $create_new_action,
1417
-                'page'   => $this->page_slug,
1418
-            ), 'admin.php');
1419
-        }
1420
-        if (post_type_supports($this->_cpt_routes[$this->_req_action], 'comments')) {
1421
-            wp_enqueue_script('admin-comments');
1422
-            enqueue_comment_hotkeys_js();
1423
-        }
1424
-        add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1425
-        //modify the default editor title field with default title.
1426
-        add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1427
-        include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1428
-    }
1429
-
1430
-
1431
-
1432
-    /**
1433
-     * some getters
1434
-     */
1435
-    /**
1436
-     * This returns the protected _cpt_model_obj property
1437
-     *
1438
-     * @return EE_CPT_Base
1439
-     */
1440
-    public function get_cpt_model_obj()
1441
-    {
1442
-        return $this->_cpt_model_obj;
1443
-    }
1373
+	}
1374
+
1375
+
1376
+
1377
+	/**
1378
+	 * default method for the 'edit' route for cpt admin pages
1379
+	 * For reference on what to put in here, refer to wp-admin/post.php
1380
+	 *
1381
+	 * @access protected
1382
+	 * @return string   template for edit cpt form
1383
+	 */
1384
+	protected function _edit_cpt_item()
1385
+	{
1386
+		global $post, $title, $is_IE, $post_type, $post_type_object;
1387
+		$post_id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1388
+		$post = ! empty($post_id) ? get_post($post_id, OBJECT, 'edit') : null;
1389
+		if (empty ($post)) {
1390
+			wp_die(__('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?'));
1391
+		}
1392
+		if ( ! empty($_GET['get-post-lock'])) {
1393
+			wp_set_post_lock($post_id);
1394
+			wp_redirect(get_edit_post_link($post_id, 'url'));
1395
+			exit();
1396
+		}
1397
+
1398
+		// template vars
1399
+		$editing          = true;
1400
+		$post_ID          = $post_id;
1401
+		$post_type        = $this->_cpt_routes[$this->_req_action];
1402
+		$post_type_object = $this->_cpt_object;
1403
+
1404
+		if ( ! wp_check_post_lock($post->ID)) {
1405
+			$active_post_lock = wp_set_post_lock($post->ID);
1406
+			//wp_enqueue_script('autosave');
1407
+		}
1408
+		$title = $this->_cpt_object->labels->edit_item;
1409
+		add_action('admin_footer', '_admin_notice_post_locked');
1410
+		if (isset($this->_cpt_routes[$this->_req_data['action']])
1411
+			&& ! isset($this->_labels['hide_add_button_on_cpt_route'][$this->_req_data['action']])
1412
+		) {
1413
+			$create_new_action = apply_filters('FHEE__EE_Admin_Page_CPT___edit_cpt_item__create_new_action',
1414
+				'create_new', $this);
1415
+			$post_new_file = EE_Admin_Page::add_query_args_and_nonce(array(
1416
+				'action' => $create_new_action,
1417
+				'page'   => $this->page_slug,
1418
+			), 'admin.php');
1419
+		}
1420
+		if (post_type_supports($this->_cpt_routes[$this->_req_action], 'comments')) {
1421
+			wp_enqueue_script('admin-comments');
1422
+			enqueue_comment_hotkeys_js();
1423
+		}
1424
+		add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1425
+		//modify the default editor title field with default title.
1426
+		add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1427
+		include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1428
+	}
1429
+
1430
+
1431
+
1432
+	/**
1433
+	 * some getters
1434
+	 */
1435
+	/**
1436
+	 * This returns the protected _cpt_model_obj property
1437
+	 *
1438
+	 * @return EE_CPT_Base
1439
+	 */
1440
+	public function get_cpt_model_obj()
1441
+	{
1442
+		return $this->_cpt_model_obj;
1443
+	}
1444 1444
 
1445 1445
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
      */
236 236
     protected function _register_autosave_containers($ids)
237 237
     {
238
-        $this->_autosave_containers = array_merge($this->_autosave_fields, (array)$ids);
238
+        $this->_autosave_containers = array_merge($this->_autosave_fields, (array) $ids);
239 239
     }
240 240
 
241 241
 
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
         //filter _autosave_containers
280 280
         $containers = apply_filters('FHEE__EE_Admin_Page_CPT___load_autosave_scripts_styles__containers',
281 281
             $this->_autosave_containers, $this);
282
-        $containers = apply_filters('FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
282
+        $containers = apply_filters('FHEE__EE_Admin_Page_CPT__'.get_class($this).'___load_autosave_scripts_styles__containers',
283 283
             $containers, $this);
284 284
 
285 285
         wp_localize_script('event_editor_js', 'EE_AUTOSAVE_IDS',
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
         parent::_load_page_dependencies();
370 370
         //notice we are ALSO going to load the pagenow hook set for this route (see _before_page_setup for the reset of the pagenow global ). This is for any plugins that are doing things properly and hooking into the load page hook for core wp cpt routes.
371 371
         global $pagenow;
372
-        do_action('load-' . $pagenow);
372
+        do_action('load-'.$pagenow);
373 373
         $this->modify_current_screen();
374 374
         add_action('admin_enqueue_scripts', array($this, 'setup_autosave_hooks'), 30);
375 375
         //we route REALLY early.
@@ -400,8 +400,8 @@  discard block
 block discarded – undo
400 400
                 'admin.php?page=espresso_registrations&action=contact_list',
401 401
             ),
402 402
             1 => array(
403
-                'edit.php?post_type=' . $this->_cpt_object->name,
404
-                'admin.php?page=' . $this->_cpt_object->name,
403
+                'edit.php?post_type='.$this->_cpt_object->name,
404
+                'admin.php?page='.$this->_cpt_object->name,
405 405
             ),
406 406
         );
407 407
         foreach ($routes_to_match as $route_matches) {
@@ -429,7 +429,7 @@  discard block
 block discarded – undo
429 429
         $cpt_has_support = ! empty($cpt_args['page_templates']);
430 430
 
431 431
         //if the installed version of WP is > 4.7 we do some additional checks.
432
-        if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
432
+        if (EE_Recommended_Versions::check_wp_version('4.7', '>=')) {
433 433
             $post_templates = wp_get_theme()->get_post_templates();
434 434
             //if there are $post_templates for this cpt, then we return false for this method because
435 435
             //that means we aren't going to load our page template manager and leave that up to the native
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
         global $post;
453 453
         $template = '';
454 454
 
455
-        if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
455
+        if (EE_Recommended_Versions::check_wp_version('4.7', '>=')) {
456 456
             $page_template_count = count(get_page_templates());
457 457
         } else {
458 458
             $page_template_count = count(get_page_templates($post));
@@ -489,7 +489,7 @@  discard block
 block discarded – undo
489 489
         $post = get_post($id);
490 490
         if ('publish' != get_post_status($post)) {
491 491
             //include shims for the `get_preview_post_link` function
492
-            require_once( EE_CORE . 'wordpress-shims.php' );
492
+            require_once(EE_CORE.'wordpress-shims.php');
493 493
             $return .= '<span_id="view-post-btn"><a target="_blank" href="'
494 494
                        . get_preview_post_link($id)
495 495
                        . '" class="button button-small">'
@@ -527,7 +527,7 @@  discard block
 block discarded – undo
527 527
             $template_args['statuses']         = $statuses;
528 528
         }
529 529
 
530
-        $template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
530
+        $template = EE_ADMIN_TEMPLATE.'status_dropdown.template.php';
531 531
         EEH_Template::display_template($template, $template_args);
532 532
     }
533 533
 
@@ -572,13 +572,13 @@  discard block
 block discarded – undo
572 572
             define('DOING_AUTOSAVE', true);
573 573
         }
574 574
         //if we made it here then the nonce checked out.  Let's run our methods and actions
575
-        if (method_exists($this, '_ee_autosave_' . $this->_current_view)) {
576
-            call_user_func(array($this, '_ee_autosave_' . $this->_current_view));
575
+        if (method_exists($this, '_ee_autosave_'.$this->_current_view)) {
576
+            call_user_func(array($this, '_ee_autosave_'.$this->_current_view));
577 577
         } else {
578 578
             $this->_template_args['success'] = true;
579 579
         }
580 580
         do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
581
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
581
+        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_'.get_class($this), $this);
582 582
         //now let's return json
583 583
         $this->_return_json();
584 584
     }
@@ -971,7 +971,7 @@  discard block
 block discarded – undo
971 971
         //global action
972 972
         do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
973 973
         //class specific action so you can limit hooking into a specific page.
974
-        do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
974
+        do_action('AHEE_EE_Admin_Page_CPT_'.get_class($this).'__restore_revision', $post_id, $revision_id);
975 975
     }
976 976
 
977 977
 
@@ -1049,7 +1049,7 @@  discard block
 block discarded – undo
1049 1049
         if ( ! empty($id) && '' != get_option('permalink_structure')) {
1050 1050
             $post = get_post($id);
1051 1051
             if (isset($post->post_type) && $this->page_slug == $post->post_type) {
1052
-                $shortlink = home_url('?p=' . $post->ID);
1052
+                $shortlink = home_url('?p='.$post->ID);
1053 1053
             }
1054 1054
         }
1055 1055
         return $shortlink;
@@ -1084,11 +1084,11 @@  discard block
 block discarded – undo
1084 1084
      */
1085 1085
     public function cpt_post_form_hidden_input()
1086 1086
     {
1087
-        echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="' . $this->_admin_base_url . '" />';
1087
+        echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="'.$this->_admin_base_url.'" />';
1088 1088
         //we're also going to add the route value and the current page so we can direct autosave parsing correctly
1089 1089
         echo '<div id="ee-cpt-hidden-inputs">';
1090
-        echo '<input type="hidden" id="current_route" name="current_route" value="' . $this->_current_view . '" />';
1091
-        echo '<input type="hidden" id="current_page" name="current_page" value="' . $this->page_slug . '" />';
1090
+        echo '<input type="hidden" id="current_route" name="current_route" value="'.$this->_current_view.'" />';
1091
+        echo '<input type="hidden" id="current_page" name="current_page" value="'.$this->page_slug.'" />';
1092 1092
         echo '</div>';
1093 1093
     }
1094 1094
 
@@ -1295,39 +1295,39 @@  discard block
 block discarded – undo
1295 1295
             1 => sprintf(
1296 1296
                 __('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1297 1297
                 $this->_cpt_object->labels->singular_name,
1298
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1298
+                '<a href="'.esc_url(get_permalink($id)).'">',
1299 1299
                 '</a>'
1300 1300
             ),
1301 1301
             2 => __('Custom field updated'),
1302 1302
             3 => __('Custom field deleted.'),
1303 1303
             4 => sprintf(__('%1$s updated.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1304 1304
             5 => isset($_GET['revision']) ? sprintf(__('%s restored to revision from %s', 'event_espresso'),
1305
-                $this->_cpt_object->labels->singular_name, wp_post_revision_title((int)$_GET['revision'], false))
1305
+                $this->_cpt_object->labels->singular_name, wp_post_revision_title((int) $_GET['revision'], false))
1306 1306
                 : false,
1307 1307
             6 => sprintf(
1308 1308
                 __('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1309 1309
                 $this->_cpt_object->labels->singular_name,
1310
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1310
+                '<a href="'.esc_url(get_permalink($id)).'">',
1311 1311
                 '</a>'
1312 1312
             ),
1313 1313
             7 => sprintf(__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1314 1314
             8 => sprintf(
1315 1315
                 __('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1316 1316
                 $this->_cpt_object->labels->singular_name,
1317
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1317
+                '<a target="_blank" href="'.esc_url(add_query_arg('preview', 'true', get_permalink($id))).'">',
1318 1318
                 '</a>'
1319 1319
             ),
1320 1320
             9 => sprintf(
1321 1321
                 __('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1322 1322
                 $this->_cpt_object->labels->singular_name,
1323
-                '<strong>' . date_i18n(__('M j, Y @ G:i'), strtotime($post->post_date)) . '</strong>',
1324
-                '<a target="_blank" href="' . esc_url(get_permalink($id)),
1323
+                '<strong>'.date_i18n(__('M j, Y @ G:i'), strtotime($post->post_date)).'</strong>',
1324
+                '<a target="_blank" href="'.esc_url(get_permalink($id)),
1325 1325
                 '</a>'
1326 1326
             ),
1327 1327
             10 => sprintf(
1328 1328
                 __('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1329 1329
                 $this->_cpt_object->labels->singular_name,
1330
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1330
+                '<a target="_blank" href="'.esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1331 1331
                 '</a>'
1332 1332
             ),
1333 1333
         );
@@ -1357,7 +1357,7 @@  discard block
 block discarded – undo
1357 1357
         add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1358 1358
         //modify the default editor title field with default title.
1359 1359
         add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1360
-        include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1360
+        include_once WP_ADMIN_PATH.'edit-form-advanced.php';
1361 1361
     }
1362 1362
 
1363 1363
 
@@ -1424,7 +1424,7 @@  discard block
 block discarded – undo
1424 1424
         add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1425 1425
         //modify the default editor title field with default title.
1426 1426
         add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1427
-        include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1427
+        include_once WP_ADMIN_PATH.'edit-form-advanced.php';
1428 1428
     }
1429 1429
 
1430 1430
 
Please login to merge, or discard this patch.
form_sections/strategies/normalization/EE_Text_Normalization.strategy.php 3 patches
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -15,10 +15,10 @@  discard block
 block discarded – undo
15 15
 	 */
16 16
 	public function normalize($value_to_normalize) {
17 17
 		if(is_array($value_to_normalize)) {
18
-            return array_shift($value_to_normalize);
19
-        //consider `"null"` values to be equivalent to null.
20
-        }elseif($value_to_normalize === '' || $value_to_normalize === null) {
21
-		    return null;
18
+			return array_shift($value_to_normalize);
19
+		//consider `"null"` values to be equivalent to null.
20
+		}elseif($value_to_normalize === '' || $value_to_normalize === null) {
21
+			return null;
22 22
 		}else{
23 23
 			return $value_to_normalize;
24 24
 		}
@@ -29,10 +29,10 @@  discard block
 block discarded – undo
29 29
 	 * @return string
30 30
 	 */
31 31
 	public function unnormalize( $normalized_value ){
32
-	    //account for default "select here" option values
33
-	    if ($normalized_value === null) {
34
-	        return '';
35
-        }
32
+		//account for default "select here" option values
33
+		if ($normalized_value === null) {
34
+			return '';
35
+		}
36 36
 		return $normalized_value;
37 37
 	}
38 38
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -7,19 +7,19 @@  discard block
 block discarded – undo
7 7
  * @subpackage
8 8
  * @author				Mike Nelson
9 9
  */
10
-class EE_Text_Normalization extends EE_Normalization_Strategy_Base{
10
+class EE_Text_Normalization extends EE_Normalization_Strategy_Base {
11 11
 
12 12
 	/**
13 13
 	 * @param string $value_to_normalize
14 14
 	 * @return array|mixed|string
15 15
 	 */
16 16
 	public function normalize($value_to_normalize) {
17
-		if(is_array($value_to_normalize)) {
17
+		if (is_array($value_to_normalize)) {
18 18
             return array_shift($value_to_normalize);
19 19
         //consider `"null"` values to be equivalent to null.
20
-        }elseif($value_to_normalize === '' || $value_to_normalize === null) {
20
+        }elseif ($value_to_normalize === '' || $value_to_normalize === null) {
21 21
 		    return null;
22
-		}else{
22
+		} else {
23 23
 			return $value_to_normalize;
24 24
 		}
25 25
 	}
@@ -28,7 +28,7 @@  discard block
 block discarded – undo
28 28
 	 * @param string $normalized_value
29 29
 	 * @return string
30 30
 	 */
31
-	public function unnormalize( $normalized_value ){
31
+	public function unnormalize($normalized_value) {
32 32
 	    //account for default "select here" option values
33 33
 	    if ($normalized_value === null) {
34 34
 	        return '';
Please login to merge, or discard this patch.
Braces   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -17,9 +17,9 @@
 block discarded – undo
17 17
 		if(is_array($value_to_normalize)) {
18 18
             return array_shift($value_to_normalize);
19 19
         //consider `"null"` values to be equivalent to null.
20
-        }elseif($value_to_normalize === '' || $value_to_normalize === null) {
20
+        } elseif($value_to_normalize === '' || $value_to_normalize === null) {
21 21
 		    return null;
22
-		}else{
22
+		} else{
23 23
 			return $value_to_normalize;
24 24
 		}
25 25
 	}
Please login to merge, or discard this patch.
core/helpers/EEH_File.helper.php 4 patches
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -325,8 +325,8 @@
 block discarded – undo
325 325
 		//eg if given "/var/something/somewhere/", we want to get "somewhere"'s
326 326
 		//parent folder, "/var/something/"
327 327
 		$ds = strlen($file_or_folder_path) > 1
328
-            ? strrpos($file_or_folder_path, DS, -2)
329
-            : strlen($file_or_folder_path);
328
+			? strrpos($file_or_folder_path, DS, -2)
329
+			: strlen($file_or_folder_path);
330 330
 		return substr($file_or_folder_path, 0, $ds + 1);
331 331
 	}
332 332
 
Please login to merge, or discard this patch.
Spacing   +176 added lines, -176 removed lines patch added patch discarded remove patch
@@ -12,8 +12,8 @@  discard block
 block discarded – undo
12 12
  * @ version		 	4.0
13 13
  *
14 14
  */
15
-require_once( EE_HELPERS . 'EEH_Base.helper.php' );
16
-require_once( EE_INTERFACES . 'EEI_Interfaces.php' );
15
+require_once(EE_HELPERS.'EEH_Base.helper.php');
16
+require_once(EE_INTERFACES.'EEI_Interfaces.php');
17 17
 /**
18 18
  *
19 19
  * Class EEH_File
@@ -52,30 +52,30 @@  discard block
 block discarded – undo
52 52
 	 * @throws EE_Error if filesystem credentials are required
53 53
 	 * @return WP_Filesystem_Base
54 54
 	 */
55
-	private static function _get_wp_filesystem( $filepath = null) {
56
-		if( apply_filters(
55
+	private static function _get_wp_filesystem($filepath = null) {
56
+		if (apply_filters(
57 57
 				'FHEE__EEH_File___get_wp_filesystem__allow_using_filesystem_direct',
58
-				$filepath && EEH_File::is_in_uploads_folder( $filepath ),
59
-				$filepath ) ) {
60
-			if( ! EEH_File::$_wp_filesystem_direct instanceof WP_Filesystem_Direct ) {
61
-				require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php');
58
+				$filepath && EEH_File::is_in_uploads_folder($filepath),
59
+				$filepath )) {
60
+			if ( ! EEH_File::$_wp_filesystem_direct instanceof WP_Filesystem_Direct) {
61
+				require_once(ABSPATH.'wp-admin/includes/class-wp-filesystem-base.php');
62 62
 				$method = 'direct';
63
-				$wp_filesystem_direct_file = apply_filters( 'filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method );
63
+				$wp_filesystem_direct_file = apply_filters('filesystem_method_file', ABSPATH.'wp-admin/includes/class-wp-filesystem-'.$method.'.php', $method);
64 64
 				//check constants defined, just like in wp-admin/includes/file.php's WP_Filesystem()
65
-				if ( ! defined('FS_CHMOD_DIR') ) {
66
-					define('FS_CHMOD_DIR', ( fileperms( ABSPATH ) & 0777 | 0755 ) );
65
+				if ( ! defined('FS_CHMOD_DIR')) {
66
+					define('FS_CHMOD_DIR', (fileperms(ABSPATH) & 0777 | 0755));
67 67
 				}
68
-				if ( ! defined('FS_CHMOD_FILE') ) {
69
-					define('FS_CHMOD_FILE', ( fileperms( ABSPATH . 'index.php' ) & 0777 | 0644 ) );
68
+				if ( ! defined('FS_CHMOD_FILE')) {
69
+					define('FS_CHMOD_FILE', (fileperms(ABSPATH.'index.php') & 0777 | 0644));
70 70
 				}
71
-				require_once( $wp_filesystem_direct_file );
72
-				EEH_File::$_wp_filesystem_direct = new WP_Filesystem_Direct( array() );
71
+				require_once($wp_filesystem_direct_file);
72
+				EEH_File::$_wp_filesystem_direct = new WP_Filesystem_Direct(array());
73 73
 			}
74 74
 			return EEH_File::$_wp_filesystem_direct;
75 75
 		}
76 76
 		global $wp_filesystem;
77 77
 		// no filesystem setup ???
78
-		if ( ! $wp_filesystem instanceof WP_Filesystem_Base ) {
78
+		if ( ! $wp_filesystem instanceof WP_Filesystem_Base) {
79 79
 			// if some eager beaver's just trying to get in there too early...
80 80
 			// let them do it, because we are one of those eager beavers! :P
81 81
 			/**
@@ -88,34 +88,34 @@  discard block
 block discarded – undo
88 88
 			 * and there may be troubles if the WP files are owned by a different user
89 89
 			 * than the server user. But both of these issues should exist in 4.4 and earlier too
90 90
 			 */
91
-			if ( FALSE && ! did_action( 'wp_loaded' )) {
91
+			if (FALSE && ! did_action('wp_loaded')) {
92 92
 				$msg = __('An attempt to access and/or write to a file on the server could not be completed due to a lack of sufficient credentials.', 'event_espresso');
93
-				if ( WP_DEBUG ) {
94
-					$msg .= '<br />' .  __('The WP Filesystem can not be accessed until after the "wp_loaded" hook has run, so it\'s best not to attempt access until the "admin_init" hookpoint.', 'event_espresso');
93
+				if (WP_DEBUG) {
94
+					$msg .= '<br />'.__('The WP Filesystem can not be accessed until after the "wp_loaded" hook has run, so it\'s best not to attempt access until the "admin_init" hookpoint.', 'event_espresso');
95 95
 				}
96
-				throw new EE_Error( $msg );
96
+				throw new EE_Error($msg);
97 97
 			} else {
98 98
 				// should be loaded if we are past the wp_loaded hook...
99
-				if ( ! function_exists( 'WP_Filesystem' )) {
100
-					require_once( ABSPATH . 'wp-admin/includes/file.php' );
101
-					require_once( ABSPATH . 'wp-admin/includes/template.php' );
99
+				if ( ! function_exists('WP_Filesystem')) {
100
+					require_once(ABSPATH.'wp-admin/includes/file.php');
101
+					require_once(ABSPATH.'wp-admin/includes/template.php');
102 102
 				}
103 103
 				// turn on output buffering so that we can capture the credentials form
104 104
 				ob_start();
105
-				$credentials = request_filesystem_credentials( '' );
105
+				$credentials = request_filesystem_credentials('');
106 106
 				// store credentials form for the time being
107 107
 				EEH_File::$_credentials_form = ob_get_clean();
108 108
 				// basically check for direct or previously configured access
109
-				if ( ! WP_Filesystem( $credentials ) ) {
109
+				if ( ! WP_Filesystem($credentials)) {
110 110
 					// if credentials do NOT exist
111
-					if ( $credentials === FALSE ) {
112
-						add_action( 'admin_notices', array( 'EEH_File', 'display_request_filesystem_credentials_form' ), 999 );
113
-						throw new EE_Error( __('An attempt to access and/or write to a file on the server could not be completed due to a lack of sufficient credentials.', 'event_espresso'));
114
-					} elseif( is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->get_error_code() ) {
115
-						add_action( 'admin_notices', array( 'EEH_File', 'display_request_filesystem_credentials_form' ), 999 );
111
+					if ($credentials === FALSE) {
112
+						add_action('admin_notices', array('EEH_File', 'display_request_filesystem_credentials_form'), 999);
113
+						throw new EE_Error(__('An attempt to access and/or write to a file on the server could not be completed due to a lack of sufficient credentials.', 'event_espresso'));
114
+					} elseif (is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code()) {
115
+						add_action('admin_notices', array('EEH_File', 'display_request_filesystem_credentials_form'), 999);
116 116
 						throw new EE_Error(
117 117
 								sprintf(
118
-										__( 'WP Filesystem Error: $1%s', 'event_espresso' ),
118
+										__('WP Filesystem Error: $1%s', 'event_espresso'),
119 119
 										$wp_filesystem->errors->get_error_message() ) );
120 120
 					}
121 121
 				}
@@ -128,8 +128,8 @@  discard block
 block discarded – undo
128 128
 	 * display_request_filesystem_credentials_form
129 129
 	 */
130 130
 	public static function display_request_filesystem_credentials_form() {
131
-		if ( ! empty( EEH_File::$_credentials_form )) {
132
-			echo '<div class="updated espresso-notices-attention"><p>' . EEH_File::$_credentials_form . '</p></div>';
131
+		if ( ! empty(EEH_File::$_credentials_form)) {
132
+			echo '<div class="updated espresso-notices-attention"><p>'.EEH_File::$_credentials_form.'</p></div>';
133 133
 		}
134 134
 	}
135 135
 
@@ -147,29 +147,29 @@  discard block
 block discarded – undo
147 147
 	 * @throws EE_Error if filesystem credentials are required
148 148
 	 * @return bool
149 149
 	 */
150
-	public static function verify_filepath_and_permissions( $full_file_path = '', $file_name = '', $file_ext = '', $type_of_file = '' ) {
150
+	public static function verify_filepath_and_permissions($full_file_path = '', $file_name = '', $file_ext = '', $type_of_file = '') {
151 151
 		// load WP_Filesystem and set file permissions
152
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $full_file_path );
153
-		$full_file_path = EEH_File::standardise_directory_separators( $full_file_path );
154
-		if ( ! $wp_filesystem->is_readable( EEH_File::convert_local_filepath_to_remote_filepath( $full_file_path ) )) {
155
-			$file_name = ! empty( $type_of_file ) ? $file_name . ' ' . $type_of_file : $file_name;
156
-			$file_name .= ! empty( $file_ext ) ? ' file' : ' folder';
152
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
153
+		$full_file_path = EEH_File::standardise_directory_separators($full_file_path);
154
+		if ( ! $wp_filesystem->is_readable(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path))) {
155
+			$file_name = ! empty($type_of_file) ? $file_name.' '.$type_of_file : $file_name;
156
+			$file_name .= ! empty($file_ext) ? ' file' : ' folder';
157 157
 			$msg = sprintf(
158
-				__( 'The requested %1$s could not be found or is not readable, possibly due to an incorrect filepath, or incorrect file permissions.%2$s', 'event_espresso' ),
158
+				__('The requested %1$s could not be found or is not readable, possibly due to an incorrect filepath, or incorrect file permissions.%2$s', 'event_espresso'),
159 159
 				$file_name,
160 160
 				'<br />'
161 161
 			);
162
-			if ( EEH_File::exists( $full_file_path )) {
163
-				$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $full_file_path, $type_of_file );
162
+			if (EEH_File::exists($full_file_path)) {
163
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path, $type_of_file);
164 164
 			} else {
165 165
 				// no file permissions means the file was not found
166 166
 				$msg .= sprintf(
167
-					__( 'Please ensure the following path is correct: "%s".', 'event_espresso' ),
167
+					__('Please ensure the following path is correct: "%s".', 'event_espresso'),
168 168
 					$full_file_path
169 169
 				);
170 170
 			}
171
-			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
172
-				throw new EE_Error( $msg . '||' . $msg );
171
+			if (defined('WP_DEBUG') && WP_DEBUG) {
172
+				throw new EE_Error($msg.'||'.$msg);
173 173
 			}
174 174
 			return FALSE;
175 175
 		}
@@ -187,24 +187,24 @@  discard block
 block discarded – undo
187 187
 	 * @throws EE_Error if filesystem credentials are required
188 188
 	 * @return string
189 189
 	 */
190
-	private static function _permissions_error_for_unreadable_filepath( $full_file_path = '', $type_of_file = '' ){
190
+	private static function _permissions_error_for_unreadable_filepath($full_file_path = '', $type_of_file = '') {
191 191
 		// load WP_Filesystem and set file permissions
192
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $full_file_path );
192
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
193 193
 		// check file permissions
194
-		$perms = $wp_filesystem->getchmod( EEH_File::convert_local_filepath_to_remote_filepath( $full_file_path ) );
195
-		if ( $perms ) {
194
+		$perms = $wp_filesystem->getchmod(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path));
195
+		if ($perms) {
196 196
 			// file permissions exist, but way be set incorrectly
197
-			$type_of_file = ! empty( $type_of_file ) ? $type_of_file . ' ' : '';
198
-			$type_of_file .= ! empty( $type_of_file ) ? 'file' : 'folder';
197
+			$type_of_file = ! empty($type_of_file) ? $type_of_file.' ' : '';
198
+			$type_of_file .= ! empty($type_of_file) ? 'file' : 'folder';
199 199
 			return sprintf(
200
-				__( 'File permissions for the requested %1$s are currently set at "%2$s". The recommended permissions are 644 for files and 755 for folders.', 'event_espresso' ),
200
+				__('File permissions for the requested %1$s are currently set at "%2$s". The recommended permissions are 644 for files and 755 for folders.', 'event_espresso'),
201 201
 				$type_of_file,
202 202
 				$perms
203 203
 			);
204 204
 		} else {
205 205
 			// file exists but file permissions could not be read ?!?!
206 206
 			return sprintf(
207
-				__( 'Please ensure that the server and/or PHP configuration allows the current process to access the following file: "%s".', 'event_espresso' ),
207
+				__('Please ensure that the server and/or PHP configuration allows the current process to access the following file: "%s".', 'event_espresso'),
208 208
 				$full_file_path
209 209
 			);
210 210
 		}
@@ -222,35 +222,35 @@  discard block
 block discarded – undo
222 222
 	 * can't write to it
223 223
 	 * @return bool false if folder isn't writable; true if it exists and is writeable,
224 224
 	 */
225
-	public static function ensure_folder_exists_and_is_writable( $folder = '' ){
226
-		if ( empty( $folder )) {
225
+	public static function ensure_folder_exists_and_is_writable($folder = '') {
226
+		if (empty($folder)) {
227 227
 			return false;
228 228
 		}
229 229
 		// remove ending DS
230
-		$folder = EEH_File::standardise_directory_separators( rtrim( $folder, '/\\' ));
231
-		$parent_folder = EEH_File::get_parent_folder( $folder );
230
+		$folder = EEH_File::standardise_directory_separators(rtrim($folder, '/\\'));
231
+		$parent_folder = EEH_File::get_parent_folder($folder);
232 232
 		// add DS to folder
233
-		$folder = EEH_File::end_with_directory_separator( $folder );
234
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $folder );
235
-		if ( ! $wp_filesystem->is_dir( EEH_File::convert_local_filepath_to_remote_filepath( $folder ) ) ) {
233
+		$folder = EEH_File::end_with_directory_separator($folder);
234
+		$wp_filesystem = EEH_File::_get_wp_filesystem($folder);
235
+		if ( ! $wp_filesystem->is_dir(EEH_File::convert_local_filepath_to_remote_filepath($folder))) {
236 236
 			//ok so it doesn't exist. Does its parent? Can we write to it?
237
-			if(	! EEH_File::ensure_folder_exists_and_is_writable( $parent_folder ) ) {
237
+			if ( ! EEH_File::ensure_folder_exists_and_is_writable($parent_folder)) {
238 238
 				return false;
239 239
 			}
240
-			if ( ! EEH_File::verify_is_writable( $parent_folder, 'folder' )) {
240
+			if ( ! EEH_File::verify_is_writable($parent_folder, 'folder')) {
241 241
 				return false;
242 242
 			} else {
243
-				if ( ! $wp_filesystem->mkdir( EEH_File::convert_local_filepath_to_remote_filepath(  $folder ) ) ) {
244
-					if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
245
-						$msg = sprintf( __( '"%s" could not be created.', 'event_espresso' ), $folder );
246
-						$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $folder );
247
-						throw new EE_Error( $msg );
243
+				if ( ! $wp_filesystem->mkdir(EEH_File::convert_local_filepath_to_remote_filepath($folder))) {
244
+					if (defined('WP_DEBUG') && WP_DEBUG) {
245
+						$msg = sprintf(__('"%s" could not be created.', 'event_espresso'), $folder);
246
+						$msg .= EEH_File::_permissions_error_for_unreadable_filepath($folder);
247
+						throw new EE_Error($msg);
248 248
 					}
249 249
 					return false;
250 250
 				}
251
-				EEH_File::add_index_file( $folder );
251
+				EEH_File::add_index_file($folder);
252 252
 			}
253
-		} elseif ( ! EEH_File::verify_is_writable( $folder, 'folder' )) {
253
+		} elseif ( ! EEH_File::verify_is_writable($folder, 'folder')) {
254 254
 			return false;
255 255
 		}
256 256
 		return true;
@@ -265,15 +265,15 @@  discard block
 block discarded – undo
265 265
 	 * @throws EE_Error if filesystem credentials are required
266 266
 	 * @return bool
267 267
 	 */
268
-	public static function verify_is_writable( $full_path = '', $file_or_folder = 'folder' ){
268
+	public static function verify_is_writable($full_path = '', $file_or_folder = 'folder') {
269 269
 		// load WP_Filesystem and set file permissions
270
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $full_path );
271
-		$full_path = EEH_File::standardise_directory_separators( $full_path );
272
-		if ( ! $wp_filesystem->is_writable( EEH_File::convert_local_filepath_to_remote_filepath( $full_path ) ) ) {
273
-			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
274
-				$msg = sprintf( __( 'The "%1$s" %2$s is not writable.', 'event_espresso' ), $full_path, $file_or_folder );
275
-				$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $full_path );
276
-				throw new EE_Error( $msg );
270
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_path);
271
+		$full_path = EEH_File::standardise_directory_separators($full_path);
272
+		if ( ! $wp_filesystem->is_writable(EEH_File::convert_local_filepath_to_remote_filepath($full_path))) {
273
+			if (defined('WP_DEBUG') && WP_DEBUG) {
274
+				$msg = sprintf(__('The "%1$s" %2$s is not writable.', 'event_espresso'), $full_path, $file_or_folder);
275
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_path);
276
+				throw new EE_Error($msg);
277 277
 			}
278 278
 			return FALSE;
279 279
 		}
@@ -290,25 +290,25 @@  discard block
 block discarded – undo
290 290
 	 * @throws EE_Error if filesystem credentials are required
291 291
 	 * @return bool
292 292
 	 */
293
-	public static function ensure_file_exists_and_is_writable( $full_file_path = '' ) {
293
+	public static function ensure_file_exists_and_is_writable($full_file_path = '') {
294 294
 		// load WP_Filesystem and set file permissions
295
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $full_file_path );
296
-		$full_file_path = EEH_File::standardise_directory_separators( $full_file_path );
297
-		$parent_folder = EEH_File::get_parent_folder( $full_file_path );
298
-		if ( ! EEH_File::exists( $full_file_path )) {
299
-			if( ! EEH_File::ensure_folder_exists_and_is_writable( $parent_folder ) ) {
295
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
296
+		$full_file_path = EEH_File::standardise_directory_separators($full_file_path);
297
+		$parent_folder = EEH_File::get_parent_folder($full_file_path);
298
+		if ( ! EEH_File::exists($full_file_path)) {
299
+			if ( ! EEH_File::ensure_folder_exists_and_is_writable($parent_folder)) {
300 300
 				return false;
301 301
 			}
302
-			if ( ! $wp_filesystem->touch( EEH_File::convert_local_filepath_to_remote_filepath( $full_file_path ) ) ) {
303
-				if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
304
-					$msg = sprintf( __( 'The "%s" file could not be created.', 'event_espresso' ), $full_file_path );
305
-					$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $full_file_path );
306
-					throw new EE_Error( $msg );
302
+			if ( ! $wp_filesystem->touch(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path))) {
303
+				if (defined('WP_DEBUG') && WP_DEBUG) {
304
+					$msg = sprintf(__('The "%s" file could not be created.', 'event_espresso'), $full_file_path);
305
+					$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path);
306
+					throw new EE_Error($msg);
307 307
 				}
308 308
 				return false;
309 309
 			}
310 310
 		}
311
-		if ( ! EEH_File::verify_is_writable( $full_file_path, 'file' )) {
311
+		if ( ! EEH_File::verify_is_writable($full_file_path, 'file')) {
312 312
 			return false;
313 313
 		}
314 314
 		return true;
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
 	 * @param string $file_or_folder_path
321 321
 	 * @return string parent folder, ENDING with a directory separator
322 322
 	 */
323
-	public static function get_parent_folder( $file_or_folder_path ) {
323
+	public static function get_parent_folder($file_or_folder_path) {
324 324
 		//find the last DS, ignoring a DS on the very end
325 325
 		//eg if given "/var/something/somewhere/", we want to get "somewhere"'s
326 326
 		//parent folder, "/var/something/"
@@ -342,12 +342,12 @@  discard block
 block discarded – undo
342 342
 	 * @throws EE_Error if filesystem credentials are required
343 343
 	 * @return string
344 344
 	 */
345
-	public static function get_file_contents( $full_file_path = '' ){
346
-		$full_file_path = EEH_File::standardise_directory_separators( $full_file_path );
347
-		if ( EEH_File::verify_filepath_and_permissions( $full_file_path, EEH_File::get_filename_from_filepath( $full_file_path ) , EEH_File::get_file_extension( $full_file_path ))) {
345
+	public static function get_file_contents($full_file_path = '') {
346
+		$full_file_path = EEH_File::standardise_directory_separators($full_file_path);
347
+		if (EEH_File::verify_filepath_and_permissions($full_file_path, EEH_File::get_filename_from_filepath($full_file_path), EEH_File::get_file_extension($full_file_path))) {
348 348
 			// load WP_Filesystem and set file permissions
349
-			$wp_filesystem = EEH_File::_get_wp_filesystem( $full_file_path );
350
-			return $wp_filesystem->get_contents(EEH_File::convert_local_filepath_to_remote_filepath( $full_file_path ) );
349
+			$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
350
+			return $wp_filesystem->get_contents(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path));
351 351
 		}
352 352
 		return '';
353 353
 	}
@@ -362,26 +362,26 @@  discard block
 block discarded – undo
362 362
 	 * @throws EE_Error if filesystem credentials are required
363 363
 	 * @return bool
364 364
 	 */
365
-	public static function write_to_file( $full_file_path = '', $file_contents = '', $file_type = '' ){
366
-		$full_file_path = EEH_File::standardise_directory_separators( $full_file_path );
367
-		$file_type = ! empty( $file_type ) ? rtrim( $file_type, ' ' ) . ' ' : '';
368
-		$folder = EEH_File::remove_filename_from_filepath( $full_file_path );
369
-		if ( ! EEH_File::verify_is_writable( $folder, 'folder' )) {
370
-			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
371
-				$msg = sprintf( __( 'The %1$sfile located at "%2$s" is not writable.', 'event_espresso' ), $file_type, $full_file_path );
372
-				$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $full_file_path );
373
-				throw new EE_Error( $msg );
365
+	public static function write_to_file($full_file_path = '', $file_contents = '', $file_type = '') {
366
+		$full_file_path = EEH_File::standardise_directory_separators($full_file_path);
367
+		$file_type = ! empty($file_type) ? rtrim($file_type, ' ').' ' : '';
368
+		$folder = EEH_File::remove_filename_from_filepath($full_file_path);
369
+		if ( ! EEH_File::verify_is_writable($folder, 'folder')) {
370
+			if (defined('WP_DEBUG') && WP_DEBUG) {
371
+				$msg = sprintf(__('The %1$sfile located at "%2$s" is not writable.', 'event_espresso'), $file_type, $full_file_path);
372
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path);
373
+				throw new EE_Error($msg);
374 374
 			}
375 375
 			return FALSE;
376 376
 		}
377 377
 		// load WP_Filesystem and set file permissions
378
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $full_file_path );
378
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
379 379
 		// write the file
380
-		if ( ! $wp_filesystem->put_contents(EEH_File::convert_local_filepath_to_remote_filepath( $full_file_path ), $file_contents )) {
381
-			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
382
-				$msg = sprintf( __( 'The %1$sfile located at "%2$s" could not be written to.', 'event_espresso' ), $file_type, $full_file_path );
383
-				$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $full_file_path, 'f' );
384
-				throw new EE_Error( $msg );
380
+		if ( ! $wp_filesystem->put_contents(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path), $file_contents)) {
381
+			if (defined('WP_DEBUG') && WP_DEBUG) {
382
+				$msg = sprintf(__('The %1$sfile located at "%2$s" could not be written to.', 'event_espresso'), $file_type, $full_file_path);
383
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path, 'f');
384
+				throw new EE_Error($msg);
385 385
 			}
386 386
 			return FALSE;
387 387
 		}
@@ -397,9 +397,9 @@  discard block
 block discarded – undo
397 397
 	 * @throws EE_Error if filesystem credentials are required
398 398
 	 * @return boolean
399 399
 	 */
400
-	public static function delete( $filepath, $recursive = false, $type = false ) {
400
+	public static function delete($filepath, $recursive = false, $type = false) {
401 401
 		$wp_filesystem = EEH_File::_get_wp_filesystem();
402
-		return $wp_filesystem->delete( $filepath, $recursive, $type ) ? TRUE : FALSE;
402
+		return $wp_filesystem->delete($filepath, $recursive, $type) ? TRUE : FALSE;
403 403
 	}
404 404
 
405 405
 
@@ -411,9 +411,9 @@  discard block
 block discarded – undo
411 411
 	 * @throws EE_Error if filesystem credentials are required
412 412
 	 * @return bool
413 413
 	 */
414
-	public static function exists( $full_file_path = '' ) {
415
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $full_file_path );
416
-		return $wp_filesystem->exists( EEH_File::convert_local_filepath_to_remote_filepath( $full_file_path ) ) ? TRUE : FALSE;
414
+	public static function exists($full_file_path = '') {
415
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
416
+		return $wp_filesystem->exists(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path)) ? TRUE : FALSE;
417 417
 	}
418 418
 
419 419
 
@@ -426,9 +426,9 @@  discard block
 block discarded – undo
426 426
 	 * @throws EE_Error if filesystem credentials are required
427 427
 	 * @return bool
428 428
 	 */
429
-	public static function is_readable( $full_file_path = '' ) {
430
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $full_file_path );
431
-		if( $wp_filesystem->is_readable( EEH_File::convert_local_filepath_to_remote_filepath(  $full_file_path ) ) ) {
429
+	public static function is_readable($full_file_path = '') {
430
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
431
+		if ($wp_filesystem->is_readable(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path))) {
432 432
 			return true;
433 433
 		} else {
434 434
 			return false;
@@ -444,8 +444,8 @@  discard block
 block discarded – undo
444 444
 	 * @param string $full_file_path
445 445
 	 * @return string
446 446
 	 */
447
-	public static function remove_filename_from_filepath( $full_file_path = '' ) {
448
-		return pathinfo( $full_file_path, PATHINFO_DIRNAME );
447
+	public static function remove_filename_from_filepath($full_file_path = '') {
448
+		return pathinfo($full_file_path, PATHINFO_DIRNAME);
449 449
 	}
450 450
 
451 451
 
@@ -455,8 +455,8 @@  discard block
 block discarded – undo
455 455
 	 * @param string $full_file_path
456 456
 	 * @return string
457 457
 	 */
458
-	public static function get_filename_from_filepath( $full_file_path = '' ) {
459
-		return pathinfo( $full_file_path, PATHINFO_BASENAME );
458
+	public static function get_filename_from_filepath($full_file_path = '') {
459
+		return pathinfo($full_file_path, PATHINFO_BASENAME);
460 460
 	}
461 461
 
462 462
 
@@ -466,8 +466,8 @@  discard block
 block discarded – undo
466 466
 	 * @param string $full_file_path
467 467
 	 * @return string
468 468
 	 */
469
-	public static function get_file_extension( $full_file_path = '' ) {
470
-		return pathinfo( $full_file_path, PATHINFO_EXTENSION );
469
+	public static function get_file_extension($full_file_path = '') {
470
+		return pathinfo($full_file_path, PATHINFO_EXTENSION);
471 471
 	}
472 472
 
473 473
 
@@ -478,10 +478,10 @@  discard block
 block discarded – undo
478 478
 	 * @throws EE_Error if filesystem credentials are required
479 479
 	 * @return bool
480 480
 	 */
481
-	public static function add_htaccess_deny_from_all( $folder = '' ) {
482
-		$folder = EEH_File::standardise_and_end_with_directory_separator( $folder );
483
-		if ( ! EEH_File::exists( $folder . '.htaccess' ) ) {
484
-			if ( ! EEH_File::write_to_file( $folder . '.htaccess', 'deny from all', '.htaccess' )) {
481
+	public static function add_htaccess_deny_from_all($folder = '') {
482
+		$folder = EEH_File::standardise_and_end_with_directory_separator($folder);
483
+		if ( ! EEH_File::exists($folder.'.htaccess')) {
484
+			if ( ! EEH_File::write_to_file($folder.'.htaccess', 'deny from all', '.htaccess')) {
485 485
 				return FALSE;
486 486
 			}
487 487
 		}
@@ -495,10 +495,10 @@  discard block
 block discarded – undo
495 495
 	 * @throws EE_Error if filesystem credentials are required
496 496
 	 * @return boolean
497 497
 	 */
498
-	public static function add_index_file( $folder ) {
499
-		$folder = EEH_File::standardise_and_end_with_directory_separator( $folder );
500
-		if ( ! EEH_File::exists( $folder . 'index.php' ) ) {
501
-			if ( ! EEH_File::write_to_file( $folder . 'index.php', 'You are not permitted to read from this folder', '.php' )) {
498
+	public static function add_index_file($folder) {
499
+		$folder = EEH_File::standardise_and_end_with_directory_separator($folder);
500
+		if ( ! EEH_File::exists($folder.'index.php')) {
501
+			if ( ! EEH_File::write_to_file($folder.'index.php', 'You are not permitted to read from this folder', '.php')) {
502 502
 				return false;
503 503
 			}
504 504
 		}
@@ -513,11 +513,11 @@  discard block
 block discarded – undo
513 513
 	 * @param string $file_path
514 514
 	 * @return string
515 515
 	 */
516
-	public static function get_classname_from_filepath_with_standard_filename( $file_path ){
516
+	public static function get_classname_from_filepath_with_standard_filename($file_path) {
517 517
 		//extract file from path
518
-		$filename = basename( $file_path );
518
+		$filename = basename($file_path);
519 519
 		//now remove the first period and everything after
520
-		$pos_of_first_period = strpos( $filename,'.' );
520
+		$pos_of_first_period = strpos($filename, '.');
521 521
 		return substr($filename, 0, $pos_of_first_period);
522 522
 	}
523 523
 
@@ -529,8 +529,8 @@  discard block
 block discarded – undo
529 529
 	 * @param string $file_path
530 530
 	 * @return string
531 531
 	 */
532
-	public static function standardise_directory_separators( $file_path ){
533
-		return str_replace( array( '\\', '/' ), DS, $file_path );
532
+	public static function standardise_directory_separators($file_path) {
533
+		return str_replace(array('\\', '/'), DS, $file_path);
534 534
 	}
535 535
 
536 536
 
@@ -541,8 +541,8 @@  discard block
 block discarded – undo
541 541
 	 * @param string $file_path
542 542
 	 * @return string
543 543
 	 */
544
-	public static function end_with_directory_separator( $file_path ){
545
-		return rtrim( $file_path, '/\\' ) . DS;
544
+	public static function end_with_directory_separator($file_path) {
545
+		return rtrim($file_path, '/\\').DS;
546 546
 	}
547 547
 
548 548
 
@@ -552,8 +552,8 @@  discard block
 block discarded – undo
552 552
 	 * @param $file_path
553 553
 	 * @return string
554 554
 	 */
555
-	public static function standardise_and_end_with_directory_separator( $file_path ){
556
-		return self::end_with_directory_separator( self::standardise_directory_separators( $file_path ));
555
+	public static function standardise_and_end_with_directory_separator($file_path) {
556
+		return self::end_with_directory_separator(self::standardise_directory_separators($file_path));
557 557
 	}
558 558
 
559 559
 
@@ -570,21 +570,21 @@  discard block
 block discarded – undo
570 570
 	 *		if $index_numerically == FALSE (Default) keys are what the class names SHOULD be;
571 571
 	 *		 and values are their filepaths
572 572
 	 */
573
-	public static function get_contents_of_folders( $folder_paths = array(), $index_numerically = FALSE ){
573
+	public static function get_contents_of_folders($folder_paths = array(), $index_numerically = FALSE) {
574 574
 		$class_to_folder_path = array();
575
-		foreach( $folder_paths as $folder_path ){
576
-			$folder_path = self::standardise_and_end_with_directory_separator( $folder_path );
575
+		foreach ($folder_paths as $folder_path) {
576
+			$folder_path = self::standardise_and_end_with_directory_separator($folder_path);
577 577
 			// load WP_Filesystem and set file permissions
578
-			$files_in_folder = glob( $folder_path . '*' );
578
+			$files_in_folder = glob($folder_path.'*');
579 579
 			$class_to_folder_path = array();
580
-			if ( $files_in_folder ) {
581
-				foreach( $files_in_folder as $file_path ){
580
+			if ($files_in_folder) {
581
+				foreach ($files_in_folder as $file_path) {
582 582
 					//only add files, not folders
583
-					if ( ! is_dir( $file_path )) {
584
-						if ( $index_numerically ) {
583
+					if ( ! is_dir($file_path)) {
584
+						if ($index_numerically) {
585 585
 							$class_to_folder_path[] = $file_path;
586 586
 						} else {
587
-							$classname = self::get_classname_from_filepath_with_standard_filename( $file_path );
587
+							$classname = self::get_classname_from_filepath_with_standard_filename($file_path);
588 588
 							$class_to_folder_path[$classname] = $file_path;
589 589
 						}
590 590
 					}
@@ -604,39 +604,39 @@  discard block
 block discarded – undo
604 604
 	 * @throws EE_Error if filesystem credentials are required
605 605
 	 * @return boolean success
606 606
 	 */
607
-	public static function copy( $source_file, $destination_file, $overwrite = FALSE ){
608
-		$full_source_path = EEH_File::standardise_directory_separators( $source_file );
609
-		if( ! EEH_File::exists( $full_source_path ) ){
610
-			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
611
-				$msg = sprintf( __( 'The file located at "%2$s" is not readable or doesn\'t exist.', 'event_espresso' ), $full_source_path );
612
-				$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $full_source_path );
613
-				throw new EE_Error( $msg );
607
+	public static function copy($source_file, $destination_file, $overwrite = FALSE) {
608
+		$full_source_path = EEH_File::standardise_directory_separators($source_file);
609
+		if ( ! EEH_File::exists($full_source_path)) {
610
+			if (defined('WP_DEBUG') && WP_DEBUG) {
611
+				$msg = sprintf(__('The file located at "%2$s" is not readable or doesn\'t exist.', 'event_espresso'), $full_source_path);
612
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_source_path);
613
+				throw new EE_Error($msg);
614 614
 			}
615 615
 			return FALSE;
616 616
 		}
617 617
 
618
-		$full_dest_path = EEH_File::standardise_directory_separators( $destination_file );
619
-		$folder = EEH_File::remove_filename_from_filepath( $full_dest_path );
620
-		if ( ! EEH_File::verify_is_writable( $folder, 'folder' )) {
621
-			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
622
-				$msg = sprintf( __( 'The file located at "%2$s" is not writable.', 'event_espresso' ), $full_dest_path );
623
-				$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $full_dest_path );
624
-				throw new EE_Error( $msg );
618
+		$full_dest_path = EEH_File::standardise_directory_separators($destination_file);
619
+		$folder = EEH_File::remove_filename_from_filepath($full_dest_path);
620
+		if ( ! EEH_File::verify_is_writable($folder, 'folder')) {
621
+			if (defined('WP_DEBUG') && WP_DEBUG) {
622
+				$msg = sprintf(__('The file located at "%2$s" is not writable.', 'event_espresso'), $full_dest_path);
623
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_dest_path);
624
+				throw new EE_Error($msg);
625 625
 			}
626 626
 			return FALSE;
627 627
 		}
628 628
 
629 629
 		// load WP_Filesystem and set file permissions
630
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $destination_file );
630
+		$wp_filesystem = EEH_File::_get_wp_filesystem($destination_file);
631 631
 		// write the file
632 632
 		if ( ! $wp_filesystem->copy(
633
-						EEH_File::convert_local_filepath_to_remote_filepath( $full_source_path ),
634
-						EEH_File::convert_local_filepath_to_remote_filepath( $full_dest_path ),
633
+						EEH_File::convert_local_filepath_to_remote_filepath($full_source_path),
634
+						EEH_File::convert_local_filepath_to_remote_filepath($full_dest_path),
635 635
 						$overwrite )) {
636
-			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
637
-				$msg = sprintf( __( 'Attempted writing to file %1$s, but could not, probably because of permissions issues', 'event_espresso' ), $full_source_path );
638
-				$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $full_source_path, 'f' );
639
-				throw new EE_Error( $msg );
636
+			if (defined('WP_DEBUG') && WP_DEBUG) {
637
+				$msg = sprintf(__('Attempted writing to file %1$s, but could not, probably because of permissions issues', 'event_espresso'), $full_source_path);
638
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_source_path, 'f');
639
+				throw new EE_Error($msg);
640 640
 			}
641 641
 			return FALSE;
642 642
 		}
@@ -648,9 +648,9 @@  discard block
 block discarded – undo
648 648
 	 * @param string $filepath
649 649
 	 * @return boolean
650 650
 	 */
651
-	public static function is_in_uploads_folder( $filepath ) {
651
+	public static function is_in_uploads_folder($filepath) {
652 652
 		$uploads = wp_upload_dir();
653
-		return strpos( $filepath, $uploads[ 'basedir' ] ) === 0 ? true : false;
653
+		return strpos($filepath, $uploads['basedir']) === 0 ? true : false;
654 654
 	}
655 655
 
656 656
 	/**
@@ -665,9 +665,9 @@  discard block
 block discarded – undo
665 665
 	 * @return string the remote filepath (eg the filepath the filesystem method, eg
666 666
 	 * ftp or ssh, will use to access the folder
667 667
 	 */
668
-	public static function convert_local_filepath_to_remote_filepath( $local_filepath ) {
669
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $local_filepath );
670
-		return str_replace( WP_CONTENT_DIR . DS, $wp_filesystem->wp_content_dir(), $local_filepath );
668
+	public static function convert_local_filepath_to_remote_filepath($local_filepath) {
669
+		$wp_filesystem = EEH_File::_get_wp_filesystem($local_filepath);
670
+		return str_replace(WP_CONTENT_DIR.DS, $wp_filesystem->wp_content_dir(), $local_filepath);
671 671
 	}
672 672
 }
673 673
 // End of file EEH_File.helper.php
Please login to merge, or discard this patch.
Doc Comments   -2 removed lines patch added patch discarded remove patch
@@ -658,8 +658,6 @@
 block discarded – undo
658 658
 	 * converts it into a "remote" filepath (the filepath the currently-in-use
659 659
 	 * $wp_filesystem needs to use access the folder or file).
660 660
 	 * See http://wordpress.stackexchange.com/questions/124900/using-wp-filesystem-in-plugins
661
-	 * @param WP_Filesystem_Base $wp_filesystem we aren't initially sure which one
662
-	 * is in use, so you need to provide it
663 661
 	 * @param string $local_filepath the filepath to the folder/file locally
664 662
 	 * @throws EE_Error if filesystem credentials are required
665 663
 	 * @return string the remote filepath (eg the filepath the filesystem method, eg
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,4 +1,6 @@
 block discarded – undo
1
-<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
+	exit('No direct script access allowed');
3
+}
2 4
 /**
3 5
  * Event Espresso
4 6
  *
Please login to merge, or discard this patch.
core/EE_System.core.php 2 patches
Indentation   +1423 added lines, -1423 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -16,1428 +16,1428 @@  discard block
 block discarded – undo
16 16
 {
17 17
 
18 18
 
19
-    /**
20
-     * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
21
-     * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
22
-     */
23
-    const req_type_normal = 0;
24
-
25
-    /**
26
-     * Indicates this is a brand new installation of EE so we should install
27
-     * tables and default data etc
28
-     */
29
-    const req_type_new_activation = 1;
30
-
31
-    /**
32
-     * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
33
-     * and we just exited maintenance mode). We MUST check the database is setup properly
34
-     * and that default data is setup too
35
-     */
36
-    const req_type_reactivation = 2;
37
-
38
-    /**
39
-     * indicates that EE has been upgraded since its previous request.
40
-     * We may have data migration scripts to call and will want to trigger maintenance mode
41
-     */
42
-    const req_type_upgrade = 3;
43
-
44
-    /**
45
-     * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
46
-     */
47
-    const req_type_downgrade = 4;
48
-
49
-    /**
50
-     * @deprecated since version 4.6.0.dev.006
51
-     * Now whenever a new_activation is detected the request type is still just
52
-     * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
53
-     * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
54
-     * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
55
-     * (Specifically, when the migration manager indicates migrations are finished
56
-     * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
57
-     */
58
-    const req_type_activation_but_not_installed = 5;
59
-
60
-    /**
61
-     * option prefix for recording the activation history (like core's "espresso_db_update") of addons
62
-     */
63
-    const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
64
-
65
-
66
-    /**
67
-     *    instance of the EE_System object
68
-     *
69
-     * @var    $_instance
70
-     * @access    private
71
-     */
72
-    private static $_instance = null;
73
-
74
-    /**
75
-     * @type  EE_Registry $Registry
76
-     * @access    protected
77
-     */
78
-    protected $registry;
79
-
80
-    /**
81
-     * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
82
-     * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
83
-     *
84
-     * @var int
85
-     */
86
-    private $_req_type;
87
-
88
-    /**
89
-     * Whether or not there was a non-micro version change in EE core version during this request
90
-     *
91
-     * @var boolean
92
-     */
93
-    private $_major_version_change = false;
94
-
95
-
96
-
97
-    /**
98
-     * @singleton method used to instantiate class object
99
-     * @access    public
100
-     * @param  \EE_Registry $Registry
101
-     * @return \EE_System
102
-     */
103
-    public static function instance(EE_Registry $Registry = null)
104
-    {
105
-        // check if class object is instantiated
106
-        if ( ! self::$_instance instanceof EE_System) {
107
-            self::$_instance = new self($Registry);
108
-        }
109
-        return self::$_instance;
110
-    }
111
-
112
-
113
-
114
-    /**
115
-     * resets the instance and returns it
116
-     *
117
-     * @return EE_System
118
-     */
119
-    public static function reset()
120
-    {
121
-        self::$_instance->_req_type = null;
122
-        //make sure none of the old hooks are left hanging around
123
-        remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
124
-        //we need to reset the migration manager in order for it to detect DMSs properly
125
-        EE_Data_Migration_Manager::reset();
126
-        self::instance()->detect_activations_or_upgrades();
127
-        self::instance()->perform_activations_upgrades_and_migrations();
128
-        return self::instance();
129
-    }
130
-
131
-
132
-
133
-    /**
134
-     *    sets hooks for running rest of system
135
-     *    provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
136
-     *    starting EE Addons from any other point may lead to problems
137
-     *
138
-     * @access private
139
-     * @param  \EE_Registry $Registry
140
-     */
141
-    private function __construct(EE_Registry $Registry)
142
-    {
143
-        $this->registry = $Registry;
144
-        do_action('AHEE__EE_System__construct__begin', $this);
145
-        // allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
146
-        add_action('AHEE__EE_Bootstrap__load_espresso_addons', array($this, 'load_espresso_addons'));
147
-        // when an ee addon is activated, we want to call the core hook(s) again
148
-        // because the newly-activated addon didn't get a chance to run at all
149
-        add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
150
-        // detect whether install or upgrade
151
-        add_action('AHEE__EE_Bootstrap__detect_activations_or_upgrades', array($this, 'detect_activations_or_upgrades'),
152
-            3);
153
-        // load EE_Config, EE_Textdomain, etc
154
-        add_action('AHEE__EE_Bootstrap__load_core_configuration', array($this, 'load_core_configuration'), 5);
155
-        // load EE_Config, EE_Textdomain, etc
156
-        add_action('AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
157
-            array($this, 'register_shortcodes_modules_and_widgets'), 7);
158
-        // you wanna get going? I wanna get going... let's get going!
159
-        add_action('AHEE__EE_Bootstrap__brew_espresso', array($this, 'brew_espresso'), 9);
160
-        //other housekeeping
161
-        //exclude EE critical pages from wp_list_pages
162
-        add_filter('wp_list_pages_excludes', array($this, 'remove_pages_from_wp_list_pages'), 10);
163
-        // ALL EE Addons should use the following hook point to attach their initial setup too
164
-        // it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
165
-        do_action('AHEE__EE_System__construct__complete', $this);
166
-    }
167
-
168
-
169
-
170
-    /**
171
-     * load_espresso_addons
172
-     * allow addons to load first so that they can set hooks for running DMS's, etc
173
-     * this is hooked into both:
174
-     *    'AHEE__EE_Bootstrap__load_core_configuration'
175
-     *        which runs during the WP 'plugins_loaded' action at priority 5
176
-     *    and the WP 'activate_plugin' hookpoint
177
-     *
178
-     * @access public
179
-     * @return void
180
-     */
181
-    public function load_espresso_addons()
182
-    {
183
-        // set autoloaders for all of the classes implementing EEI_Plugin_API
184
-        // which provide helpers for EE plugin authors to more easily register certain components with EE.
185
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
186
-        //load and setup EE_Capabilities
187
-        $this->registry->load_core('Capabilities');
188
-        //caps need to be initialized on every request so that capability maps are set.
189
-        //@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
190
-        $this->registry->CAP->init_caps();
191
-        do_action('AHEE__EE_System__load_espresso_addons');
192
-        //if the WP API basic auth plugin isn't already loaded, load it now.
193
-        //We want it for mobile apps. Just include the entire plugin
194
-        //also, don't load the basic auth when a plugin is getting activated, because
195
-        //it could be the basic auth plugin, and it doesn't check if its methods are already defined
196
-        //and causes a fatal error
197
-        if ( ! function_exists('json_basic_auth_handler')
198
-             && ! function_exists('json_basic_auth_error')
199
-             && ! (
200
-                isset($_GET['action'])
201
-                && in_array($_GET['action'], array('activate', 'activate-selected'))
202
-            )
203
-             && ! (
204
-                isset($_GET['activate'])
205
-                && $_GET['activate'] === 'true'
206
-            )
207
-        ) {
208
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
209
-        }
210
-        do_action('AHEE__EE_System__load_espresso_addons__complete');
211
-    }
212
-
213
-
214
-
215
-    /**
216
-     * detect_activations_or_upgrades
217
-     * Checks for activation or upgrade of core first;
218
-     * then also checks if any registered addons have been activated or upgraded
219
-     * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
220
-     * which runs during the WP 'plugins_loaded' action at priority 3
221
-     *
222
-     * @access public
223
-     * @return void
224
-     */
225
-    public function detect_activations_or_upgrades()
226
-    {
227
-        //first off: let's make sure to handle core
228
-        $this->detect_if_activation_or_upgrade();
229
-        foreach ($this->registry->addons as $addon) {
230
-            //detect teh request type for that addon
231
-            $addon->detect_activation_or_upgrade();
232
-        }
233
-    }
234
-
235
-
236
-
237
-    /**
238
-     * detect_if_activation_or_upgrade
239
-     * Takes care of detecting whether this is a brand new install or code upgrade,
240
-     * and either setting up the DB or setting up maintenance mode etc.
241
-     *
242
-     * @access public
243
-     * @return void
244
-     */
245
-    public function detect_if_activation_or_upgrade()
246
-    {
247
-        do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
248
-        // load M-Mode class
249
-        $this->registry->load_core('Maintenance_Mode');
250
-        // check if db has been updated, or if its a brand-new installation
251
-        $espresso_db_update = $this->fix_espresso_db_upgrade_option();
252
-        $request_type = $this->detect_req_type($espresso_db_update);
253
-        //EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
254
-        switch ($request_type) {
255
-            case EE_System::req_type_new_activation:
256
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
257
-                $this->_handle_core_version_change($espresso_db_update);
258
-                break;
259
-            case EE_System::req_type_reactivation:
260
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
261
-                $this->_handle_core_version_change($espresso_db_update);
262
-                break;
263
-            case EE_System::req_type_upgrade:
264
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
265
-                //migrations may be required now that we've upgraded
266
-                EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
267
-                $this->_handle_core_version_change($espresso_db_update);
268
-                //				echo "done upgrade";die;
269
-                break;
270
-            case EE_System::req_type_downgrade:
271
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
272
-                //its possible migrations are no longer required
273
-                EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
274
-                $this->_handle_core_version_change($espresso_db_update);
275
-                break;
276
-            case EE_System::req_type_normal:
277
-            default:
278
-                //				$this->_maybe_redirect_to_ee_about();
279
-                break;
280
-        }
281
-        do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
282
-    }
283
-
284
-
285
-
286
-    /**
287
-     * Updates the list of installed versions and sets hooks for
288
-     * initializing the database later during the request
289
-     *
290
-     * @param array $espresso_db_update
291
-     */
292
-    protected function _handle_core_version_change($espresso_db_update)
293
-    {
294
-        $this->update_list_of_installed_versions($espresso_db_update);
295
-        //get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
296
-        add_action('AHEE__EE_System__perform_activations_upgrades_and_migrations',
297
-            array($this, 'initialize_db_if_no_migrations_required'));
298
-    }
299
-
300
-
301
-
302
-    /**
303
-     * standardizes the wp option 'espresso_db_upgrade' which actually stores
304
-     * information about what versions of EE have been installed and activated,
305
-     * NOT necessarily the state of the database
306
-     *
307
-     * @param null $espresso_db_update
308
-     * @internal param array $espresso_db_update_value the value of the WordPress option. If not supplied, fetches it
309
-     *           from the options table
310
-     * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
311
-     */
312
-    private function fix_espresso_db_upgrade_option($espresso_db_update = null)
313
-    {
314
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
315
-        if ( ! $espresso_db_update) {
316
-            $espresso_db_update = get_option('espresso_db_update');
317
-        }
318
-        // check that option is an array
319
-        if ( ! is_array($espresso_db_update)) {
320
-            // if option is FALSE, then it never existed
321
-            if ($espresso_db_update === false) {
322
-                // make $espresso_db_update an array and save option with autoload OFF
323
-                $espresso_db_update = array();
324
-                add_option('espresso_db_update', $espresso_db_update, '', 'no');
325
-            } else {
326
-                // option is NOT FALSE but also is NOT an array, so make it an array and save it
327
-                $espresso_db_update = array($espresso_db_update => array());
328
-                update_option('espresso_db_update', $espresso_db_update);
329
-            }
330
-        } else {
331
-            $corrected_db_update = array();
332
-            //if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
333
-            foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
334
-                if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
335
-                    //the key is an int, and the value IS NOT an array
336
-                    //so it must be numerically-indexed, where values are versions installed...
337
-                    //fix it!
338
-                    $version_string = $should_be_array;
339
-                    $corrected_db_update[$version_string] = array('unknown-date');
340
-                } else {
341
-                    //ok it checks out
342
-                    $corrected_db_update[$should_be_version_string] = $should_be_array;
343
-                }
344
-            }
345
-            $espresso_db_update = $corrected_db_update;
346
-            update_option('espresso_db_update', $espresso_db_update);
347
-        }
348
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
349
-        return $espresso_db_update;
350
-    }
351
-
352
-
353
-
354
-    /**
355
-     * Does the traditional work of setting up the plugin's database and adding default data.
356
-     * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
357
-     * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
358
-     * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
359
-     * so that it will be done when migrations are finished
360
-     *
361
-     * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
362
-     * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
363
-     *                                       This is a resource-intensive job
364
-     *                                       so we prefer to only do it when necessary
365
-     * @return void
366
-     */
367
-    public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
368
-    {
369
-        $request_type = $this->detect_req_type();
370
-        //only initialize system if we're not in maintenance mode.
371
-        if (EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance) {
372
-            update_option('ee_flush_rewrite_rules', true);
373
-            if ($verify_schema) {
374
-                EEH_Activation::initialize_db_and_folders();
375
-            }
376
-            EEH_Activation::initialize_db_content();
377
-            EEH_Activation::system_initialization();
378
-            if ($initialize_addons_too) {
379
-                $this->initialize_addons();
380
-            }
381
-        } else {
382
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
383
-        }
384
-        if ($request_type === EE_System::req_type_new_activation
385
-            || $request_type === EE_System::req_type_reactivation
386
-            || (
387
-                $request_type === EE_System::req_type_upgrade
388
-                && $this->is_major_version_change()
389
-            )
390
-        ) {
391
-            add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
392
-        }
393
-    }
394
-
395
-
396
-
397
-    /**
398
-     * Initializes the db for all registered addons
399
-     */
400
-    public function initialize_addons()
401
-    {
402
-        //foreach registered addon, make sure its db is up-to-date too
403
-        foreach ($this->registry->addons as $addon) {
404
-            $addon->initialize_db_if_no_migrations_required();
405
-        }
406
-    }
407
-
408
-
409
-
410
-    /**
411
-     * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
412
-     *
413
-     * @param    array  $version_history
414
-     * @param    string $current_version_to_add version to be added to the version history
415
-     * @return    boolean success as to whether or not this option was changed
416
-     */
417
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
418
-    {
419
-        if ( ! $version_history) {
420
-            $version_history = $this->fix_espresso_db_upgrade_option($version_history);
421
-        }
422
-        if ($current_version_to_add == null) {
423
-            $current_version_to_add = espresso_version();
424
-        }
425
-        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
426
-        // re-save
427
-        return update_option('espresso_db_update', $version_history);
428
-    }
429
-
430
-
431
-
432
-    /**
433
-     * Detects if the current version indicated in the has existed in the list of
434
-     * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
435
-     *
436
-     * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
437
-     *                                  If not supplied, fetches it from the options table.
438
-     *                                  Also, caches its result so later parts of the code can also know whether
439
-     *                                  there's been an update or not. This way we can add the current version to
440
-     *                                  espresso_db_update, but still know if this is a new install or not
441
-     * @return int one of the constants on EE_System::req_type_
442
-     */
443
-    public function detect_req_type($espresso_db_update = null)
444
-    {
445
-        if ($this->_req_type === null) {
446
-            $espresso_db_update = ! empty($espresso_db_update) ? $espresso_db_update
447
-                : $this->fix_espresso_db_upgrade_option();
448
-            $this->_req_type = $this->detect_req_type_given_activation_history($espresso_db_update,
449
-                'ee_espresso_activation', espresso_version());
450
-            $this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
451
-        }
452
-        return $this->_req_type;
453
-    }
454
-
455
-
456
-
457
-    /**
458
-     * Returns whether or not there was a non-micro version change (ie, change in either
459
-     * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
460
-     * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
461
-     *
462
-     * @param $activation_history
463
-     * @return bool
464
-     */
465
-    protected function _detect_major_version_change($activation_history)
466
-    {
467
-        $previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
468
-        $previous_version_parts = explode('.', $previous_version);
469
-        $current_version_parts = explode('.', espresso_version());
470
-        return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
471
-               && ($previous_version_parts[0] !== $current_version_parts[0]
472
-                   || $previous_version_parts[1] !== $current_version_parts[1]
473
-               );
474
-    }
475
-
476
-
477
-
478
-    /**
479
-     * Returns true if either the major or minor version of EE changed during this request.
480
-     * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
481
-     *
482
-     * @return bool
483
-     */
484
-    public function is_major_version_change()
485
-    {
486
-        return $this->_major_version_change;
487
-    }
488
-
489
-
490
-
491
-    /**
492
-     * Determines the request type for any ee addon, given three piece of info: the current array of activation
493
-     * histories (for core that' 'espresso_db_update' wp option); the name of the wordpress option which is temporarily
494
-     * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
495
-     * just activated to (for core that will always be espresso_version())
496
-     *
497
-     * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
498
-     *                                                 ee plugin. for core that's 'espresso_db_update'
499
-     * @param string $activation_indicator_option_name the name of the wordpress option that is temporarily set to
500
-     *                                                 indicate that this plugin was just activated
501
-     * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
502
-     *                                                 espresso_version())
503
-     * @return int one of the constants on EE_System::req_type_*
504
-     */
505
-    public static function detect_req_type_given_activation_history(
506
-        $activation_history_for_addon,
507
-        $activation_indicator_option_name,
508
-        $version_to_upgrade_to
509
-    ) {
510
-        $version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
511
-        if ($activation_history_for_addon) {
512
-            //it exists, so this isn't a completely new install
513
-            //check if this version already in that list of previously installed versions
514
-            if ( ! isset($activation_history_for_addon[$version_to_upgrade_to])) {
515
-                //it a version we haven't seen before
516
-                if ($version_is_higher === 1) {
517
-                    $req_type = EE_System::req_type_upgrade;
518
-                } else {
519
-                    $req_type = EE_System::req_type_downgrade;
520
-                }
521
-                delete_option($activation_indicator_option_name);
522
-            } else {
523
-                // its not an update. maybe a reactivation?
524
-                if (get_option($activation_indicator_option_name, false)) {
525
-                    if ($version_is_higher === -1) {
526
-                        $req_type = EE_System::req_type_downgrade;
527
-                    } elseif ($version_is_higher === 0) {
528
-                        //we've seen this version before, but it's an activation. must be a reactivation
529
-                        $req_type = EE_System::req_type_reactivation;
530
-                    } else {//$version_is_higher === 1
531
-                        $req_type = EE_System::req_type_upgrade;
532
-                    }
533
-                    delete_option($activation_indicator_option_name);
534
-                } else {
535
-                    //we've seen this version before and the activation indicate doesn't show it was just activated
536
-                    if ($version_is_higher === -1) {
537
-                        $req_type = EE_System::req_type_downgrade;
538
-                    } elseif ($version_is_higher === 0) {
539
-                        //we've seen this version before and it's not an activation. its normal request
540
-                        $req_type = EE_System::req_type_normal;
541
-                    } else {//$version_is_higher === 1
542
-                        $req_type = EE_System::req_type_upgrade;
543
-                    }
544
-                }
545
-            }
546
-        } else {
547
-            //brand new install
548
-            $req_type = EE_System::req_type_new_activation;
549
-            delete_option($activation_indicator_option_name);
550
-        }
551
-        return $req_type;
552
-    }
553
-
554
-
555
-
556
-    /**
557
-     * Detects if the $version_to_upgrade_to is higher than the most recent version in
558
-     * the $activation_history_for_addon
559
-     *
560
-     * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
561
-     *                                             sometimes containing 'unknown-date'
562
-     * @param string $version_to_upgrade_to        (current version)
563
-     * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
564
-     *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
565
-     *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
566
-     *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
567
-     */
568
-    protected static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
569
-    {
570
-        //find the most recently-activated version
571
-        $most_recently_active_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
572
-        return version_compare($version_to_upgrade_to, $most_recently_active_version);
573
-    }
574
-
575
-
576
-
577
-    /**
578
-     * Gets the most recently active version listed in the activation history,
579
-     * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
580
-     *
581
-     * @param array $activation_history  (keys are versions, values are arrays of times activated,
582
-     *                                   sometimes containing 'unknown-date'
583
-     * @return string
584
-     */
585
-    protected static function _get_most_recently_active_version_from_activation_history($activation_history)
586
-    {
587
-        $most_recently_active_version_activation = '1970-01-01 00:00:00';
588
-        $most_recently_active_version = '0.0.0.dev.000';
589
-        if (is_array($activation_history)) {
590
-            foreach ($activation_history as $version => $times_activated) {
591
-                //check there is a record of when this version was activated. Otherwise,
592
-                //mark it as unknown
593
-                if ( ! $times_activated) {
594
-                    $times_activated = array('unknown-date');
595
-                }
596
-                if (is_string($times_activated)) {
597
-                    $times_activated = array($times_activated);
598
-                }
599
-                foreach ($times_activated as $an_activation) {
600
-                    if ($an_activation != 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
601
-                        $most_recently_active_version = $version;
602
-                        $most_recently_active_version_activation = $an_activation == 'unknown-date'
603
-                            ? '1970-01-01 00:00:00' : $an_activation;
604
-                    }
605
-                }
606
-            }
607
-        }
608
-        return $most_recently_active_version;
609
-    }
610
-
611
-
612
-
613
-    /**
614
-     * This redirects to the about EE page after activation
615
-     *
616
-     * @return void
617
-     */
618
-    public function redirect_to_about_ee()
619
-    {
620
-        $notices = EE_Error::get_notices(false);
621
-        //if current user is an admin and it's not an ajax or rest request
622
-        if (
623
-            ! (defined('DOING_AJAX') && DOING_AJAX)
624
-            && ! (defined('REST_REQUEST') && REST_REQUEST)
625
-            && ! isset($notices['errors'])
626
-            && apply_filters(
627
-                'FHEE__EE_System__redirect_to_about_ee__do_redirect',
628
-                $this->registry->CAP->current_user_can('manage_options', 'espresso_about_default')
629
-            )
630
-        ) {
631
-            $query_params = array('page' => 'espresso_about');
632
-            if (EE_System::instance()->detect_req_type() == EE_System::req_type_new_activation) {
633
-                $query_params['new_activation'] = true;
634
-            }
635
-            if (EE_System::instance()->detect_req_type() == EE_System::req_type_reactivation) {
636
-                $query_params['reactivation'] = true;
637
-            }
638
-            $url = add_query_arg($query_params, admin_url('admin.php'));
639
-            wp_safe_redirect($url);
640
-            exit();
641
-        }
642
-    }
643
-
644
-
645
-
646
-    /**
647
-     * load_core_configuration
648
-     * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
649
-     * which runs during the WP 'plugins_loaded' action at priority 5
650
-     *
651
-     * @return void
652
-     */
653
-    public function load_core_configuration()
654
-    {
655
-        do_action('AHEE__EE_System__load_core_configuration__begin', $this);
656
-        $this->registry->load_core('EE_Load_Textdomain');
657
-        //load textdomain
658
-        EE_Load_Textdomain::load_textdomain();
659
-        // load and setup EE_Config and EE_Network_Config
660
-        $this->registry->load_core('Config');
661
-        $this->registry->load_core('Network_Config');
662
-        // setup autoloaders
663
-        // enable logging?
664
-        if ($this->registry->CFG->admin->use_full_logging) {
665
-            $this->registry->load_core('Log');
666
-        }
667
-        // check for activation errors
668
-        $activation_errors = get_option('ee_plugin_activation_errors', false);
669
-        if ($activation_errors) {
670
-            EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
671
-            update_option('ee_plugin_activation_errors', false);
672
-        }
673
-        // get model names
674
-        $this->_parse_model_names();
675
-        //load caf stuff a chance to play during the activation process too.
676
-        $this->_maybe_brew_regular();
677
-        do_action('AHEE__EE_System__load_core_configuration__complete', $this);
678
-    }
679
-
680
-
681
-
682
-    /**
683
-     * cycles through all of the models/*.model.php files, and assembles an array of model names
684
-     *
685
-     * @return void
686
-     */
687
-    private function _parse_model_names()
688
-    {
689
-        //get all the files in the EE_MODELS folder that end in .model.php
690
-        $models = glob(EE_MODELS . '*.model.php');
691
-        $model_names = array();
692
-        $non_abstract_db_models = array();
693
-        foreach ($models as $model) {
694
-            // get model classname
695
-            $classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
696
-            $short_name = str_replace('EEM_', '', $classname);
697
-            $reflectionClass = new ReflectionClass($classname);
698
-            if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
699
-                $non_abstract_db_models[$short_name] = $classname;
700
-            }
701
-            $model_names[$short_name] = $classname;
702
-        }
703
-        $this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
704
-        $this->registry->non_abstract_db_models = apply_filters('FHEE__EE_System__parse_implemented_model_names',
705
-            $non_abstract_db_models);
706
-    }
707
-
708
-
709
-
710
-    /**
711
-     * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
712
-     * that need to be setup before our EE_System launches.
713
-     *
714
-     * @return void
715
-     */
716
-    private function _maybe_brew_regular()
717
-    {
718
-        if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
719
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
720
-        }
721
-    }
722
-
723
-
724
-
725
-    /**
726
-     * register_shortcodes_modules_and_widgets
727
-     * generate lists of shortcodes and modules, then verify paths and classes
728
-     * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
729
-     * which runs during the WP 'plugins_loaded' action at priority 7
730
-     *
731
-     * @access public
732
-     * @return void
733
-     */
734
-    public function register_shortcodes_modules_and_widgets()
735
-    {
736
-        do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
737
-        // check for addons using old hookpoint
738
-        if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
739
-            $this->_incompatible_addon_error();
740
-        }
741
-    }
742
-
743
-
744
-
745
-    /**
746
-     * _incompatible_addon_error
747
-     *
748
-     * @access public
749
-     * @return void
750
-     */
751
-    private function _incompatible_addon_error()
752
-    {
753
-        // get array of classes hooking into here
754
-        $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook('AHEE__EE_System__register_shortcodes_modules_and_addons');
755
-        if ( ! empty($class_names)) {
756
-            $msg = __('The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
757
-                'event_espresso');
758
-            $msg .= '<ul>';
759
-            foreach ($class_names as $class_name) {
760
-                $msg .= '<li><b>Event Espresso - ' . str_replace(array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
761
-                        $class_name) . '</b></li>';
762
-            }
763
-            $msg .= '</ul>';
764
-            $msg .= __('Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
765
-                'event_espresso');
766
-            // save list of incompatible addons to wp-options for later use
767
-            add_option('ee_incompatible_addons', $class_names, '', 'no');
768
-            if (is_admin()) {
769
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
770
-            }
771
-        }
772
-    }
773
-
774
-
775
-
776
-    /**
777
-     * brew_espresso
778
-     * begins the process of setting hooks for initializing EE in the correct order
779
-     * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hookpoint
780
-     * which runs during the WP 'plugins_loaded' action at priority 9
781
-     *
782
-     * @return void
783
-     */
784
-    public function brew_espresso()
785
-    {
786
-        do_action('AHEE__EE_System__brew_espresso__begin', $this);
787
-        // load some final core systems
788
-        add_action('init', array($this, 'set_hooks_for_core'), 1);
789
-        add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
790
-        add_action('init', array($this, 'load_CPTs_and_session'), 5);
791
-        add_action('init', array($this, 'load_controllers'), 7);
792
-        add_action('init', array($this, 'core_loaded_and_ready'), 9);
793
-        add_action('init', array($this, 'initialize'), 10);
794
-        add_action('init', array($this, 'initialize_last'), 100);
795
-        add_action('wp_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 100);
796
-        add_action('admin_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 100);
797
-        add_action('admin_bar_menu', array($this, 'espresso_toolbar_items'), 100);
798
-        if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
799
-            // pew pew pew
800
-            $this->registry->load_core('PUE');
801
-            do_action('AHEE__EE_System__brew_espresso__after_pue_init');
802
-        }
803
-        do_action('AHEE__EE_System__brew_espresso__complete', $this);
804
-    }
805
-
806
-
807
-
808
-    /**
809
-     *    set_hooks_for_core
810
-     *
811
-     * @access public
812
-     * @return    void
813
-     */
814
-    public function set_hooks_for_core()
815
-    {
816
-        $this->_deactivate_incompatible_addons();
817
-        do_action('AHEE__EE_System__set_hooks_for_core');
818
-    }
819
-
820
-
821
-
822
-    /**
823
-     * Using the information gathered in EE_System::_incompatible_addon_error,
824
-     * deactivates any addons considered incompatible with the current version of EE
825
-     */
826
-    private function _deactivate_incompatible_addons()
827
-    {
828
-        $incompatible_addons = get_option('ee_incompatible_addons', array());
829
-        if ( ! empty($incompatible_addons)) {
830
-            $active_plugins = get_option('active_plugins', array());
831
-            foreach ($active_plugins as $active_plugin) {
832
-                foreach ($incompatible_addons as $incompatible_addon) {
833
-                    if (strpos($active_plugin, $incompatible_addon) !== false) {
834
-                        unset($_GET['activate']);
835
-                        espresso_deactivate_plugin($active_plugin);
836
-                    }
837
-                }
838
-            }
839
-        }
840
-    }
841
-
842
-
843
-
844
-    /**
845
-     *    perform_activations_upgrades_and_migrations
846
-     *
847
-     * @access public
848
-     * @return    void
849
-     */
850
-    public function perform_activations_upgrades_and_migrations()
851
-    {
852
-        //first check if we had previously attempted to setup EE's directories but failed
853
-        if (EEH_Activation::upload_directories_incomplete()) {
854
-            EEH_Activation::create_upload_directories();
855
-        }
856
-        do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
857
-    }
858
-
859
-
860
-
861
-    /**
862
-     *    load_CPTs_and_session
863
-     *
864
-     * @access public
865
-     * @return    void
866
-     */
867
-    public function load_CPTs_and_session()
868
-    {
869
-        do_action('AHEE__EE_System__load_CPTs_and_session__start');
870
-        // register Custom Post Types
871
-        $this->registry->load_core('Register_CPTs');
872
-        do_action('AHEE__EE_System__load_CPTs_and_session__complete');
873
-    }
874
-
875
-
876
-
877
-    /**
878
-     * load_controllers
879
-     * this is the best place to load any additional controllers that needs access to EE core.
880
-     * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
881
-     * time
882
-     *
883
-     * @access public
884
-     * @return void
885
-     */
886
-    public function load_controllers()
887
-    {
888
-        do_action('AHEE__EE_System__load_controllers__start');
889
-        // let's get it started
890
-        if ( ! is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
891
-            do_action('AHEE__EE_System__load_controllers__load_front_controllers');
892
-            $this->registry->load_core('Front_Controller', array(), false, true);
893
-        } else if ( ! EE_FRONT_AJAX) {
894
-            do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
895
-            EE_Registry::instance()->load_core('Admin');
896
-        }
897
-        do_action('AHEE__EE_System__load_controllers__complete');
898
-    }
899
-
900
-
901
-
902
-    /**
903
-     * core_loaded_and_ready
904
-     * all of the basic EE core should be loaded at this point and available regardless of M-Mode
905
-     *
906
-     * @access public
907
-     * @return void
908
-     */
909
-    public function core_loaded_and_ready()
910
-    {
911
-        do_action('AHEE__EE_System__core_loaded_and_ready');
912
-        do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
913
-        $this->registry->load_core('Session');
914
-        //		add_action( 'wp_loaded', array( $this, 'set_hooks_for_shortcodes_modules_and_addons' ), 1 );
915
-    }
916
-
917
-
918
-
919
-    /**
920
-     * initialize
921
-     * this is the best place to begin initializing client code
922
-     *
923
-     * @access public
924
-     * @return void
925
-     */
926
-    public function initialize()
927
-    {
928
-        do_action('AHEE__EE_System__initialize');
929
-    }
930
-
931
-
932
-
933
-    /**
934
-     * initialize_last
935
-     * this is run really late during the WP init hookpoint, and ensures that mostly everything else that needs to
936
-     * initialize has done so
937
-     *
938
-     * @access public
939
-     * @return void
940
-     */
941
-    public function initialize_last()
942
-    {
943
-        do_action('AHEE__EE_System__initialize_last');
944
-    }
945
-
946
-
947
-
948
-    /**
949
-     * set_hooks_for_shortcodes_modules_and_addons
950
-     * this is the best place for other systems to set callbacks for hooking into other parts of EE
951
-     * this happens at the very beginning of the wp_loaded hookpoint
952
-     *
953
-     * @access public
954
-     * @return void
955
-     */
956
-    public function set_hooks_for_shortcodes_modules_and_addons()
957
-    {
958
-        //		do_action( 'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons' );
959
-    }
960
-
961
-
962
-
963
-    /**
964
-     * do_not_cache
965
-     * sets no cache headers and defines no cache constants for WP plugins
966
-     *
967
-     * @access public
968
-     * @return void
969
-     */
970
-    public static function do_not_cache()
971
-    {
972
-        // set no cache constants
973
-        if ( ! defined('DONOTCACHEPAGE')) {
974
-            define('DONOTCACHEPAGE', true);
975
-        }
976
-        if ( ! defined('DONOTCACHCEOBJECT')) {
977
-            define('DONOTCACHCEOBJECT', true);
978
-        }
979
-        if ( ! defined('DONOTCACHEDB')) {
980
-            define('DONOTCACHEDB', true);
981
-        }
982
-        // add no cache headers
983
-        add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
984
-        // plus a little extra for nginx and Google Chrome
985
-        add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
986
-        // prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
987
-        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
988
-    }
989
-
990
-
991
-
992
-    /**
993
-     *    extra_nocache_headers
994
-     *
995
-     * @access    public
996
-     * @param $headers
997
-     * @return    array
998
-     */
999
-    public static function extra_nocache_headers($headers)
1000
-    {
1001
-        // for NGINX
1002
-        $headers['X-Accel-Expires'] = 0;
1003
-        // plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1004
-        $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1005
-        return $headers;
1006
-    }
1007
-
1008
-
1009
-
1010
-    /**
1011
-     *    nocache_headers
1012
-     *
1013
-     * @access    public
1014
-     * @return    void
1015
-     */
1016
-    public static function nocache_headers()
1017
-    {
1018
-        nocache_headers();
1019
-    }
1020
-
1021
-
1022
-
1023
-    /**
1024
-     *    espresso_toolbar_items
1025
-     *
1026
-     * @access public
1027
-     * @param  WP_Admin_Bar $admin_bar
1028
-     * @return void
1029
-     */
1030
-    public function espresso_toolbar_items(WP_Admin_Bar $admin_bar)
1031
-    {
1032
-        // if in full M-Mode, or its an AJAX request, or user is NOT an admin
1033
-        if (EE_Maintenance_Mode::instance()->level() == EE_Maintenance_Mode::level_2_complete_maintenance
1034
-            || defined('DOING_AJAX')
1035
-            || ! $this->registry->CAP->current_user_can('ee_read_ee', 'ee_admin_bar_menu_top_level')
1036
-        ) {
1037
-            return;
1038
-        }
1039
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1040
-        $menu_class = 'espresso_menu_item_class';
1041
-        //we don't use the constants EVENTS_ADMIN_URL or REG_ADMIN_URL
1042
-        //because they're only defined in each of their respective constructors
1043
-        //and this might be a frontend request, in which case they aren't available
1044
-        $events_admin_url = admin_url("admin.php?page=espresso_events");
1045
-        $reg_admin_url = admin_url("admin.php?page=espresso_registrations");
1046
-        $extensions_admin_url = admin_url("admin.php?page=espresso_packages");
1047
-        //Top Level
1048
-        $admin_bar->add_menu(array(
1049
-            'id'    => 'espresso-toolbar',
1050
-            'title' => '<span class="ee-icon ee-icon-ee-cup-thick ee-icon-size-20"></span><span class="ab-label">'
1051
-                       . _x('Event Espresso', 'admin bar menu group label', 'event_espresso')
1052
-                       . '</span>',
1053
-            'href'  => $events_admin_url,
1054
-            'meta'  => array(
1055
-                'title' => __('Event Espresso', 'event_espresso'),
1056
-                'class' => $menu_class . 'first',
1057
-            ),
1058
-        ));
1059
-        //Events
1060
-        if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events')) {
1061
-            $admin_bar->add_menu(array(
1062
-                'id'     => 'espresso-toolbar-events',
1063
-                'parent' => 'espresso-toolbar',
1064
-                'title'  => __('Events', 'event_espresso'),
1065
-                'href'   => $events_admin_url,
1066
-                'meta'   => array(
1067
-                    'title'  => __('Events', 'event_espresso'),
1068
-                    'target' => '',
1069
-                    'class'  => $menu_class,
1070
-                ),
1071
-            ));
1072
-        }
1073
-        if ($this->registry->CAP->current_user_can('ee_edit_events', 'ee_admin_bar_menu_espresso-toolbar-events-new')) {
1074
-            //Events Add New
1075
-            $admin_bar->add_menu(array(
1076
-                'id'     => 'espresso-toolbar-events-new',
1077
-                'parent' => 'espresso-toolbar-events',
1078
-                'title'  => __('Add New', 'event_espresso'),
1079
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'create_new'), $events_admin_url),
1080
-                'meta'   => array(
1081
-                    'title'  => __('Add New', 'event_espresso'),
1082
-                    'target' => '',
1083
-                    'class'  => $menu_class,
1084
-                ),
1085
-            ));
1086
-        }
1087
-        if (is_single() && (get_post_type() == 'espresso_events')) {
1088
-            //Current post
1089
-            global $post;
1090
-            if ($this->registry->CAP->current_user_can('ee_edit_event',
1091
-                'ee_admin_bar_menu_espresso-toolbar-events-edit', $post->ID)
1092
-            ) {
1093
-                //Events Edit Current Event
1094
-                $admin_bar->add_menu(array(
1095
-                    'id'     => 'espresso-toolbar-events-edit',
1096
-                    'parent' => 'espresso-toolbar-events',
1097
-                    'title'  => __('Edit Event', 'event_espresso'),
1098
-                    'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'edit', 'post' => $post->ID),
1099
-                        $events_admin_url),
1100
-                    'meta'   => array(
1101
-                        'title'  => __('Edit Event', 'event_espresso'),
1102
-                        'target' => '',
1103
-                        'class'  => $menu_class,
1104
-                    ),
1105
-                ));
1106
-            }
1107
-        }
1108
-        //Events View
1109
-        if ($this->registry->CAP->current_user_can('ee_read_events',
1110
-            'ee_admin_bar_menu_espresso-toolbar-events-view')
1111
-        ) {
1112
-            $admin_bar->add_menu(array(
1113
-                'id'     => 'espresso-toolbar-events-view',
1114
-                'parent' => 'espresso-toolbar-events',
1115
-                'title'  => __('View', 'event_espresso'),
1116
-                'href'   => $events_admin_url,
1117
-                'meta'   => array(
1118
-                    'title'  => __('View', 'event_espresso'),
1119
-                    'target' => '',
1120
-                    'class'  => $menu_class,
1121
-                ),
1122
-            ));
1123
-        }
1124
-        if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events-all')) {
1125
-            //Events View All
1126
-            $admin_bar->add_menu(array(
1127
-                'id'     => 'espresso-toolbar-events-all',
1128
-                'parent' => 'espresso-toolbar-events-view',
1129
-                'title'  => __('All', 'event_espresso'),
1130
-                'href'   => $events_admin_url,
1131
-                'meta'   => array(
1132
-                    'title'  => __('All', 'event_espresso'),
1133
-                    'target' => '',
1134
-                    'class'  => $menu_class,
1135
-                ),
1136
-            ));
1137
-        }
1138
-        if ($this->registry->CAP->current_user_can('ee_read_events',
1139
-            'ee_admin_bar_menu_espresso-toolbar-events-today')
1140
-        ) {
1141
-            //Events View Today
1142
-            $admin_bar->add_menu(array(
1143
-                'id'     => 'espresso-toolbar-events-today',
1144
-                'parent' => 'espresso-toolbar-events-view',
1145
-                'title'  => __('Today', 'event_espresso'),
1146
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1147
-                    $events_admin_url),
1148
-                'meta'   => array(
1149
-                    'title'  => __('Today', 'event_espresso'),
1150
-                    'target' => '',
1151
-                    'class'  => $menu_class,
1152
-                ),
1153
-            ));
1154
-        }
1155
-        if ($this->registry->CAP->current_user_can('ee_read_events',
1156
-            'ee_admin_bar_menu_espresso-toolbar-events-month')
1157
-        ) {
1158
-            //Events View This Month
1159
-            $admin_bar->add_menu(array(
1160
-                'id'     => 'espresso-toolbar-events-month',
1161
-                'parent' => 'espresso-toolbar-events-view',
1162
-                'title'  => __('This Month', 'event_espresso'),
1163
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1164
-                    $events_admin_url),
1165
-                'meta'   => array(
1166
-                    'title'  => __('This Month', 'event_espresso'),
1167
-                    'target' => '',
1168
-                    'class'  => $menu_class,
1169
-                ),
1170
-            ));
1171
-        }
1172
-        //Registration Overview
1173
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1174
-            'ee_admin_bar_menu_espresso-toolbar-registrations')
1175
-        ) {
1176
-            $admin_bar->add_menu(array(
1177
-                'id'     => 'espresso-toolbar-registrations',
1178
-                'parent' => 'espresso-toolbar',
1179
-                'title'  => __('Registrations', 'event_espresso'),
1180
-                'href'   => $reg_admin_url,
1181
-                'meta'   => array(
1182
-                    'title'  => __('Registrations', 'event_espresso'),
1183
-                    'target' => '',
1184
-                    'class'  => $menu_class,
1185
-                ),
1186
-            ));
1187
-        }
1188
-        //Registration Overview Today
1189
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1190
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today')
1191
-        ) {
1192
-            $admin_bar->add_menu(array(
1193
-                'id'     => 'espresso-toolbar-registrations-today',
1194
-                'parent' => 'espresso-toolbar-registrations',
1195
-                'title'  => __('Today', 'event_espresso'),
1196
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1197
-                    $reg_admin_url),
1198
-                'meta'   => array(
1199
-                    'title'  => __('Today', 'event_espresso'),
1200
-                    'target' => '',
1201
-                    'class'  => $menu_class,
1202
-                ),
1203
-            ));
1204
-        }
1205
-        //Registration Overview Today Completed
1206
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1207
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-approved')
1208
-        ) {
1209
-            $admin_bar->add_menu(array(
1210
-                'id'     => 'espresso-toolbar-registrations-today-approved',
1211
-                'parent' => 'espresso-toolbar-registrations-today',
1212
-                'title'  => __('Approved', 'event_espresso'),
1213
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1214
-                    'action'      => 'default',
1215
-                    'status'      => 'today',
1216
-                    '_reg_status' => EEM_Registration::status_id_approved,
1217
-                ), $reg_admin_url),
1218
-                'meta'   => array(
1219
-                    'title'  => __('Approved', 'event_espresso'),
1220
-                    'target' => '',
1221
-                    'class'  => $menu_class,
1222
-                ),
1223
-            ));
1224
-        }
1225
-        //Registration Overview Today Pending\
1226
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1227
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-pending')
1228
-        ) {
1229
-            $admin_bar->add_menu(array(
1230
-                'id'     => 'espresso-toolbar-registrations-today-pending',
1231
-                'parent' => 'espresso-toolbar-registrations-today',
1232
-                'title'  => __('Pending', 'event_espresso'),
1233
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1234
-                    'action'     => 'default',
1235
-                    'status'     => 'today',
1236
-                    'reg_status' => EEM_Registration::status_id_pending_payment,
1237
-                ), $reg_admin_url),
1238
-                'meta'   => array(
1239
-                    'title'  => __('Pending Payment', 'event_espresso'),
1240
-                    'target' => '',
1241
-                    'class'  => $menu_class,
1242
-                ),
1243
-            ));
1244
-        }
1245
-        //Registration Overview Today Incomplete
1246
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1247
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-not-approved')
1248
-        ) {
1249
-            $admin_bar->add_menu(array(
1250
-                'id'     => 'espresso-toolbar-registrations-today-not-approved',
1251
-                'parent' => 'espresso-toolbar-registrations-today',
1252
-                'title'  => __('Not Approved', 'event_espresso'),
1253
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1254
-                    'action'      => 'default',
1255
-                    'status'      => 'today',
1256
-                    '_reg_status' => EEM_Registration::status_id_not_approved,
1257
-                ), $reg_admin_url),
1258
-                'meta'   => array(
1259
-                    'title'  => __('Not Approved', 'event_espresso'),
1260
-                    'target' => '',
1261
-                    'class'  => $menu_class,
1262
-                ),
1263
-            ));
1264
-        }
1265
-        //Registration Overview Today Incomplete
1266
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1267
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-cancelled')
1268
-        ) {
1269
-            $admin_bar->add_menu(array(
1270
-                'id'     => 'espresso-toolbar-registrations-today-cancelled',
1271
-                'parent' => 'espresso-toolbar-registrations-today',
1272
-                'title'  => __('Cancelled', 'event_espresso'),
1273
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1274
-                    'action'      => 'default',
1275
-                    'status'      => 'today',
1276
-                    '_reg_status' => EEM_Registration::status_id_cancelled,
1277
-                ), $reg_admin_url),
1278
-                'meta'   => array(
1279
-                    'title'  => __('Cancelled', 'event_espresso'),
1280
-                    'target' => '',
1281
-                    'class'  => $menu_class,
1282
-                ),
1283
-            ));
1284
-        }
1285
-        //Registration Overview This Month
1286
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1287
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month')
1288
-        ) {
1289
-            $admin_bar->add_menu(array(
1290
-                'id'     => 'espresso-toolbar-registrations-month',
1291
-                'parent' => 'espresso-toolbar-registrations',
1292
-                'title'  => __('This Month', 'event_espresso'),
1293
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1294
-                    $reg_admin_url),
1295
-                'meta'   => array(
1296
-                    'title'  => __('This Month', 'event_espresso'),
1297
-                    'target' => '',
1298
-                    'class'  => $menu_class,
1299
-                ),
1300
-            ));
1301
-        }
1302
-        //Registration Overview This Month Approved
1303
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1304
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-approved')
1305
-        ) {
1306
-            $admin_bar->add_menu(array(
1307
-                'id'     => 'espresso-toolbar-registrations-month-approved',
1308
-                'parent' => 'espresso-toolbar-registrations-month',
1309
-                'title'  => __('Approved', 'event_espresso'),
1310
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1311
-                    'action'      => 'default',
1312
-                    'status'      => 'month',
1313
-                    '_reg_status' => EEM_Registration::status_id_approved,
1314
-                ), $reg_admin_url),
1315
-                'meta'   => array(
1316
-                    'title'  => __('Approved', 'event_espresso'),
1317
-                    'target' => '',
1318
-                    'class'  => $menu_class,
1319
-                ),
1320
-            ));
1321
-        }
1322
-        //Registration Overview This Month Pending
1323
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1324
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-pending')
1325
-        ) {
1326
-            $admin_bar->add_menu(array(
1327
-                'id'     => 'espresso-toolbar-registrations-month-pending',
1328
-                'parent' => 'espresso-toolbar-registrations-month',
1329
-                'title'  => __('Pending', 'event_espresso'),
1330
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1331
-                    'action'      => 'default',
1332
-                    'status'      => 'month',
1333
-                    '_reg_status' => EEM_Registration::status_id_pending_payment,
1334
-                ), $reg_admin_url),
1335
-                'meta'   => array(
1336
-                    'title'  => __('Pending', 'event_espresso'),
1337
-                    'target' => '',
1338
-                    'class'  => $menu_class,
1339
-                ),
1340
-            ));
1341
-        }
1342
-        //Registration Overview This Month Not Approved
1343
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1344
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-not-approved')
1345
-        ) {
1346
-            $admin_bar->add_menu(array(
1347
-                'id'     => 'espresso-toolbar-registrations-month-not-approved',
1348
-                'parent' => 'espresso-toolbar-registrations-month',
1349
-                'title'  => __('Not Approved', 'event_espresso'),
1350
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1351
-                    'action'      => 'default',
1352
-                    'status'      => 'month',
1353
-                    '_reg_status' => EEM_Registration::status_id_not_approved,
1354
-                ), $reg_admin_url),
1355
-                'meta'   => array(
1356
-                    'title'  => __('Not Approved', 'event_espresso'),
1357
-                    'target' => '',
1358
-                    'class'  => $menu_class,
1359
-                ),
1360
-            ));
1361
-        }
1362
-        //Registration Overview This Month Cancelled
1363
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1364
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-cancelled')
1365
-        ) {
1366
-            $admin_bar->add_menu(array(
1367
-                'id'     => 'espresso-toolbar-registrations-month-cancelled',
1368
-                'parent' => 'espresso-toolbar-registrations-month',
1369
-                'title'  => __('Cancelled', 'event_espresso'),
1370
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1371
-                    'action'      => 'default',
1372
-                    'status'      => 'month',
1373
-                    '_reg_status' => EEM_Registration::status_id_cancelled,
1374
-                ), $reg_admin_url),
1375
-                'meta'   => array(
1376
-                    'title'  => __('Cancelled', 'event_espresso'),
1377
-                    'target' => '',
1378
-                    'class'  => $menu_class,
1379
-                ),
1380
-            ));
1381
-        }
1382
-        //Extensions & Services
1383
-        if ($this->registry->CAP->current_user_can('ee_read_ee',
1384
-            'ee_admin_bar_menu_espresso-toolbar-extensions-and-services')
1385
-        ) {
1386
-            $admin_bar->add_menu(array(
1387
-                'id'     => 'espresso-toolbar-extensions-and-services',
1388
-                'parent' => 'espresso-toolbar',
1389
-                'title'  => __('Extensions & Services', 'event_espresso'),
1390
-                'href'   => $extensions_admin_url,
1391
-                'meta'   => array(
1392
-                    'title'  => __('Extensions & Services', 'event_espresso'),
1393
-                    'target' => '',
1394
-                    'class'  => $menu_class,
1395
-                ),
1396
-            ));
1397
-        }
1398
-    }
1399
-
1400
-
1401
-
1402
-    /**
1403
-     * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1404
-     * never returned with the function.
1405
-     *
1406
-     * @param  array $exclude_array any existing pages being excluded are in this array.
1407
-     * @return array
1408
-     */
1409
-    public function remove_pages_from_wp_list_pages($exclude_array)
1410
-    {
1411
-        return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1412
-    }
1413
-
1414
-
1415
-
1416
-
1417
-
1418
-
1419
-    /***********************************************        WP_ENQUEUE_SCRIPTS HOOK         ***********************************************/
1420
-    /**
1421
-     *    wp_enqueue_scripts
1422
-     *
1423
-     * @access    public
1424
-     * @return    void
1425
-     */
1426
-    public function wp_enqueue_scripts()
1427
-    {
1428
-        // unlike other systems, EE_System_scripts loading is turned ON by default, but prior to the init hook, can be turned off via: add_filter( 'FHEE_load_EE_System_scripts', '__return_false' );
1429
-        if (apply_filters('FHEE_load_EE_System_scripts', true)) {
1430
-            // jquery_validate loading is turned OFF by default, but prior to the wp_enqueue_scripts hook, can be turned back on again via:  add_filter( 'FHEE_load_jquery_validate', '__return_true' );
1431
-            if (apply_filters('FHEE_load_jquery_validate', false)) {
1432
-                // register jQuery Validate and additional methods
1433
-                wp_register_script('jquery-validate', EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
1434
-                    array('jquery'), '1.15.0', true);
1435
-                wp_register_script('jquery-validate-extra-methods',
1436
-                    EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
1437
-                    array('jquery', 'jquery-validate'), '1.15.0', true);
1438
-            }
1439
-        }
1440
-    }
19
+	/**
20
+	 * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
21
+	 * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
22
+	 */
23
+	const req_type_normal = 0;
24
+
25
+	/**
26
+	 * Indicates this is a brand new installation of EE so we should install
27
+	 * tables and default data etc
28
+	 */
29
+	const req_type_new_activation = 1;
30
+
31
+	/**
32
+	 * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
33
+	 * and we just exited maintenance mode). We MUST check the database is setup properly
34
+	 * and that default data is setup too
35
+	 */
36
+	const req_type_reactivation = 2;
37
+
38
+	/**
39
+	 * indicates that EE has been upgraded since its previous request.
40
+	 * We may have data migration scripts to call and will want to trigger maintenance mode
41
+	 */
42
+	const req_type_upgrade = 3;
43
+
44
+	/**
45
+	 * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
46
+	 */
47
+	const req_type_downgrade = 4;
48
+
49
+	/**
50
+	 * @deprecated since version 4.6.0.dev.006
51
+	 * Now whenever a new_activation is detected the request type is still just
52
+	 * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
53
+	 * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
54
+	 * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
55
+	 * (Specifically, when the migration manager indicates migrations are finished
56
+	 * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
57
+	 */
58
+	const req_type_activation_but_not_installed = 5;
59
+
60
+	/**
61
+	 * option prefix for recording the activation history (like core's "espresso_db_update") of addons
62
+	 */
63
+	const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
64
+
65
+
66
+	/**
67
+	 *    instance of the EE_System object
68
+	 *
69
+	 * @var    $_instance
70
+	 * @access    private
71
+	 */
72
+	private static $_instance = null;
73
+
74
+	/**
75
+	 * @type  EE_Registry $Registry
76
+	 * @access    protected
77
+	 */
78
+	protected $registry;
79
+
80
+	/**
81
+	 * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
82
+	 * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
83
+	 *
84
+	 * @var int
85
+	 */
86
+	private $_req_type;
87
+
88
+	/**
89
+	 * Whether or not there was a non-micro version change in EE core version during this request
90
+	 *
91
+	 * @var boolean
92
+	 */
93
+	private $_major_version_change = false;
94
+
95
+
96
+
97
+	/**
98
+	 * @singleton method used to instantiate class object
99
+	 * @access    public
100
+	 * @param  \EE_Registry $Registry
101
+	 * @return \EE_System
102
+	 */
103
+	public static function instance(EE_Registry $Registry = null)
104
+	{
105
+		// check if class object is instantiated
106
+		if ( ! self::$_instance instanceof EE_System) {
107
+			self::$_instance = new self($Registry);
108
+		}
109
+		return self::$_instance;
110
+	}
111
+
112
+
113
+
114
+	/**
115
+	 * resets the instance and returns it
116
+	 *
117
+	 * @return EE_System
118
+	 */
119
+	public static function reset()
120
+	{
121
+		self::$_instance->_req_type = null;
122
+		//make sure none of the old hooks are left hanging around
123
+		remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
124
+		//we need to reset the migration manager in order for it to detect DMSs properly
125
+		EE_Data_Migration_Manager::reset();
126
+		self::instance()->detect_activations_or_upgrades();
127
+		self::instance()->perform_activations_upgrades_and_migrations();
128
+		return self::instance();
129
+	}
130
+
131
+
132
+
133
+	/**
134
+	 *    sets hooks for running rest of system
135
+	 *    provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
136
+	 *    starting EE Addons from any other point may lead to problems
137
+	 *
138
+	 * @access private
139
+	 * @param  \EE_Registry $Registry
140
+	 */
141
+	private function __construct(EE_Registry $Registry)
142
+	{
143
+		$this->registry = $Registry;
144
+		do_action('AHEE__EE_System__construct__begin', $this);
145
+		// allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
146
+		add_action('AHEE__EE_Bootstrap__load_espresso_addons', array($this, 'load_espresso_addons'));
147
+		// when an ee addon is activated, we want to call the core hook(s) again
148
+		// because the newly-activated addon didn't get a chance to run at all
149
+		add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
150
+		// detect whether install or upgrade
151
+		add_action('AHEE__EE_Bootstrap__detect_activations_or_upgrades', array($this, 'detect_activations_or_upgrades'),
152
+			3);
153
+		// load EE_Config, EE_Textdomain, etc
154
+		add_action('AHEE__EE_Bootstrap__load_core_configuration', array($this, 'load_core_configuration'), 5);
155
+		// load EE_Config, EE_Textdomain, etc
156
+		add_action('AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
157
+			array($this, 'register_shortcodes_modules_and_widgets'), 7);
158
+		// you wanna get going? I wanna get going... let's get going!
159
+		add_action('AHEE__EE_Bootstrap__brew_espresso', array($this, 'brew_espresso'), 9);
160
+		//other housekeeping
161
+		//exclude EE critical pages from wp_list_pages
162
+		add_filter('wp_list_pages_excludes', array($this, 'remove_pages_from_wp_list_pages'), 10);
163
+		// ALL EE Addons should use the following hook point to attach their initial setup too
164
+		// it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
165
+		do_action('AHEE__EE_System__construct__complete', $this);
166
+	}
167
+
168
+
169
+
170
+	/**
171
+	 * load_espresso_addons
172
+	 * allow addons to load first so that they can set hooks for running DMS's, etc
173
+	 * this is hooked into both:
174
+	 *    'AHEE__EE_Bootstrap__load_core_configuration'
175
+	 *        which runs during the WP 'plugins_loaded' action at priority 5
176
+	 *    and the WP 'activate_plugin' hookpoint
177
+	 *
178
+	 * @access public
179
+	 * @return void
180
+	 */
181
+	public function load_espresso_addons()
182
+	{
183
+		// set autoloaders for all of the classes implementing EEI_Plugin_API
184
+		// which provide helpers for EE plugin authors to more easily register certain components with EE.
185
+		EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
186
+		//load and setup EE_Capabilities
187
+		$this->registry->load_core('Capabilities');
188
+		//caps need to be initialized on every request so that capability maps are set.
189
+		//@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
190
+		$this->registry->CAP->init_caps();
191
+		do_action('AHEE__EE_System__load_espresso_addons');
192
+		//if the WP API basic auth plugin isn't already loaded, load it now.
193
+		//We want it for mobile apps. Just include the entire plugin
194
+		//also, don't load the basic auth when a plugin is getting activated, because
195
+		//it could be the basic auth plugin, and it doesn't check if its methods are already defined
196
+		//and causes a fatal error
197
+		if ( ! function_exists('json_basic_auth_handler')
198
+			 && ! function_exists('json_basic_auth_error')
199
+			 && ! (
200
+				isset($_GET['action'])
201
+				&& in_array($_GET['action'], array('activate', 'activate-selected'))
202
+			)
203
+			 && ! (
204
+				isset($_GET['activate'])
205
+				&& $_GET['activate'] === 'true'
206
+			)
207
+		) {
208
+			include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
209
+		}
210
+		do_action('AHEE__EE_System__load_espresso_addons__complete');
211
+	}
212
+
213
+
214
+
215
+	/**
216
+	 * detect_activations_or_upgrades
217
+	 * Checks for activation or upgrade of core first;
218
+	 * then also checks if any registered addons have been activated or upgraded
219
+	 * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
220
+	 * which runs during the WP 'plugins_loaded' action at priority 3
221
+	 *
222
+	 * @access public
223
+	 * @return void
224
+	 */
225
+	public function detect_activations_or_upgrades()
226
+	{
227
+		//first off: let's make sure to handle core
228
+		$this->detect_if_activation_or_upgrade();
229
+		foreach ($this->registry->addons as $addon) {
230
+			//detect teh request type for that addon
231
+			$addon->detect_activation_or_upgrade();
232
+		}
233
+	}
234
+
235
+
236
+
237
+	/**
238
+	 * detect_if_activation_or_upgrade
239
+	 * Takes care of detecting whether this is a brand new install or code upgrade,
240
+	 * and either setting up the DB or setting up maintenance mode etc.
241
+	 *
242
+	 * @access public
243
+	 * @return void
244
+	 */
245
+	public function detect_if_activation_or_upgrade()
246
+	{
247
+		do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
248
+		// load M-Mode class
249
+		$this->registry->load_core('Maintenance_Mode');
250
+		// check if db has been updated, or if its a brand-new installation
251
+		$espresso_db_update = $this->fix_espresso_db_upgrade_option();
252
+		$request_type = $this->detect_req_type($espresso_db_update);
253
+		//EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
254
+		switch ($request_type) {
255
+			case EE_System::req_type_new_activation:
256
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
257
+				$this->_handle_core_version_change($espresso_db_update);
258
+				break;
259
+			case EE_System::req_type_reactivation:
260
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
261
+				$this->_handle_core_version_change($espresso_db_update);
262
+				break;
263
+			case EE_System::req_type_upgrade:
264
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
265
+				//migrations may be required now that we've upgraded
266
+				EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
267
+				$this->_handle_core_version_change($espresso_db_update);
268
+				//				echo "done upgrade";die;
269
+				break;
270
+			case EE_System::req_type_downgrade:
271
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
272
+				//its possible migrations are no longer required
273
+				EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
274
+				$this->_handle_core_version_change($espresso_db_update);
275
+				break;
276
+			case EE_System::req_type_normal:
277
+			default:
278
+				//				$this->_maybe_redirect_to_ee_about();
279
+				break;
280
+		}
281
+		do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
282
+	}
283
+
284
+
285
+
286
+	/**
287
+	 * Updates the list of installed versions and sets hooks for
288
+	 * initializing the database later during the request
289
+	 *
290
+	 * @param array $espresso_db_update
291
+	 */
292
+	protected function _handle_core_version_change($espresso_db_update)
293
+	{
294
+		$this->update_list_of_installed_versions($espresso_db_update);
295
+		//get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
296
+		add_action('AHEE__EE_System__perform_activations_upgrades_and_migrations',
297
+			array($this, 'initialize_db_if_no_migrations_required'));
298
+	}
299
+
300
+
301
+
302
+	/**
303
+	 * standardizes the wp option 'espresso_db_upgrade' which actually stores
304
+	 * information about what versions of EE have been installed and activated,
305
+	 * NOT necessarily the state of the database
306
+	 *
307
+	 * @param null $espresso_db_update
308
+	 * @internal param array $espresso_db_update_value the value of the WordPress option. If not supplied, fetches it
309
+	 *           from the options table
310
+	 * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
311
+	 */
312
+	private function fix_espresso_db_upgrade_option($espresso_db_update = null)
313
+	{
314
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
315
+		if ( ! $espresso_db_update) {
316
+			$espresso_db_update = get_option('espresso_db_update');
317
+		}
318
+		// check that option is an array
319
+		if ( ! is_array($espresso_db_update)) {
320
+			// if option is FALSE, then it never existed
321
+			if ($espresso_db_update === false) {
322
+				// make $espresso_db_update an array and save option with autoload OFF
323
+				$espresso_db_update = array();
324
+				add_option('espresso_db_update', $espresso_db_update, '', 'no');
325
+			} else {
326
+				// option is NOT FALSE but also is NOT an array, so make it an array and save it
327
+				$espresso_db_update = array($espresso_db_update => array());
328
+				update_option('espresso_db_update', $espresso_db_update);
329
+			}
330
+		} else {
331
+			$corrected_db_update = array();
332
+			//if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
333
+			foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
334
+				if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
335
+					//the key is an int, and the value IS NOT an array
336
+					//so it must be numerically-indexed, where values are versions installed...
337
+					//fix it!
338
+					$version_string = $should_be_array;
339
+					$corrected_db_update[$version_string] = array('unknown-date');
340
+				} else {
341
+					//ok it checks out
342
+					$corrected_db_update[$should_be_version_string] = $should_be_array;
343
+				}
344
+			}
345
+			$espresso_db_update = $corrected_db_update;
346
+			update_option('espresso_db_update', $espresso_db_update);
347
+		}
348
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
349
+		return $espresso_db_update;
350
+	}
351
+
352
+
353
+
354
+	/**
355
+	 * Does the traditional work of setting up the plugin's database and adding default data.
356
+	 * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
357
+	 * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
358
+	 * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
359
+	 * so that it will be done when migrations are finished
360
+	 *
361
+	 * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
362
+	 * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
363
+	 *                                       This is a resource-intensive job
364
+	 *                                       so we prefer to only do it when necessary
365
+	 * @return void
366
+	 */
367
+	public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
368
+	{
369
+		$request_type = $this->detect_req_type();
370
+		//only initialize system if we're not in maintenance mode.
371
+		if (EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance) {
372
+			update_option('ee_flush_rewrite_rules', true);
373
+			if ($verify_schema) {
374
+				EEH_Activation::initialize_db_and_folders();
375
+			}
376
+			EEH_Activation::initialize_db_content();
377
+			EEH_Activation::system_initialization();
378
+			if ($initialize_addons_too) {
379
+				$this->initialize_addons();
380
+			}
381
+		} else {
382
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
383
+		}
384
+		if ($request_type === EE_System::req_type_new_activation
385
+			|| $request_type === EE_System::req_type_reactivation
386
+			|| (
387
+				$request_type === EE_System::req_type_upgrade
388
+				&& $this->is_major_version_change()
389
+			)
390
+		) {
391
+			add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
392
+		}
393
+	}
394
+
395
+
396
+
397
+	/**
398
+	 * Initializes the db for all registered addons
399
+	 */
400
+	public function initialize_addons()
401
+	{
402
+		//foreach registered addon, make sure its db is up-to-date too
403
+		foreach ($this->registry->addons as $addon) {
404
+			$addon->initialize_db_if_no_migrations_required();
405
+		}
406
+	}
407
+
408
+
409
+
410
+	/**
411
+	 * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
412
+	 *
413
+	 * @param    array  $version_history
414
+	 * @param    string $current_version_to_add version to be added to the version history
415
+	 * @return    boolean success as to whether or not this option was changed
416
+	 */
417
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
418
+	{
419
+		if ( ! $version_history) {
420
+			$version_history = $this->fix_espresso_db_upgrade_option($version_history);
421
+		}
422
+		if ($current_version_to_add == null) {
423
+			$current_version_to_add = espresso_version();
424
+		}
425
+		$version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
426
+		// re-save
427
+		return update_option('espresso_db_update', $version_history);
428
+	}
429
+
430
+
431
+
432
+	/**
433
+	 * Detects if the current version indicated in the has existed in the list of
434
+	 * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
435
+	 *
436
+	 * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
437
+	 *                                  If not supplied, fetches it from the options table.
438
+	 *                                  Also, caches its result so later parts of the code can also know whether
439
+	 *                                  there's been an update or not. This way we can add the current version to
440
+	 *                                  espresso_db_update, but still know if this is a new install or not
441
+	 * @return int one of the constants on EE_System::req_type_
442
+	 */
443
+	public function detect_req_type($espresso_db_update = null)
444
+	{
445
+		if ($this->_req_type === null) {
446
+			$espresso_db_update = ! empty($espresso_db_update) ? $espresso_db_update
447
+				: $this->fix_espresso_db_upgrade_option();
448
+			$this->_req_type = $this->detect_req_type_given_activation_history($espresso_db_update,
449
+				'ee_espresso_activation', espresso_version());
450
+			$this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
451
+		}
452
+		return $this->_req_type;
453
+	}
454
+
455
+
456
+
457
+	/**
458
+	 * Returns whether or not there was a non-micro version change (ie, change in either
459
+	 * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
460
+	 * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
461
+	 *
462
+	 * @param $activation_history
463
+	 * @return bool
464
+	 */
465
+	protected function _detect_major_version_change($activation_history)
466
+	{
467
+		$previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
468
+		$previous_version_parts = explode('.', $previous_version);
469
+		$current_version_parts = explode('.', espresso_version());
470
+		return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
471
+			   && ($previous_version_parts[0] !== $current_version_parts[0]
472
+				   || $previous_version_parts[1] !== $current_version_parts[1]
473
+			   );
474
+	}
475
+
476
+
477
+
478
+	/**
479
+	 * Returns true if either the major or minor version of EE changed during this request.
480
+	 * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
481
+	 *
482
+	 * @return bool
483
+	 */
484
+	public function is_major_version_change()
485
+	{
486
+		return $this->_major_version_change;
487
+	}
488
+
489
+
490
+
491
+	/**
492
+	 * Determines the request type for any ee addon, given three piece of info: the current array of activation
493
+	 * histories (for core that' 'espresso_db_update' wp option); the name of the wordpress option which is temporarily
494
+	 * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
495
+	 * just activated to (for core that will always be espresso_version())
496
+	 *
497
+	 * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
498
+	 *                                                 ee plugin. for core that's 'espresso_db_update'
499
+	 * @param string $activation_indicator_option_name the name of the wordpress option that is temporarily set to
500
+	 *                                                 indicate that this plugin was just activated
501
+	 * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
502
+	 *                                                 espresso_version())
503
+	 * @return int one of the constants on EE_System::req_type_*
504
+	 */
505
+	public static function detect_req_type_given_activation_history(
506
+		$activation_history_for_addon,
507
+		$activation_indicator_option_name,
508
+		$version_to_upgrade_to
509
+	) {
510
+		$version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
511
+		if ($activation_history_for_addon) {
512
+			//it exists, so this isn't a completely new install
513
+			//check if this version already in that list of previously installed versions
514
+			if ( ! isset($activation_history_for_addon[$version_to_upgrade_to])) {
515
+				//it a version we haven't seen before
516
+				if ($version_is_higher === 1) {
517
+					$req_type = EE_System::req_type_upgrade;
518
+				} else {
519
+					$req_type = EE_System::req_type_downgrade;
520
+				}
521
+				delete_option($activation_indicator_option_name);
522
+			} else {
523
+				// its not an update. maybe a reactivation?
524
+				if (get_option($activation_indicator_option_name, false)) {
525
+					if ($version_is_higher === -1) {
526
+						$req_type = EE_System::req_type_downgrade;
527
+					} elseif ($version_is_higher === 0) {
528
+						//we've seen this version before, but it's an activation. must be a reactivation
529
+						$req_type = EE_System::req_type_reactivation;
530
+					} else {//$version_is_higher === 1
531
+						$req_type = EE_System::req_type_upgrade;
532
+					}
533
+					delete_option($activation_indicator_option_name);
534
+				} else {
535
+					//we've seen this version before and the activation indicate doesn't show it was just activated
536
+					if ($version_is_higher === -1) {
537
+						$req_type = EE_System::req_type_downgrade;
538
+					} elseif ($version_is_higher === 0) {
539
+						//we've seen this version before and it's not an activation. its normal request
540
+						$req_type = EE_System::req_type_normal;
541
+					} else {//$version_is_higher === 1
542
+						$req_type = EE_System::req_type_upgrade;
543
+					}
544
+				}
545
+			}
546
+		} else {
547
+			//brand new install
548
+			$req_type = EE_System::req_type_new_activation;
549
+			delete_option($activation_indicator_option_name);
550
+		}
551
+		return $req_type;
552
+	}
553
+
554
+
555
+
556
+	/**
557
+	 * Detects if the $version_to_upgrade_to is higher than the most recent version in
558
+	 * the $activation_history_for_addon
559
+	 *
560
+	 * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
561
+	 *                                             sometimes containing 'unknown-date'
562
+	 * @param string $version_to_upgrade_to        (current version)
563
+	 * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
564
+	 *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
565
+	 *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
566
+	 *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
567
+	 */
568
+	protected static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
569
+	{
570
+		//find the most recently-activated version
571
+		$most_recently_active_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
572
+		return version_compare($version_to_upgrade_to, $most_recently_active_version);
573
+	}
574
+
575
+
576
+
577
+	/**
578
+	 * Gets the most recently active version listed in the activation history,
579
+	 * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
580
+	 *
581
+	 * @param array $activation_history  (keys are versions, values are arrays of times activated,
582
+	 *                                   sometimes containing 'unknown-date'
583
+	 * @return string
584
+	 */
585
+	protected static function _get_most_recently_active_version_from_activation_history($activation_history)
586
+	{
587
+		$most_recently_active_version_activation = '1970-01-01 00:00:00';
588
+		$most_recently_active_version = '0.0.0.dev.000';
589
+		if (is_array($activation_history)) {
590
+			foreach ($activation_history as $version => $times_activated) {
591
+				//check there is a record of when this version was activated. Otherwise,
592
+				//mark it as unknown
593
+				if ( ! $times_activated) {
594
+					$times_activated = array('unknown-date');
595
+				}
596
+				if (is_string($times_activated)) {
597
+					$times_activated = array($times_activated);
598
+				}
599
+				foreach ($times_activated as $an_activation) {
600
+					if ($an_activation != 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
601
+						$most_recently_active_version = $version;
602
+						$most_recently_active_version_activation = $an_activation == 'unknown-date'
603
+							? '1970-01-01 00:00:00' : $an_activation;
604
+					}
605
+				}
606
+			}
607
+		}
608
+		return $most_recently_active_version;
609
+	}
610
+
611
+
612
+
613
+	/**
614
+	 * This redirects to the about EE page after activation
615
+	 *
616
+	 * @return void
617
+	 */
618
+	public function redirect_to_about_ee()
619
+	{
620
+		$notices = EE_Error::get_notices(false);
621
+		//if current user is an admin and it's not an ajax or rest request
622
+		if (
623
+			! (defined('DOING_AJAX') && DOING_AJAX)
624
+			&& ! (defined('REST_REQUEST') && REST_REQUEST)
625
+			&& ! isset($notices['errors'])
626
+			&& apply_filters(
627
+				'FHEE__EE_System__redirect_to_about_ee__do_redirect',
628
+				$this->registry->CAP->current_user_can('manage_options', 'espresso_about_default')
629
+			)
630
+		) {
631
+			$query_params = array('page' => 'espresso_about');
632
+			if (EE_System::instance()->detect_req_type() == EE_System::req_type_new_activation) {
633
+				$query_params['new_activation'] = true;
634
+			}
635
+			if (EE_System::instance()->detect_req_type() == EE_System::req_type_reactivation) {
636
+				$query_params['reactivation'] = true;
637
+			}
638
+			$url = add_query_arg($query_params, admin_url('admin.php'));
639
+			wp_safe_redirect($url);
640
+			exit();
641
+		}
642
+	}
643
+
644
+
645
+
646
+	/**
647
+	 * load_core_configuration
648
+	 * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
649
+	 * which runs during the WP 'plugins_loaded' action at priority 5
650
+	 *
651
+	 * @return void
652
+	 */
653
+	public function load_core_configuration()
654
+	{
655
+		do_action('AHEE__EE_System__load_core_configuration__begin', $this);
656
+		$this->registry->load_core('EE_Load_Textdomain');
657
+		//load textdomain
658
+		EE_Load_Textdomain::load_textdomain();
659
+		// load and setup EE_Config and EE_Network_Config
660
+		$this->registry->load_core('Config');
661
+		$this->registry->load_core('Network_Config');
662
+		// setup autoloaders
663
+		// enable logging?
664
+		if ($this->registry->CFG->admin->use_full_logging) {
665
+			$this->registry->load_core('Log');
666
+		}
667
+		// check for activation errors
668
+		$activation_errors = get_option('ee_plugin_activation_errors', false);
669
+		if ($activation_errors) {
670
+			EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
671
+			update_option('ee_plugin_activation_errors', false);
672
+		}
673
+		// get model names
674
+		$this->_parse_model_names();
675
+		//load caf stuff a chance to play during the activation process too.
676
+		$this->_maybe_brew_regular();
677
+		do_action('AHEE__EE_System__load_core_configuration__complete', $this);
678
+	}
679
+
680
+
681
+
682
+	/**
683
+	 * cycles through all of the models/*.model.php files, and assembles an array of model names
684
+	 *
685
+	 * @return void
686
+	 */
687
+	private function _parse_model_names()
688
+	{
689
+		//get all the files in the EE_MODELS folder that end in .model.php
690
+		$models = glob(EE_MODELS . '*.model.php');
691
+		$model_names = array();
692
+		$non_abstract_db_models = array();
693
+		foreach ($models as $model) {
694
+			// get model classname
695
+			$classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
696
+			$short_name = str_replace('EEM_', '', $classname);
697
+			$reflectionClass = new ReflectionClass($classname);
698
+			if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
699
+				$non_abstract_db_models[$short_name] = $classname;
700
+			}
701
+			$model_names[$short_name] = $classname;
702
+		}
703
+		$this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
704
+		$this->registry->non_abstract_db_models = apply_filters('FHEE__EE_System__parse_implemented_model_names',
705
+			$non_abstract_db_models);
706
+	}
707
+
708
+
709
+
710
+	/**
711
+	 * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
712
+	 * that need to be setup before our EE_System launches.
713
+	 *
714
+	 * @return void
715
+	 */
716
+	private function _maybe_brew_regular()
717
+	{
718
+		if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
719
+			require_once EE_CAFF_PATH . 'brewing_regular.php';
720
+		}
721
+	}
722
+
723
+
724
+
725
+	/**
726
+	 * register_shortcodes_modules_and_widgets
727
+	 * generate lists of shortcodes and modules, then verify paths and classes
728
+	 * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
729
+	 * which runs during the WP 'plugins_loaded' action at priority 7
730
+	 *
731
+	 * @access public
732
+	 * @return void
733
+	 */
734
+	public function register_shortcodes_modules_and_widgets()
735
+	{
736
+		do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
737
+		// check for addons using old hookpoint
738
+		if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
739
+			$this->_incompatible_addon_error();
740
+		}
741
+	}
742
+
743
+
744
+
745
+	/**
746
+	 * _incompatible_addon_error
747
+	 *
748
+	 * @access public
749
+	 * @return void
750
+	 */
751
+	private function _incompatible_addon_error()
752
+	{
753
+		// get array of classes hooking into here
754
+		$class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook('AHEE__EE_System__register_shortcodes_modules_and_addons');
755
+		if ( ! empty($class_names)) {
756
+			$msg = __('The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
757
+				'event_espresso');
758
+			$msg .= '<ul>';
759
+			foreach ($class_names as $class_name) {
760
+				$msg .= '<li><b>Event Espresso - ' . str_replace(array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
761
+						$class_name) . '</b></li>';
762
+			}
763
+			$msg .= '</ul>';
764
+			$msg .= __('Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
765
+				'event_espresso');
766
+			// save list of incompatible addons to wp-options for later use
767
+			add_option('ee_incompatible_addons', $class_names, '', 'no');
768
+			if (is_admin()) {
769
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
770
+			}
771
+		}
772
+	}
773
+
774
+
775
+
776
+	/**
777
+	 * brew_espresso
778
+	 * begins the process of setting hooks for initializing EE in the correct order
779
+	 * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hookpoint
780
+	 * which runs during the WP 'plugins_loaded' action at priority 9
781
+	 *
782
+	 * @return void
783
+	 */
784
+	public function brew_espresso()
785
+	{
786
+		do_action('AHEE__EE_System__brew_espresso__begin', $this);
787
+		// load some final core systems
788
+		add_action('init', array($this, 'set_hooks_for_core'), 1);
789
+		add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
790
+		add_action('init', array($this, 'load_CPTs_and_session'), 5);
791
+		add_action('init', array($this, 'load_controllers'), 7);
792
+		add_action('init', array($this, 'core_loaded_and_ready'), 9);
793
+		add_action('init', array($this, 'initialize'), 10);
794
+		add_action('init', array($this, 'initialize_last'), 100);
795
+		add_action('wp_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 100);
796
+		add_action('admin_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 100);
797
+		add_action('admin_bar_menu', array($this, 'espresso_toolbar_items'), 100);
798
+		if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
799
+			// pew pew pew
800
+			$this->registry->load_core('PUE');
801
+			do_action('AHEE__EE_System__brew_espresso__after_pue_init');
802
+		}
803
+		do_action('AHEE__EE_System__brew_espresso__complete', $this);
804
+	}
805
+
806
+
807
+
808
+	/**
809
+	 *    set_hooks_for_core
810
+	 *
811
+	 * @access public
812
+	 * @return    void
813
+	 */
814
+	public function set_hooks_for_core()
815
+	{
816
+		$this->_deactivate_incompatible_addons();
817
+		do_action('AHEE__EE_System__set_hooks_for_core');
818
+	}
819
+
820
+
821
+
822
+	/**
823
+	 * Using the information gathered in EE_System::_incompatible_addon_error,
824
+	 * deactivates any addons considered incompatible with the current version of EE
825
+	 */
826
+	private function _deactivate_incompatible_addons()
827
+	{
828
+		$incompatible_addons = get_option('ee_incompatible_addons', array());
829
+		if ( ! empty($incompatible_addons)) {
830
+			$active_plugins = get_option('active_plugins', array());
831
+			foreach ($active_plugins as $active_plugin) {
832
+				foreach ($incompatible_addons as $incompatible_addon) {
833
+					if (strpos($active_plugin, $incompatible_addon) !== false) {
834
+						unset($_GET['activate']);
835
+						espresso_deactivate_plugin($active_plugin);
836
+					}
837
+				}
838
+			}
839
+		}
840
+	}
841
+
842
+
843
+
844
+	/**
845
+	 *    perform_activations_upgrades_and_migrations
846
+	 *
847
+	 * @access public
848
+	 * @return    void
849
+	 */
850
+	public function perform_activations_upgrades_and_migrations()
851
+	{
852
+		//first check if we had previously attempted to setup EE's directories but failed
853
+		if (EEH_Activation::upload_directories_incomplete()) {
854
+			EEH_Activation::create_upload_directories();
855
+		}
856
+		do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
857
+	}
858
+
859
+
860
+
861
+	/**
862
+	 *    load_CPTs_and_session
863
+	 *
864
+	 * @access public
865
+	 * @return    void
866
+	 */
867
+	public function load_CPTs_and_session()
868
+	{
869
+		do_action('AHEE__EE_System__load_CPTs_and_session__start');
870
+		// register Custom Post Types
871
+		$this->registry->load_core('Register_CPTs');
872
+		do_action('AHEE__EE_System__load_CPTs_and_session__complete');
873
+	}
874
+
875
+
876
+
877
+	/**
878
+	 * load_controllers
879
+	 * this is the best place to load any additional controllers that needs access to EE core.
880
+	 * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
881
+	 * time
882
+	 *
883
+	 * @access public
884
+	 * @return void
885
+	 */
886
+	public function load_controllers()
887
+	{
888
+		do_action('AHEE__EE_System__load_controllers__start');
889
+		// let's get it started
890
+		if ( ! is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
891
+			do_action('AHEE__EE_System__load_controllers__load_front_controllers');
892
+			$this->registry->load_core('Front_Controller', array(), false, true);
893
+		} else if ( ! EE_FRONT_AJAX) {
894
+			do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
895
+			EE_Registry::instance()->load_core('Admin');
896
+		}
897
+		do_action('AHEE__EE_System__load_controllers__complete');
898
+	}
899
+
900
+
901
+
902
+	/**
903
+	 * core_loaded_and_ready
904
+	 * all of the basic EE core should be loaded at this point and available regardless of M-Mode
905
+	 *
906
+	 * @access public
907
+	 * @return void
908
+	 */
909
+	public function core_loaded_and_ready()
910
+	{
911
+		do_action('AHEE__EE_System__core_loaded_and_ready');
912
+		do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
913
+		$this->registry->load_core('Session');
914
+		//		add_action( 'wp_loaded', array( $this, 'set_hooks_for_shortcodes_modules_and_addons' ), 1 );
915
+	}
916
+
917
+
918
+
919
+	/**
920
+	 * initialize
921
+	 * this is the best place to begin initializing client code
922
+	 *
923
+	 * @access public
924
+	 * @return void
925
+	 */
926
+	public function initialize()
927
+	{
928
+		do_action('AHEE__EE_System__initialize');
929
+	}
930
+
931
+
932
+
933
+	/**
934
+	 * initialize_last
935
+	 * this is run really late during the WP init hookpoint, and ensures that mostly everything else that needs to
936
+	 * initialize has done so
937
+	 *
938
+	 * @access public
939
+	 * @return void
940
+	 */
941
+	public function initialize_last()
942
+	{
943
+		do_action('AHEE__EE_System__initialize_last');
944
+	}
945
+
946
+
947
+
948
+	/**
949
+	 * set_hooks_for_shortcodes_modules_and_addons
950
+	 * this is the best place for other systems to set callbacks for hooking into other parts of EE
951
+	 * this happens at the very beginning of the wp_loaded hookpoint
952
+	 *
953
+	 * @access public
954
+	 * @return void
955
+	 */
956
+	public function set_hooks_for_shortcodes_modules_and_addons()
957
+	{
958
+		//		do_action( 'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons' );
959
+	}
960
+
961
+
962
+
963
+	/**
964
+	 * do_not_cache
965
+	 * sets no cache headers and defines no cache constants for WP plugins
966
+	 *
967
+	 * @access public
968
+	 * @return void
969
+	 */
970
+	public static function do_not_cache()
971
+	{
972
+		// set no cache constants
973
+		if ( ! defined('DONOTCACHEPAGE')) {
974
+			define('DONOTCACHEPAGE', true);
975
+		}
976
+		if ( ! defined('DONOTCACHCEOBJECT')) {
977
+			define('DONOTCACHCEOBJECT', true);
978
+		}
979
+		if ( ! defined('DONOTCACHEDB')) {
980
+			define('DONOTCACHEDB', true);
981
+		}
982
+		// add no cache headers
983
+		add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
984
+		// plus a little extra for nginx and Google Chrome
985
+		add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
986
+		// prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
987
+		remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
988
+	}
989
+
990
+
991
+
992
+	/**
993
+	 *    extra_nocache_headers
994
+	 *
995
+	 * @access    public
996
+	 * @param $headers
997
+	 * @return    array
998
+	 */
999
+	public static function extra_nocache_headers($headers)
1000
+	{
1001
+		// for NGINX
1002
+		$headers['X-Accel-Expires'] = 0;
1003
+		// plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1004
+		$headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1005
+		return $headers;
1006
+	}
1007
+
1008
+
1009
+
1010
+	/**
1011
+	 *    nocache_headers
1012
+	 *
1013
+	 * @access    public
1014
+	 * @return    void
1015
+	 */
1016
+	public static function nocache_headers()
1017
+	{
1018
+		nocache_headers();
1019
+	}
1020
+
1021
+
1022
+
1023
+	/**
1024
+	 *    espresso_toolbar_items
1025
+	 *
1026
+	 * @access public
1027
+	 * @param  WP_Admin_Bar $admin_bar
1028
+	 * @return void
1029
+	 */
1030
+	public function espresso_toolbar_items(WP_Admin_Bar $admin_bar)
1031
+	{
1032
+		// if in full M-Mode, or its an AJAX request, or user is NOT an admin
1033
+		if (EE_Maintenance_Mode::instance()->level() == EE_Maintenance_Mode::level_2_complete_maintenance
1034
+			|| defined('DOING_AJAX')
1035
+			|| ! $this->registry->CAP->current_user_can('ee_read_ee', 'ee_admin_bar_menu_top_level')
1036
+		) {
1037
+			return;
1038
+		}
1039
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1040
+		$menu_class = 'espresso_menu_item_class';
1041
+		//we don't use the constants EVENTS_ADMIN_URL or REG_ADMIN_URL
1042
+		//because they're only defined in each of their respective constructors
1043
+		//and this might be a frontend request, in which case they aren't available
1044
+		$events_admin_url = admin_url("admin.php?page=espresso_events");
1045
+		$reg_admin_url = admin_url("admin.php?page=espresso_registrations");
1046
+		$extensions_admin_url = admin_url("admin.php?page=espresso_packages");
1047
+		//Top Level
1048
+		$admin_bar->add_menu(array(
1049
+			'id'    => 'espresso-toolbar',
1050
+			'title' => '<span class="ee-icon ee-icon-ee-cup-thick ee-icon-size-20"></span><span class="ab-label">'
1051
+					   . _x('Event Espresso', 'admin bar menu group label', 'event_espresso')
1052
+					   . '</span>',
1053
+			'href'  => $events_admin_url,
1054
+			'meta'  => array(
1055
+				'title' => __('Event Espresso', 'event_espresso'),
1056
+				'class' => $menu_class . 'first',
1057
+			),
1058
+		));
1059
+		//Events
1060
+		if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events')) {
1061
+			$admin_bar->add_menu(array(
1062
+				'id'     => 'espresso-toolbar-events',
1063
+				'parent' => 'espresso-toolbar',
1064
+				'title'  => __('Events', 'event_espresso'),
1065
+				'href'   => $events_admin_url,
1066
+				'meta'   => array(
1067
+					'title'  => __('Events', 'event_espresso'),
1068
+					'target' => '',
1069
+					'class'  => $menu_class,
1070
+				),
1071
+			));
1072
+		}
1073
+		if ($this->registry->CAP->current_user_can('ee_edit_events', 'ee_admin_bar_menu_espresso-toolbar-events-new')) {
1074
+			//Events Add New
1075
+			$admin_bar->add_menu(array(
1076
+				'id'     => 'espresso-toolbar-events-new',
1077
+				'parent' => 'espresso-toolbar-events',
1078
+				'title'  => __('Add New', 'event_espresso'),
1079
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'create_new'), $events_admin_url),
1080
+				'meta'   => array(
1081
+					'title'  => __('Add New', 'event_espresso'),
1082
+					'target' => '',
1083
+					'class'  => $menu_class,
1084
+				),
1085
+			));
1086
+		}
1087
+		if (is_single() && (get_post_type() == 'espresso_events')) {
1088
+			//Current post
1089
+			global $post;
1090
+			if ($this->registry->CAP->current_user_can('ee_edit_event',
1091
+				'ee_admin_bar_menu_espresso-toolbar-events-edit', $post->ID)
1092
+			) {
1093
+				//Events Edit Current Event
1094
+				$admin_bar->add_menu(array(
1095
+					'id'     => 'espresso-toolbar-events-edit',
1096
+					'parent' => 'espresso-toolbar-events',
1097
+					'title'  => __('Edit Event', 'event_espresso'),
1098
+					'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'edit', 'post' => $post->ID),
1099
+						$events_admin_url),
1100
+					'meta'   => array(
1101
+						'title'  => __('Edit Event', 'event_espresso'),
1102
+						'target' => '',
1103
+						'class'  => $menu_class,
1104
+					),
1105
+				));
1106
+			}
1107
+		}
1108
+		//Events View
1109
+		if ($this->registry->CAP->current_user_can('ee_read_events',
1110
+			'ee_admin_bar_menu_espresso-toolbar-events-view')
1111
+		) {
1112
+			$admin_bar->add_menu(array(
1113
+				'id'     => 'espresso-toolbar-events-view',
1114
+				'parent' => 'espresso-toolbar-events',
1115
+				'title'  => __('View', 'event_espresso'),
1116
+				'href'   => $events_admin_url,
1117
+				'meta'   => array(
1118
+					'title'  => __('View', 'event_espresso'),
1119
+					'target' => '',
1120
+					'class'  => $menu_class,
1121
+				),
1122
+			));
1123
+		}
1124
+		if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events-all')) {
1125
+			//Events View All
1126
+			$admin_bar->add_menu(array(
1127
+				'id'     => 'espresso-toolbar-events-all',
1128
+				'parent' => 'espresso-toolbar-events-view',
1129
+				'title'  => __('All', 'event_espresso'),
1130
+				'href'   => $events_admin_url,
1131
+				'meta'   => array(
1132
+					'title'  => __('All', 'event_espresso'),
1133
+					'target' => '',
1134
+					'class'  => $menu_class,
1135
+				),
1136
+			));
1137
+		}
1138
+		if ($this->registry->CAP->current_user_can('ee_read_events',
1139
+			'ee_admin_bar_menu_espresso-toolbar-events-today')
1140
+		) {
1141
+			//Events View Today
1142
+			$admin_bar->add_menu(array(
1143
+				'id'     => 'espresso-toolbar-events-today',
1144
+				'parent' => 'espresso-toolbar-events-view',
1145
+				'title'  => __('Today', 'event_espresso'),
1146
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1147
+					$events_admin_url),
1148
+				'meta'   => array(
1149
+					'title'  => __('Today', 'event_espresso'),
1150
+					'target' => '',
1151
+					'class'  => $menu_class,
1152
+				),
1153
+			));
1154
+		}
1155
+		if ($this->registry->CAP->current_user_can('ee_read_events',
1156
+			'ee_admin_bar_menu_espresso-toolbar-events-month')
1157
+		) {
1158
+			//Events View This Month
1159
+			$admin_bar->add_menu(array(
1160
+				'id'     => 'espresso-toolbar-events-month',
1161
+				'parent' => 'espresso-toolbar-events-view',
1162
+				'title'  => __('This Month', 'event_espresso'),
1163
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1164
+					$events_admin_url),
1165
+				'meta'   => array(
1166
+					'title'  => __('This Month', 'event_espresso'),
1167
+					'target' => '',
1168
+					'class'  => $menu_class,
1169
+				),
1170
+			));
1171
+		}
1172
+		//Registration Overview
1173
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1174
+			'ee_admin_bar_menu_espresso-toolbar-registrations')
1175
+		) {
1176
+			$admin_bar->add_menu(array(
1177
+				'id'     => 'espresso-toolbar-registrations',
1178
+				'parent' => 'espresso-toolbar',
1179
+				'title'  => __('Registrations', 'event_espresso'),
1180
+				'href'   => $reg_admin_url,
1181
+				'meta'   => array(
1182
+					'title'  => __('Registrations', 'event_espresso'),
1183
+					'target' => '',
1184
+					'class'  => $menu_class,
1185
+				),
1186
+			));
1187
+		}
1188
+		//Registration Overview Today
1189
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1190
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today')
1191
+		) {
1192
+			$admin_bar->add_menu(array(
1193
+				'id'     => 'espresso-toolbar-registrations-today',
1194
+				'parent' => 'espresso-toolbar-registrations',
1195
+				'title'  => __('Today', 'event_espresso'),
1196
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1197
+					$reg_admin_url),
1198
+				'meta'   => array(
1199
+					'title'  => __('Today', 'event_espresso'),
1200
+					'target' => '',
1201
+					'class'  => $menu_class,
1202
+				),
1203
+			));
1204
+		}
1205
+		//Registration Overview Today Completed
1206
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1207
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-approved')
1208
+		) {
1209
+			$admin_bar->add_menu(array(
1210
+				'id'     => 'espresso-toolbar-registrations-today-approved',
1211
+				'parent' => 'espresso-toolbar-registrations-today',
1212
+				'title'  => __('Approved', 'event_espresso'),
1213
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1214
+					'action'      => 'default',
1215
+					'status'      => 'today',
1216
+					'_reg_status' => EEM_Registration::status_id_approved,
1217
+				), $reg_admin_url),
1218
+				'meta'   => array(
1219
+					'title'  => __('Approved', 'event_espresso'),
1220
+					'target' => '',
1221
+					'class'  => $menu_class,
1222
+				),
1223
+			));
1224
+		}
1225
+		//Registration Overview Today Pending\
1226
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1227
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-pending')
1228
+		) {
1229
+			$admin_bar->add_menu(array(
1230
+				'id'     => 'espresso-toolbar-registrations-today-pending',
1231
+				'parent' => 'espresso-toolbar-registrations-today',
1232
+				'title'  => __('Pending', 'event_espresso'),
1233
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1234
+					'action'     => 'default',
1235
+					'status'     => 'today',
1236
+					'reg_status' => EEM_Registration::status_id_pending_payment,
1237
+				), $reg_admin_url),
1238
+				'meta'   => array(
1239
+					'title'  => __('Pending Payment', 'event_espresso'),
1240
+					'target' => '',
1241
+					'class'  => $menu_class,
1242
+				),
1243
+			));
1244
+		}
1245
+		//Registration Overview Today Incomplete
1246
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1247
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-not-approved')
1248
+		) {
1249
+			$admin_bar->add_menu(array(
1250
+				'id'     => 'espresso-toolbar-registrations-today-not-approved',
1251
+				'parent' => 'espresso-toolbar-registrations-today',
1252
+				'title'  => __('Not Approved', 'event_espresso'),
1253
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1254
+					'action'      => 'default',
1255
+					'status'      => 'today',
1256
+					'_reg_status' => EEM_Registration::status_id_not_approved,
1257
+				), $reg_admin_url),
1258
+				'meta'   => array(
1259
+					'title'  => __('Not Approved', 'event_espresso'),
1260
+					'target' => '',
1261
+					'class'  => $menu_class,
1262
+				),
1263
+			));
1264
+		}
1265
+		//Registration Overview Today Incomplete
1266
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1267
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-cancelled')
1268
+		) {
1269
+			$admin_bar->add_menu(array(
1270
+				'id'     => 'espresso-toolbar-registrations-today-cancelled',
1271
+				'parent' => 'espresso-toolbar-registrations-today',
1272
+				'title'  => __('Cancelled', 'event_espresso'),
1273
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1274
+					'action'      => 'default',
1275
+					'status'      => 'today',
1276
+					'_reg_status' => EEM_Registration::status_id_cancelled,
1277
+				), $reg_admin_url),
1278
+				'meta'   => array(
1279
+					'title'  => __('Cancelled', 'event_espresso'),
1280
+					'target' => '',
1281
+					'class'  => $menu_class,
1282
+				),
1283
+			));
1284
+		}
1285
+		//Registration Overview This Month
1286
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1287
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month')
1288
+		) {
1289
+			$admin_bar->add_menu(array(
1290
+				'id'     => 'espresso-toolbar-registrations-month',
1291
+				'parent' => 'espresso-toolbar-registrations',
1292
+				'title'  => __('This Month', 'event_espresso'),
1293
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1294
+					$reg_admin_url),
1295
+				'meta'   => array(
1296
+					'title'  => __('This Month', 'event_espresso'),
1297
+					'target' => '',
1298
+					'class'  => $menu_class,
1299
+				),
1300
+			));
1301
+		}
1302
+		//Registration Overview This Month Approved
1303
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1304
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-approved')
1305
+		) {
1306
+			$admin_bar->add_menu(array(
1307
+				'id'     => 'espresso-toolbar-registrations-month-approved',
1308
+				'parent' => 'espresso-toolbar-registrations-month',
1309
+				'title'  => __('Approved', 'event_espresso'),
1310
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1311
+					'action'      => 'default',
1312
+					'status'      => 'month',
1313
+					'_reg_status' => EEM_Registration::status_id_approved,
1314
+				), $reg_admin_url),
1315
+				'meta'   => array(
1316
+					'title'  => __('Approved', 'event_espresso'),
1317
+					'target' => '',
1318
+					'class'  => $menu_class,
1319
+				),
1320
+			));
1321
+		}
1322
+		//Registration Overview This Month Pending
1323
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1324
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-pending')
1325
+		) {
1326
+			$admin_bar->add_menu(array(
1327
+				'id'     => 'espresso-toolbar-registrations-month-pending',
1328
+				'parent' => 'espresso-toolbar-registrations-month',
1329
+				'title'  => __('Pending', 'event_espresso'),
1330
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1331
+					'action'      => 'default',
1332
+					'status'      => 'month',
1333
+					'_reg_status' => EEM_Registration::status_id_pending_payment,
1334
+				), $reg_admin_url),
1335
+				'meta'   => array(
1336
+					'title'  => __('Pending', 'event_espresso'),
1337
+					'target' => '',
1338
+					'class'  => $menu_class,
1339
+				),
1340
+			));
1341
+		}
1342
+		//Registration Overview This Month Not Approved
1343
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1344
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-not-approved')
1345
+		) {
1346
+			$admin_bar->add_menu(array(
1347
+				'id'     => 'espresso-toolbar-registrations-month-not-approved',
1348
+				'parent' => 'espresso-toolbar-registrations-month',
1349
+				'title'  => __('Not Approved', 'event_espresso'),
1350
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1351
+					'action'      => 'default',
1352
+					'status'      => 'month',
1353
+					'_reg_status' => EEM_Registration::status_id_not_approved,
1354
+				), $reg_admin_url),
1355
+				'meta'   => array(
1356
+					'title'  => __('Not Approved', 'event_espresso'),
1357
+					'target' => '',
1358
+					'class'  => $menu_class,
1359
+				),
1360
+			));
1361
+		}
1362
+		//Registration Overview This Month Cancelled
1363
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1364
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-cancelled')
1365
+		) {
1366
+			$admin_bar->add_menu(array(
1367
+				'id'     => 'espresso-toolbar-registrations-month-cancelled',
1368
+				'parent' => 'espresso-toolbar-registrations-month',
1369
+				'title'  => __('Cancelled', 'event_espresso'),
1370
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1371
+					'action'      => 'default',
1372
+					'status'      => 'month',
1373
+					'_reg_status' => EEM_Registration::status_id_cancelled,
1374
+				), $reg_admin_url),
1375
+				'meta'   => array(
1376
+					'title'  => __('Cancelled', 'event_espresso'),
1377
+					'target' => '',
1378
+					'class'  => $menu_class,
1379
+				),
1380
+			));
1381
+		}
1382
+		//Extensions & Services
1383
+		if ($this->registry->CAP->current_user_can('ee_read_ee',
1384
+			'ee_admin_bar_menu_espresso-toolbar-extensions-and-services')
1385
+		) {
1386
+			$admin_bar->add_menu(array(
1387
+				'id'     => 'espresso-toolbar-extensions-and-services',
1388
+				'parent' => 'espresso-toolbar',
1389
+				'title'  => __('Extensions & Services', 'event_espresso'),
1390
+				'href'   => $extensions_admin_url,
1391
+				'meta'   => array(
1392
+					'title'  => __('Extensions & Services', 'event_espresso'),
1393
+					'target' => '',
1394
+					'class'  => $menu_class,
1395
+				),
1396
+			));
1397
+		}
1398
+	}
1399
+
1400
+
1401
+
1402
+	/**
1403
+	 * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1404
+	 * never returned with the function.
1405
+	 *
1406
+	 * @param  array $exclude_array any existing pages being excluded are in this array.
1407
+	 * @return array
1408
+	 */
1409
+	public function remove_pages_from_wp_list_pages($exclude_array)
1410
+	{
1411
+		return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1412
+	}
1413
+
1414
+
1415
+
1416
+
1417
+
1418
+
1419
+	/***********************************************        WP_ENQUEUE_SCRIPTS HOOK         ***********************************************/
1420
+	/**
1421
+	 *    wp_enqueue_scripts
1422
+	 *
1423
+	 * @access    public
1424
+	 * @return    void
1425
+	 */
1426
+	public function wp_enqueue_scripts()
1427
+	{
1428
+		// unlike other systems, EE_System_scripts loading is turned ON by default, but prior to the init hook, can be turned off via: add_filter( 'FHEE_load_EE_System_scripts', '__return_false' );
1429
+		if (apply_filters('FHEE_load_EE_System_scripts', true)) {
1430
+			// jquery_validate loading is turned OFF by default, but prior to the wp_enqueue_scripts hook, can be turned back on again via:  add_filter( 'FHEE_load_jquery_validate', '__return_true' );
1431
+			if (apply_filters('FHEE_load_jquery_validate', false)) {
1432
+				// register jQuery Validate and additional methods
1433
+				wp_register_script('jquery-validate', EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
1434
+					array('jquery'), '1.15.0', true);
1435
+				wp_register_script('jquery-validate-extra-methods',
1436
+					EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
1437
+					array('jquery', 'jquery-validate'), '1.15.0', true);
1438
+			}
1439
+		}
1440
+	}
1441 1441
 
1442 1442
 
1443 1443
 
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
     {
183 183
         // set autoloaders for all of the classes implementing EEI_Plugin_API
184 184
         // which provide helpers for EE plugin authors to more easily register certain components with EE.
185
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
185
+        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES.'plugin_api');
186 186
         //load and setup EE_Capabilities
187 187
         $this->registry->load_core('Capabilities');
188 188
         //caps need to be initialized on every request so that capability maps are set.
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
                 && $_GET['activate'] === 'true'
206 206
             )
207 207
         ) {
208
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
208
+            include_once EE_THIRD_PARTY.'wp-api-basic-auth'.DS.'basic-auth.php';
209 209
         }
210 210
         do_action('AHEE__EE_System__load_espresso_addons__complete');
211 211
     }
@@ -687,7 +687,7 @@  discard block
 block discarded – undo
687 687
     private function _parse_model_names()
688 688
     {
689 689
         //get all the files in the EE_MODELS folder that end in .model.php
690
-        $models = glob(EE_MODELS . '*.model.php');
690
+        $models = glob(EE_MODELS.'*.model.php');
691 691
         $model_names = array();
692 692
         $non_abstract_db_models = array();
693 693
         foreach ($models as $model) {
@@ -715,8 +715,8 @@  discard block
 block discarded – undo
715 715
      */
716 716
     private function _maybe_brew_regular()
717 717
     {
718
-        if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
719
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
718
+        if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH.'brewing_regular.php')) {
719
+            require_once EE_CAFF_PATH.'brewing_regular.php';
720 720
         }
721 721
     }
722 722
 
@@ -757,8 +757,8 @@  discard block
 block discarded – undo
757 757
                 'event_espresso');
758 758
             $msg .= '<ul>';
759 759
             foreach ($class_names as $class_name) {
760
-                $msg .= '<li><b>Event Espresso - ' . str_replace(array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
761
-                        $class_name) . '</b></li>';
760
+                $msg .= '<li><b>Event Espresso - '.str_replace(array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
761
+                        $class_name).'</b></li>';
762 762
             }
763 763
             $msg .= '</ul>';
764 764
             $msg .= __('Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
@@ -1053,7 +1053,7 @@  discard block
 block discarded – undo
1053 1053
             'href'  => $events_admin_url,
1054 1054
             'meta'  => array(
1055 1055
                 'title' => __('Event Espresso', 'event_espresso'),
1056
-                'class' => $menu_class . 'first',
1056
+                'class' => $menu_class.'first',
1057 1057
             ),
1058 1058
         ));
1059 1059
         //Events
@@ -1430,10 +1430,10 @@  discard block
 block discarded – undo
1430 1430
             // jquery_validate loading is turned OFF by default, but prior to the wp_enqueue_scripts hook, can be turned back on again via:  add_filter( 'FHEE_load_jquery_validate', '__return_true' );
1431 1431
             if (apply_filters('FHEE_load_jquery_validate', false)) {
1432 1432
                 // register jQuery Validate and additional methods
1433
-                wp_register_script('jquery-validate', EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
1433
+                wp_register_script('jquery-validate', EE_GLOBAL_ASSETS_URL.'scripts/jquery.validate.min.js',
1434 1434
                     array('jquery'), '1.15.0', true);
1435 1435
                 wp_register_script('jquery-validate-extra-methods',
1436
-                    EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
1436
+                    EE_GLOBAL_ASSETS_URL.'scripts/jquery.validate.additional-methods.min.js',
1437 1437
                     array('jquery', 'jquery-validate'), '1.15.0', true);
1438 1438
             }
1439 1439
         }
Please login to merge, or discard this patch.
libraries/form_sections/inputs/EE_Form_Input_With_Options_Base.input.php 2 patches
Indentation   +309 added lines, -309 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -16,314 +16,314 @@  discard block
 block discarded – undo
16 16
 class EE_Form_Input_With_Options_Base extends EE_Form_Input_Base
17 17
 {
18 18
 
19
-    /**
20
-     * array of available options to choose as an answer
21
-     *
22
-     * @var array
23
-     */
24
-    protected $_options = array();
25
-
26
-    /**
27
-     * whether to display the html_label_text above the checkbox/radio button options
28
-     *
29
-     * @var boolean
30
-     */
31
-    protected $_display_html_label_text = true;
32
-
33
-    /**
34
-     * whether to display an question option description as part of the input label
35
-     *
36
-     * @var boolean
37
-     */
38
-    protected $_use_desc_in_label = true;
39
-
40
-    /**
41
-     * strlen() result for the longest input value (what gets displayed in the label)
42
-     * this is used to apply a css class to the input label
43
-     *
44
-     * @var int
45
-     */
46
-    protected $_label_size = 0;
47
-
48
-    /**
49
-     * whether to enforce the label size value passed in the constructor
50
-     *
51
-     * @var boolean
52
-     */
53
-    protected $_enforce_label_size = false;
54
-
55
-    /**
56
-     * whether to allow multiple selections (ie, the value of this input should be an array)
57
-     * or not (ie, the value should be a simple int, string, etc)
58
-     *
59
-     * @var boolean
60
-     */
61
-    protected $_multiple_selections = false;
62
-
63
-
64
-
65
-    /**
66
-     * @param array     $answer_options
67
-     * @param array     $input_settings {
68
-     * @type int|string $label_size
69
-     * @type boolean    $display_html_label_text
70
-     *                                  }
71
-     *                                  And all the options accepted by EE_Form_Input_Base
72
-     */
73
-    public function __construct($answer_options = array(), $input_settings = array())
74
-    {
75
-        if (isset($input_settings['label_size'])) {
76
-            $this->_set_label_size($input_settings['label_size']);
77
-            if (isset($input_settings['enforce_label_size']) && $input_settings['enforce_label_size']) {
78
-                $this->_enforce_label_size = true;
79
-            }
80
-        }
81
-        if (isset($input_settings['display_html_label_text'])) {
82
-            $this->set_display_html_label_text($input_settings['display_html_label_text']);
83
-        }
84
-        $this->set_select_options($answer_options);
85
-        parent::__construct($input_settings);
86
-    }
87
-
88
-
89
-
90
-    /**
91
-     * Sets the allowed options for this input. Also has the side-effect of
92
-     * updating the normalization strategy to match the keys provided in the array
93
-     *
94
-     * @param array $answer_options
95
-     * @return void  just has the side-effect of setting the options for this input
96
-     */
97
-    public function set_select_options($answer_options = array())
98
-    {
99
-        $answer_options = is_array($answer_options) ? $answer_options : array($answer_options);
100
-        //get the first item in the select options and check it's type
101
-        $this->_options = reset($answer_options) instanceof EE_Question_Option
102
-            ? $this->_process_question_options($answer_options)
103
-            : $answer_options;
104
-        //d( $this->_options );
105
-        $select_option_keys = array_keys($this->_options);
106
-        // attempt to determine data type for values in order to set normalization type
107
-        if (
108
-            count($this->_options) === 2
109
-            && (
110
-                (in_array(true, $select_option_keys, true) && in_array(false, $select_option_keys, true))
111
-                || (in_array(1, $select_option_keys, true) && in_array(0, $select_option_keys, true))
112
-            )
113
-        ) {
114
-            // values appear to be boolean, like TRUE, FALSE, 1, 0
115
-            $normalization = new EE_Boolean_Normalization();
116
-        } else {
117
-            //are ALL the options ints? If so use int validation
118
-            $all_ints = true;
119
-            foreach ($select_option_keys as $value) {
120
-                //allow for a default value which may be empty.
121
-                if ( ! is_int($value) && $value !== '' && $value !== null) {
122
-                    $all_ints = false;
123
-                    break;
124
-                }
125
-            }
126
-            if ($all_ints) {
127
-                $normalization = new EE_Int_Normalization();
128
-            } else {
129
-                $normalization = new EE_Text_Normalization();
130
-            }
131
-        }
132
-        // does input type have multiple options ?
133
-        if ($this->_multiple_selections) {
134
-            $this->_set_normalization_strategy(new EE_Many_Valued_Normalization($normalization));
135
-        } else {
136
-            $this->_set_normalization_strategy($normalization);
137
-        }
138
-    }
139
-
140
-
141
-
142
-    /**
143
-     * @return array
144
-     */
145
-    public function options()
146
-    {
147
-        return $this->_options;
148
-    }
149
-
150
-
151
-
152
-    /**
153
-     * Returns an array which is guaranteed to not be multidimensional
154
-     *
155
-     * @return array
156
-     */
157
-    public function flat_options()
158
-    {
159
-        return $this->_flatten_select_options($this->options());
160
-    }
161
-
162
-
163
-
164
-    /**
165
-     * Makes sure $arr is a flat array, not a multidimensional one
166
-     *
167
-     * @param array $arr
168
-     * @return array
169
-     */
170
-    protected function _flatten_select_options($arr)
171
-    {
172
-        $flat_array = array();
173
-        if (EEH_Array::is_multi_dimensional_array($arr)) {
174
-            foreach ($arr as $sub_array) {
175
-                foreach ((array)$sub_array as $key => $value) {
176
-                    $flat_array[$key] = $value;
177
-                    $this->_set_label_size($value);
178
-                }
179
-            }
180
-        } else {
181
-            foreach ($arr as $key => $value) {
182
-                $flat_array[$key] = $value;
183
-                $this->_set_label_size($value);
184
-            }
185
-        }
186
-        return $flat_array;
187
-    }
188
-
189
-
190
-
191
-    /**
192
-     * @param EE_Question_Option[] $question_options_array
193
-     * @return array
194
-     */
195
-    protected function _process_question_options($question_options_array = array())
196
-    {
197
-        $flat_array = array();
198
-        foreach ($question_options_array as $question_option) {
199
-            if ($question_option instanceof EE_Question_Option) {
200
-                $desc = '';
201
-                if ($this->_use_desc_in_label) {
202
-                    $desc = $question_option->desc();
203
-                    $desc = ! empty($desc) ? '<span class="ee-question-option-desc">' . $desc . '</span>' : '';
204
-                }
205
-                $value = $question_option->value();
206
-                // add value even if it's empty
207
-                $flat_array[$value] = $value;
208
-                // if both value and desc are not empty, then separate with a dash
209
-                if ( ! empty($value) && ! empty($desc)) {
210
-                    $flat_array[$value] .= ' - ' . $desc;
211
-                } else {
212
-                    // otherwise, just add desc, since either or both of the vars is empty, and no dash is necessary
213
-                    $flat_array[$value] .= $desc;
214
-                }
215
-            } elseif (is_array($question_option)) {
216
-                $flat_array += $this->_flatten_select_options($question_option);
217
-            }
218
-        }
219
-        return $flat_array;
220
-    }
221
-
222
-
223
-
224
-    /**
225
-     *    set_label_sizes
226
-     *
227
-     * @return void
228
-     */
229
-    public function set_label_sizes()
230
-    {
231
-        // did the input settings specifically say to NOT set the label size dynamically ?
232
-        if ( ! $this->_enforce_label_size) {
233
-            foreach ($this->_options as $option) {
234
-                // calculate the strlen of the label
235
-                $this->_set_label_size($option);
236
-            }
237
-        }
238
-    }
239
-
240
-
241
-
242
-    /**
243
-     *    _set_label_size_class
244
-     *
245
-     * @param int|string $value
246
-     * @return void
247
-     */
248
-    private function _set_label_size($value = '')
249
-    {
250
-        // determine length of option value
251
-        $val_size = is_int($value) ? $value : strlen($value);
252
-        // use new value if bigger than existing
253
-        $this->_label_size = $val_size > $this->_label_size ? $val_size : $this->_label_size;
254
-    }
255
-
256
-
257
-
258
-    /**
259
-     *    get_label_size_class
260
-     *
261
-     * @return string
262
-     */
263
-    public function get_label_size_class()
264
-    {
265
-        $size = ' medium-lbl';
266
-        // use maximum option value length to determine label size
267
-        if ($this->_label_size < 3) {
268
-            $size = ' nano-lbl';
269
-        } else if ($this->_label_size < 6) {
270
-            $size = ' micro-lbl';
271
-        } else if ($this->_label_size < 12) {
272
-            $size = ' tiny-lbl';
273
-        } else if ($this->_label_size < 25) {
274
-            $size = ' small-lbl';
275
-        } else if ($this->_label_size < 50) {
276
-            $size = ' medium-lbl';
277
-        } else if ($this->_label_size >= 100) {
278
-            $size = ' big-lbl';
279
-        }
280
-        return $size;
281
-    }
282
-
283
-
284
-
285
-    /**
286
-     * Returns the pretty value for the normalized value
287
-     *
288
-     * @return string
289
-     */
290
-    public function pretty_value()
291
-    {
292
-        $options = $this->flat_options();
293
-        $unnormalized_value_choices = $this->get_normalization_strategy()->unnormalize($this->_normalized_value);
294
-        if ( ! $this->_multiple_selections) {
295
-            $unnormalized_value_choices = array($unnormalized_value_choices);
296
-        }
297
-        $pretty_strings = array();
298
-        foreach ((array)$unnormalized_value_choices as $unnormalized_value_choice) {
299
-            if (isset($options[$unnormalized_value_choice])) {
300
-                $pretty_strings[] = $options[$unnormalized_value_choice];
301
-            } else {
302
-                $pretty_strings[] = $this->normalized_value();
303
-            }
304
-        }
305
-        return implode(', ', $pretty_strings);
306
-    }
307
-
308
-
309
-
310
-    /**
311
-     * @return boolean
312
-     */
313
-    public function display_html_label_text()
314
-    {
315
-        return $this->_display_html_label_text;
316
-    }
317
-
318
-
319
-
320
-    /**
321
-     * @param boolean $display_html_label_text
322
-     */
323
-    public function set_display_html_label_text($display_html_label_text)
324
-    {
325
-        $this->_display_html_label_text = filter_var($display_html_label_text, FILTER_VALIDATE_BOOLEAN);
326
-    }
19
+	/**
20
+	 * array of available options to choose as an answer
21
+	 *
22
+	 * @var array
23
+	 */
24
+	protected $_options = array();
25
+
26
+	/**
27
+	 * whether to display the html_label_text above the checkbox/radio button options
28
+	 *
29
+	 * @var boolean
30
+	 */
31
+	protected $_display_html_label_text = true;
32
+
33
+	/**
34
+	 * whether to display an question option description as part of the input label
35
+	 *
36
+	 * @var boolean
37
+	 */
38
+	protected $_use_desc_in_label = true;
39
+
40
+	/**
41
+	 * strlen() result for the longest input value (what gets displayed in the label)
42
+	 * this is used to apply a css class to the input label
43
+	 *
44
+	 * @var int
45
+	 */
46
+	protected $_label_size = 0;
47
+
48
+	/**
49
+	 * whether to enforce the label size value passed in the constructor
50
+	 *
51
+	 * @var boolean
52
+	 */
53
+	protected $_enforce_label_size = false;
54
+
55
+	/**
56
+	 * whether to allow multiple selections (ie, the value of this input should be an array)
57
+	 * or not (ie, the value should be a simple int, string, etc)
58
+	 *
59
+	 * @var boolean
60
+	 */
61
+	protected $_multiple_selections = false;
62
+
63
+
64
+
65
+	/**
66
+	 * @param array     $answer_options
67
+	 * @param array     $input_settings {
68
+	 * @type int|string $label_size
69
+	 * @type boolean    $display_html_label_text
70
+	 *                                  }
71
+	 *                                  And all the options accepted by EE_Form_Input_Base
72
+	 */
73
+	public function __construct($answer_options = array(), $input_settings = array())
74
+	{
75
+		if (isset($input_settings['label_size'])) {
76
+			$this->_set_label_size($input_settings['label_size']);
77
+			if (isset($input_settings['enforce_label_size']) && $input_settings['enforce_label_size']) {
78
+				$this->_enforce_label_size = true;
79
+			}
80
+		}
81
+		if (isset($input_settings['display_html_label_text'])) {
82
+			$this->set_display_html_label_text($input_settings['display_html_label_text']);
83
+		}
84
+		$this->set_select_options($answer_options);
85
+		parent::__construct($input_settings);
86
+	}
87
+
88
+
89
+
90
+	/**
91
+	 * Sets the allowed options for this input. Also has the side-effect of
92
+	 * updating the normalization strategy to match the keys provided in the array
93
+	 *
94
+	 * @param array $answer_options
95
+	 * @return void  just has the side-effect of setting the options for this input
96
+	 */
97
+	public function set_select_options($answer_options = array())
98
+	{
99
+		$answer_options = is_array($answer_options) ? $answer_options : array($answer_options);
100
+		//get the first item in the select options and check it's type
101
+		$this->_options = reset($answer_options) instanceof EE_Question_Option
102
+			? $this->_process_question_options($answer_options)
103
+			: $answer_options;
104
+		//d( $this->_options );
105
+		$select_option_keys = array_keys($this->_options);
106
+		// attempt to determine data type for values in order to set normalization type
107
+		if (
108
+			count($this->_options) === 2
109
+			&& (
110
+				(in_array(true, $select_option_keys, true) && in_array(false, $select_option_keys, true))
111
+				|| (in_array(1, $select_option_keys, true) && in_array(0, $select_option_keys, true))
112
+			)
113
+		) {
114
+			// values appear to be boolean, like TRUE, FALSE, 1, 0
115
+			$normalization = new EE_Boolean_Normalization();
116
+		} else {
117
+			//are ALL the options ints? If so use int validation
118
+			$all_ints = true;
119
+			foreach ($select_option_keys as $value) {
120
+				//allow for a default value which may be empty.
121
+				if ( ! is_int($value) && $value !== '' && $value !== null) {
122
+					$all_ints = false;
123
+					break;
124
+				}
125
+			}
126
+			if ($all_ints) {
127
+				$normalization = new EE_Int_Normalization();
128
+			} else {
129
+				$normalization = new EE_Text_Normalization();
130
+			}
131
+		}
132
+		// does input type have multiple options ?
133
+		if ($this->_multiple_selections) {
134
+			$this->_set_normalization_strategy(new EE_Many_Valued_Normalization($normalization));
135
+		} else {
136
+			$this->_set_normalization_strategy($normalization);
137
+		}
138
+	}
139
+
140
+
141
+
142
+	/**
143
+	 * @return array
144
+	 */
145
+	public function options()
146
+	{
147
+		return $this->_options;
148
+	}
149
+
150
+
151
+
152
+	/**
153
+	 * Returns an array which is guaranteed to not be multidimensional
154
+	 *
155
+	 * @return array
156
+	 */
157
+	public function flat_options()
158
+	{
159
+		return $this->_flatten_select_options($this->options());
160
+	}
161
+
162
+
163
+
164
+	/**
165
+	 * Makes sure $arr is a flat array, not a multidimensional one
166
+	 *
167
+	 * @param array $arr
168
+	 * @return array
169
+	 */
170
+	protected function _flatten_select_options($arr)
171
+	{
172
+		$flat_array = array();
173
+		if (EEH_Array::is_multi_dimensional_array($arr)) {
174
+			foreach ($arr as $sub_array) {
175
+				foreach ((array)$sub_array as $key => $value) {
176
+					$flat_array[$key] = $value;
177
+					$this->_set_label_size($value);
178
+				}
179
+			}
180
+		} else {
181
+			foreach ($arr as $key => $value) {
182
+				$flat_array[$key] = $value;
183
+				$this->_set_label_size($value);
184
+			}
185
+		}
186
+		return $flat_array;
187
+	}
188
+
189
+
190
+
191
+	/**
192
+	 * @param EE_Question_Option[] $question_options_array
193
+	 * @return array
194
+	 */
195
+	protected function _process_question_options($question_options_array = array())
196
+	{
197
+		$flat_array = array();
198
+		foreach ($question_options_array as $question_option) {
199
+			if ($question_option instanceof EE_Question_Option) {
200
+				$desc = '';
201
+				if ($this->_use_desc_in_label) {
202
+					$desc = $question_option->desc();
203
+					$desc = ! empty($desc) ? '<span class="ee-question-option-desc">' . $desc . '</span>' : '';
204
+				}
205
+				$value = $question_option->value();
206
+				// add value even if it's empty
207
+				$flat_array[$value] = $value;
208
+				// if both value and desc are not empty, then separate with a dash
209
+				if ( ! empty($value) && ! empty($desc)) {
210
+					$flat_array[$value] .= ' - ' . $desc;
211
+				} else {
212
+					// otherwise, just add desc, since either or both of the vars is empty, and no dash is necessary
213
+					$flat_array[$value] .= $desc;
214
+				}
215
+			} elseif (is_array($question_option)) {
216
+				$flat_array += $this->_flatten_select_options($question_option);
217
+			}
218
+		}
219
+		return $flat_array;
220
+	}
221
+
222
+
223
+
224
+	/**
225
+	 *    set_label_sizes
226
+	 *
227
+	 * @return void
228
+	 */
229
+	public function set_label_sizes()
230
+	{
231
+		// did the input settings specifically say to NOT set the label size dynamically ?
232
+		if ( ! $this->_enforce_label_size) {
233
+			foreach ($this->_options as $option) {
234
+				// calculate the strlen of the label
235
+				$this->_set_label_size($option);
236
+			}
237
+		}
238
+	}
239
+
240
+
241
+
242
+	/**
243
+	 *    _set_label_size_class
244
+	 *
245
+	 * @param int|string $value
246
+	 * @return void
247
+	 */
248
+	private function _set_label_size($value = '')
249
+	{
250
+		// determine length of option value
251
+		$val_size = is_int($value) ? $value : strlen($value);
252
+		// use new value if bigger than existing
253
+		$this->_label_size = $val_size > $this->_label_size ? $val_size : $this->_label_size;
254
+	}
255
+
256
+
257
+
258
+	/**
259
+	 *    get_label_size_class
260
+	 *
261
+	 * @return string
262
+	 */
263
+	public function get_label_size_class()
264
+	{
265
+		$size = ' medium-lbl';
266
+		// use maximum option value length to determine label size
267
+		if ($this->_label_size < 3) {
268
+			$size = ' nano-lbl';
269
+		} else if ($this->_label_size < 6) {
270
+			$size = ' micro-lbl';
271
+		} else if ($this->_label_size < 12) {
272
+			$size = ' tiny-lbl';
273
+		} else if ($this->_label_size < 25) {
274
+			$size = ' small-lbl';
275
+		} else if ($this->_label_size < 50) {
276
+			$size = ' medium-lbl';
277
+		} else if ($this->_label_size >= 100) {
278
+			$size = ' big-lbl';
279
+		}
280
+		return $size;
281
+	}
282
+
283
+
284
+
285
+	/**
286
+	 * Returns the pretty value for the normalized value
287
+	 *
288
+	 * @return string
289
+	 */
290
+	public function pretty_value()
291
+	{
292
+		$options = $this->flat_options();
293
+		$unnormalized_value_choices = $this->get_normalization_strategy()->unnormalize($this->_normalized_value);
294
+		if ( ! $this->_multiple_selections) {
295
+			$unnormalized_value_choices = array($unnormalized_value_choices);
296
+		}
297
+		$pretty_strings = array();
298
+		foreach ((array)$unnormalized_value_choices as $unnormalized_value_choice) {
299
+			if (isset($options[$unnormalized_value_choice])) {
300
+				$pretty_strings[] = $options[$unnormalized_value_choice];
301
+			} else {
302
+				$pretty_strings[] = $this->normalized_value();
303
+			}
304
+		}
305
+		return implode(', ', $pretty_strings);
306
+	}
307
+
308
+
309
+
310
+	/**
311
+	 * @return boolean
312
+	 */
313
+	public function display_html_label_text()
314
+	{
315
+		return $this->_display_html_label_text;
316
+	}
317
+
318
+
319
+
320
+	/**
321
+	 * @param boolean $display_html_label_text
322
+	 */
323
+	public function set_display_html_label_text($display_html_label_text)
324
+	{
325
+		$this->_display_html_label_text = filter_var($display_html_label_text, FILTER_VALIDATE_BOOLEAN);
326
+	}
327 327
 
328 328
 
329 329
 
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
         $flat_array = array();
173 173
         if (EEH_Array::is_multi_dimensional_array($arr)) {
174 174
             foreach ($arr as $sub_array) {
175
-                foreach ((array)$sub_array as $key => $value) {
175
+                foreach ((array) $sub_array as $key => $value) {
176 176
                     $flat_array[$key] = $value;
177 177
                     $this->_set_label_size($value);
178 178
                 }
@@ -200,14 +200,14 @@  discard block
 block discarded – undo
200 200
                 $desc = '';
201 201
                 if ($this->_use_desc_in_label) {
202 202
                     $desc = $question_option->desc();
203
-                    $desc = ! empty($desc) ? '<span class="ee-question-option-desc">' . $desc . '</span>' : '';
203
+                    $desc = ! empty($desc) ? '<span class="ee-question-option-desc">'.$desc.'</span>' : '';
204 204
                 }
205 205
                 $value = $question_option->value();
206 206
                 // add value even if it's empty
207 207
                 $flat_array[$value] = $value;
208 208
                 // if both value and desc are not empty, then separate with a dash
209 209
                 if ( ! empty($value) && ! empty($desc)) {
210
-                    $flat_array[$value] .= ' - ' . $desc;
210
+                    $flat_array[$value] .= ' - '.$desc;
211 211
                 } else {
212 212
                     // otherwise, just add desc, since either or both of the vars is empty, and no dash is necessary
213 213
                     $flat_array[$value] .= $desc;
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
             $unnormalized_value_choices = array($unnormalized_value_choices);
296 296
         }
297 297
         $pretty_strings = array();
298
-        foreach ((array)$unnormalized_value_choices as $unnormalized_value_choice) {
298
+        foreach ((array) $unnormalized_value_choices as $unnormalized_value_choice) {
299 299
             if (isset($options[$unnormalized_value_choice])) {
300 300
                 $pretty_strings[] = $options[$unnormalized_value_choice];
301 301
             } else {
Please login to merge, or discard this patch.
core/libraries/rest_api/Model_Data_Translator.php 2 patches
Indentation   +481 added lines, -481 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 namespace EventEspresso\core\libraries\rest_api;
3 3
 
4 4
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5
-    exit('No direct script access allowed');
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 
8 8
 
@@ -26,485 +26,485 @@  discard block
 block discarded – undo
26 26
 class Model_Data_Translator
27 27
 {
28 28
 
29
-    /**
30
-     * We used to use -1 for infinity in the rest api, but that's ambiguous for
31
-     * fields that COULD contain -1; so we use null
32
-     */
33
-    const ee_inf_in_rest = null;
34
-
35
-
36
-
37
-    /**
38
-     * Prepares a possible array of input values from JSON for use by the models
39
-     *
40
-     * @param \EE_Model_Field_Base $field_obj
41
-     * @param mixed                $original_value_maybe_array
42
-     * @param string               $requested_version
43
-     * @param string               $timezone_string treat values as being in this timezone
44
-     * @return mixed
45
-     * @throws \DomainException
46
-     */
47
-    public static function prepare_field_values_from_json(
48
-        $field_obj,
49
-        $original_value_maybe_array,
50
-        $requested_version,
51
-        $timezone_string = 'UTC'
52
-    ) {
53
-        if (is_array($original_value_maybe_array)) {
54
-            $new_value_maybe_array = array();
55
-            foreach ($original_value_maybe_array as $array_key => $array_item) {
56
-                $new_value_maybe_array[$array_key] = Model_Data_Translator::prepare_field_value_from_json(
57
-                    $field_obj,
58
-                    $array_item,
59
-                    $requested_version,
60
-                    $timezone_string
61
-                );
62
-            }
63
-        } else {
64
-            $new_value_maybe_array = Model_Data_Translator::prepare_field_value_from_json(
65
-                $field_obj,
66
-                $original_value_maybe_array,
67
-                $requested_version,
68
-                $timezone_string
69
-            );
70
-        }
71
-        return $new_value_maybe_array;
72
-    }
73
-
74
-
75
-
76
-    /**
77
-     * Prepares an array of field values FOR use in JSON/REST API
78
-     *
79
-     * @param \EE_Model_Field_Base $field_obj
80
-     * @param mixed                $original_value_maybe_array
81
-     * @param string               $request_version (eg 4.8.36)
82
-     * @return array
83
-     */
84
-    public static function prepare_field_values_for_json($field_obj, $original_value_maybe_array, $request_version)
85
-    {
86
-        if (is_array($original_value_maybe_array)) {
87
-            $new_value_maybe_array = array();
88
-            foreach ($original_value_maybe_array as $array_key => $array_item) {
89
-                $new_value_maybe_array[$array_key] = Model_Data_Translator::prepare_field_value_for_json(
90
-                    $field_obj,
91
-                    $array_item,
92
-                    $request_version
93
-                );
94
-            }
95
-        } else {
96
-            $new_value_maybe_array = Model_Data_Translator::prepare_field_value_for_json(
97
-                $field_obj,
98
-                $original_value_maybe_array,
99
-                $request_version
100
-            );
101
-        }
102
-        return $new_value_maybe_array;
103
-    }
104
-
105
-
106
-
107
-    /**
108
-     * Prepares incoming data from the json or $_REQUEST parameters for the models'
109
-     * "$query_params".
110
-     *
111
-     * @param \EE_Model_Field_Base $field_obj
112
-     * @param mixed                $original_value
113
-     * @param string               $requested_version
114
-     * @param string               $timezone_string treat values as being in this timezone
115
-     * @return mixed
116
-     * @throws \DomainException
117
-     */
118
-    public static function prepare_field_value_from_json(
119
-        $field_obj,
120
-        $original_value,
121
-        $requested_version,
122
-        $timezone_string = 'UTC' // UTC
123
-    )
124
-    {
125
-        $timezone_string = $timezone_string !== '' ? $timezone_string : get_option('timezone_string', '');
126
-        $new_value = null;
127
-        if ($field_obj instanceof \EE_Infinite_Integer_Field
128
-            && in_array($original_value, array(null, ''), true)
129
-        ) {
130
-            $new_value = EE_INF;
131
-        } elseif ($field_obj instanceof \EE_Datetime_Field) {
132
-            list($offset_sign, $offset_secs) = Model_Data_Translator::parse_timezone_offset(
133
-                $field_obj->get_timezone_offset(
134
-                    new \DateTimeZone($timezone_string)
135
-                )
136
-            );
137
-            $offset_string =
138
-                str_pad(
139
-                    floor($offset_secs / HOUR_IN_SECONDS),
140
-                    2,
141
-                    '0',
142
-                    STR_PAD_LEFT
143
-                )
144
-                . ':'
145
-                . str_pad(
146
-                    ($offset_secs % HOUR_IN_SECONDS) / MINUTE_IN_SECONDS,
147
-                    2,
148
-                    '0',
149
-                    STR_PAD_LEFT
150
-                );
151
-            $new_value = rest_parse_date($original_value . $offset_sign . $offset_string);
152
-        } else {
153
-            $new_value = $original_value;
154
-        }
155
-        return $new_value;
156
-    }
157
-
158
-
159
-
160
-    /**
161
-     * determines what's going on with them timezone strings
162
-     *
163
-     * @param int $timezone_offset
164
-     * @return array
165
-     */
166
-    private static function parse_timezone_offset($timezone_offset)
167
-    {
168
-        $first_char = substr((string)$timezone_offset, 0, 1);
169
-        if ($first_char === '+' || $first_char === '-') {
170
-            $offset_sign = $first_char;
171
-            $offset_secs = substr((string)$timezone_offset, 1);
172
-        } else {
173
-            $offset_sign = '+';
174
-            $offset_secs = $timezone_offset;
175
-        }
176
-        return array($offset_sign, $offset_secs);
177
-    }
178
-
179
-
180
-
181
-    /**
182
-     * Prepares a field's value for display in the API
183
-     *
184
-     * @param \EE_Model_Field_Base $field_obj
185
-     * @param mixed                $original_value
186
-     * @param string               $requested_version
187
-     * @return mixed
188
-     */
189
-    public static function prepare_field_value_for_json($field_obj, $original_value, $requested_version)
190
-    {
191
-        if ($original_value === EE_INF) {
192
-            $new_value = Model_Data_Translator::ee_inf_in_rest;
193
-        } elseif ($field_obj instanceof \EE_Datetime_Field) {
194
-            if ($original_value instanceof \DateTime) {
195
-                $new_value = $original_value->format('Y-m-d H:i:s');
196
-            } elseif (is_int($original_value)) {
197
-                $new_value = date('Y-m-d H:i:s', $original_value);
198
-            } else {
199
-                $new_value = $original_value;
200
-            }
201
-            $new_value = mysql_to_rfc3339($new_value);
202
-        } else {
203
-            $new_value = $original_value;
204
-        }
205
-        return apply_filters('FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_field_for_rest_api',
206
-            $new_value,
207
-            $field_obj,
208
-            $original_value,
209
-            $requested_version
210
-        );
211
-    }
212
-
213
-
214
-
215
-    /**
216
-     * Prepares condition-query-parameters (like what's in where and having) from
217
-     * the format expected in the API to use in the models
218
-     *
219
-     * @param array     $inputted_query_params_of_this_type
220
-     * @param \EEM_Base $model
221
-     * @param string    $requested_version
222
-     * @return array
223
-     * @throws \DomainException
224
-     * @throws \EE_Error
225
-     */
226
-    public static function prepare_conditions_query_params_for_models(
227
-        $inputted_query_params_of_this_type,
228
-        \EEM_Base $model,
229
-        $requested_version
230
-    ) {
231
-        $query_param_for_models = array();
232
-        foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
233
-            $query_param_sans_stars = Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($query_param_key);
234
-            $field = Model_Data_Translator::deduce_field_from_query_param(
235
-                $query_param_sans_stars,
236
-                $model
237
-            );
238
-            //double-check is it a *_gmt field?
239
-            if ( ! $field instanceof \EE_Model_Field_Base
240
-                 && Model_Data_Translator::is_gmt_date_field_name($query_param_sans_stars)
241
-            ) {
242
-                //yep, take off '_gmt', and find the field
243
-                $query_param_key = Model_Data_Translator::remove_gmt_from_field_name($query_param_sans_stars);
244
-                $field = Model_Data_Translator::deduce_field_from_query_param(
245
-                    $query_param_key,
246
-                    $model
247
-                );
248
-                $timezone = 'UTC';
249
-            } else {
250
-                //so it's not a GMT field. Set the timezone on the model to the default
251
-                $timezone = \EEH_DTT_Helper::get_valid_timezone_string();
252
-            }
253
-            if ($field instanceof \EE_Model_Field_Base) {
254
-                //did they specify an operator?
255
-                if (is_array($query_param_value)) {
256
-                    $op = $query_param_value[0];
257
-                    $translated_value = array($op);
258
-                    if (isset($query_param_value[1])) {
259
-                        $value = $query_param_value[1];
260
-                        $translated_value[1] = Model_Data_Translator::prepare_field_values_from_json($field, $value,
261
-                            $requested_version, $timezone);
262
-                    }
263
-                } else {
264
-                    $translated_value = Model_Data_Translator::prepare_field_value_from_json($field, $query_param_value,
265
-                        $requested_version, $timezone);
266
-                }
267
-                $query_param_for_models[$query_param_key] = $translated_value;
268
-            } else {
269
-                //so it's not for a field, assume it's a logic query param key
270
-                $query_param_for_models[$query_param_key] = Model_Data_Translator::prepare_conditions_query_params_for_models($query_param_value,
271
-                    $model, $requested_version);
272
-            }
273
-        }
274
-        return $query_param_for_models;
275
-    }
276
-
277
-
278
-
279
-    /**
280
-     * Mostly checks if the last 4 characters are "_gmt", indicating its a
281
-     * gmt date field name
282
-     *
283
-     * @param string $field_name
284
-     * @return boolean
285
-     */
286
-    public static function is_gmt_date_field_name($field_name)
287
-    {
288
-        return substr(
289
-                   Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($field_name),
290
-                   -4,
291
-                   4
292
-               ) === '_gmt';
293
-    }
294
-
295
-
296
-
297
-    /**
298
-     * Removes the last "_gmt" part of a field name (and if there is no "_gmt" at the end, leave it alone)
299
-     *
300
-     * @param string $field_name
301
-     * @return string
302
-     */
303
-    public static function remove_gmt_from_field_name($field_name)
304
-    {
305
-        if ( ! Model_Data_Translator::is_gmt_date_field_name($field_name)) {
306
-            return $field_name;
307
-        }
308
-        $query_param_sans_stars = Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($field_name);
309
-        $query_param_sans_gmt_and_sans_stars = substr(
310
-            $query_param_sans_stars,
311
-            0,
312
-            strrpos(
313
-                $field_name,
314
-                '_gmt'
315
-            )
316
-        );
317
-        return str_replace($query_param_sans_stars, $query_param_sans_gmt_and_sans_stars, $field_name);
318
-    }
319
-
320
-
321
-
322
-    /**
323
-     * Takes a field name from the REST API and prepares it for the model querying
324
-     *
325
-     * @param string $field_name
326
-     * @return string
327
-     */
328
-    public static function prepare_field_name_from_json($field_name)
329
-    {
330
-        if (Model_Data_Translator::is_gmt_date_field_name($field_name)) {
331
-            return Model_Data_Translator::remove_gmt_from_field_name($field_name);
332
-        }
333
-        return $field_name;
334
-    }
335
-
336
-
337
-
338
-    /**
339
-     * Takes array of field names from REST API and prepares for models
340
-     *
341
-     * @param array $field_names
342
-     * @return array of field names (possibly include model prefixes)
343
-     */
344
-    public static function prepare_field_names_from_json(array $field_names)
345
-    {
346
-        $new_array = array();
347
-        foreach ($field_names as $key => $field_name) {
348
-            $new_array[$key] = Model_Data_Translator::prepare_field_name_from_json($field_name);
349
-        }
350
-        return $new_array;
351
-    }
352
-
353
-
354
-
355
-    /**
356
-     * Takes array where array keys are field names (possibly with model path prefixes)
357
-     * from the REST API and prepares them for model querying
358
-     *
359
-     * @param array $field_names_as_keys
360
-     * @return array
361
-     */
362
-    public static function prepare_field_names_in_array_keys_from_json(array $field_names_as_keys)
363
-    {
364
-        $new_array = array();
365
-        foreach ($field_names_as_keys as $field_name => $value) {
366
-            $new_array[Model_Data_Translator::prepare_field_name_from_json($field_name)] = $value;
367
-        }
368
-        return $new_array;
369
-    }
370
-
371
-
372
-
373
-    /**
374
-     * Prepares an array of model query params for use in the REST API
375
-     *
376
-     * @param array     $model_query_params
377
-     * @param \EEM_Base $model
378
-     * @param string    $requested_version eg "4.8.36". If null is provided, defaults to the latest release of the EE4
379
-     *                                     REST API
380
-     * @return array which can be passed into the EE4 REST API when querying a model resource
381
-     * @throws \EE_Error
382
-     */
383
-    public static function prepare_query_params_for_rest_api(
384
-        array $model_query_params,
385
-        \EEM_Base $model,
386
-        $requested_version = null
387
-    ) {
388
-        if ($requested_version === null) {
389
-            $requested_version = \EED_Core_Rest_Api::latest_rest_api_version();
390
-        }
391
-        $rest_query_params = $model_query_params;
392
-        if (isset($model_query_params[0])) {
393
-            $rest_query_params['where'] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api(
394
-                $model_query_params[0],
395
-                $model,
396
-                $requested_version
397
-            );
398
-            unset($rest_query_params[0]);
399
-        }
400
-        if (isset($model_query_params['having'])) {
401
-            $rest_query_params['having'] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api(
402
-                $model_query_params['having'],
403
-                $model,
404
-                $requested_version
405
-            );
406
-        }
407
-        return apply_filters('FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_query_params_for_rest_api',
408
-            $rest_query_params, $model_query_params, $model, $requested_version);
409
-    }
410
-
411
-
412
-
413
-    /**
414
-     * Prepares all the sub-conditions query parameters (eg having or where conditions) for use in the rest api
415
-     *
416
-     * @param array     $inputted_query_params_of_this_type eg like the "where" or "having" conditions query params
417
-     *                                                      passed into EEM_Base::get_all()
418
-     * @param \EEM_Base $model
419
-     * @param string    $requested_version                  eg "4.8.36"
420
-     * @return array ready for use in the rest api query params
421
-     * @throws \EE_Error
422
-     */
423
-    public static function prepare_conditions_query_params_for_rest_api(
424
-        $inputted_query_params_of_this_type,
425
-        \EEM_Base $model,
426
-        $requested_version
427
-    ) {
428
-        $query_param_for_models = array();
429
-        foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
430
-            $field = Model_Data_Translator::deduce_field_from_query_param(
431
-                Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($query_param_key),
432
-                $model
433
-            );
434
-            if ($field instanceof \EE_Model_Field_Base) {
435
-                //did they specify an operator?
436
-                if (is_array($query_param_value)) {
437
-                    $op = $query_param_value[0];
438
-                    $translated_value = array($op);
439
-                    if (isset($query_param_value[1])) {
440
-                        $value = $query_param_value[1];
441
-                        $translated_value[1] = Model_Data_Translator::prepare_field_values_for_json($field, $value,
442
-                            $requested_version);
443
-                    }
444
-                } else {
445
-                    $translated_value = Model_Data_Translator::prepare_field_value_for_json($field, $query_param_value,
446
-                        $requested_version);
447
-                }
448
-                $query_param_for_models[$query_param_key] = $translated_value;
449
-            } else {
450
-                //so it's not for a field, assume it's a logic query param key
451
-                $query_param_for_models[$query_param_key] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api($query_param_value,
452
-                    $model, $requested_version);
453
-            }
454
-        }
455
-        return $query_param_for_models;
456
-    }
457
-
458
-
459
-
460
-    /**
461
-     * @param $condition_query_param_key
462
-     * @return string
463
-     */
464
-    public static function remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
465
-    {
466
-        $pos_of_star = strpos($condition_query_param_key, '*');
467
-        if ($pos_of_star === false) {
468
-            return $condition_query_param_key;
469
-        } else {
470
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
471
-            return $condition_query_param_sans_star;
472
-        }
473
-    }
474
-
475
-
476
-
477
-    /**
478
-     * Takes the input parameter and finds the model field that it indicates.
479
-     *
480
-     * @param string    $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
481
-     * @param \EEM_Base $model
482
-     * @return \EE_Model_Field_Base
483
-     * @throws \EE_Error
484
-     */
485
-    public static function deduce_field_from_query_param($query_param_name, \EEM_Base $model)
486
-    {
487
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
488
-        //which will help us find the database table and column
489
-        $query_param_parts = explode('.', $query_param_name);
490
-        if (empty($query_param_parts)) {
491
-            throw new \EE_Error(sprintf(__('_extract_column_name is empty when trying to extract column and table name from %s',
492
-                'event_espresso'), $query_param_name));
493
-        }
494
-        $number_of_parts = count($query_param_parts);
495
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
496
-        if ($number_of_parts === 1) {
497
-            $field_name = $last_query_param_part;
498
-        } else {// $number_of_parts >= 2
499
-            //the last part is the column name, and there are only 2parts. therefore...
500
-            $field_name = $last_query_param_part;
501
-            $model = \EE_Registry::instance()->load_model($query_param_parts[$number_of_parts - 2]);
502
-        }
503
-        try {
504
-            return $model->field_settings_for($field_name);
505
-        } catch (\EE_Error $e) {
506
-            return null;
507
-        }
508
-    }
29
+	/**
30
+	 * We used to use -1 for infinity in the rest api, but that's ambiguous for
31
+	 * fields that COULD contain -1; so we use null
32
+	 */
33
+	const ee_inf_in_rest = null;
34
+
35
+
36
+
37
+	/**
38
+	 * Prepares a possible array of input values from JSON for use by the models
39
+	 *
40
+	 * @param \EE_Model_Field_Base $field_obj
41
+	 * @param mixed                $original_value_maybe_array
42
+	 * @param string               $requested_version
43
+	 * @param string               $timezone_string treat values as being in this timezone
44
+	 * @return mixed
45
+	 * @throws \DomainException
46
+	 */
47
+	public static function prepare_field_values_from_json(
48
+		$field_obj,
49
+		$original_value_maybe_array,
50
+		$requested_version,
51
+		$timezone_string = 'UTC'
52
+	) {
53
+		if (is_array($original_value_maybe_array)) {
54
+			$new_value_maybe_array = array();
55
+			foreach ($original_value_maybe_array as $array_key => $array_item) {
56
+				$new_value_maybe_array[$array_key] = Model_Data_Translator::prepare_field_value_from_json(
57
+					$field_obj,
58
+					$array_item,
59
+					$requested_version,
60
+					$timezone_string
61
+				);
62
+			}
63
+		} else {
64
+			$new_value_maybe_array = Model_Data_Translator::prepare_field_value_from_json(
65
+				$field_obj,
66
+				$original_value_maybe_array,
67
+				$requested_version,
68
+				$timezone_string
69
+			);
70
+		}
71
+		return $new_value_maybe_array;
72
+	}
73
+
74
+
75
+
76
+	/**
77
+	 * Prepares an array of field values FOR use in JSON/REST API
78
+	 *
79
+	 * @param \EE_Model_Field_Base $field_obj
80
+	 * @param mixed                $original_value_maybe_array
81
+	 * @param string               $request_version (eg 4.8.36)
82
+	 * @return array
83
+	 */
84
+	public static function prepare_field_values_for_json($field_obj, $original_value_maybe_array, $request_version)
85
+	{
86
+		if (is_array($original_value_maybe_array)) {
87
+			$new_value_maybe_array = array();
88
+			foreach ($original_value_maybe_array as $array_key => $array_item) {
89
+				$new_value_maybe_array[$array_key] = Model_Data_Translator::prepare_field_value_for_json(
90
+					$field_obj,
91
+					$array_item,
92
+					$request_version
93
+				);
94
+			}
95
+		} else {
96
+			$new_value_maybe_array = Model_Data_Translator::prepare_field_value_for_json(
97
+				$field_obj,
98
+				$original_value_maybe_array,
99
+				$request_version
100
+			);
101
+		}
102
+		return $new_value_maybe_array;
103
+	}
104
+
105
+
106
+
107
+	/**
108
+	 * Prepares incoming data from the json or $_REQUEST parameters for the models'
109
+	 * "$query_params".
110
+	 *
111
+	 * @param \EE_Model_Field_Base $field_obj
112
+	 * @param mixed                $original_value
113
+	 * @param string               $requested_version
114
+	 * @param string               $timezone_string treat values as being in this timezone
115
+	 * @return mixed
116
+	 * @throws \DomainException
117
+	 */
118
+	public static function prepare_field_value_from_json(
119
+		$field_obj,
120
+		$original_value,
121
+		$requested_version,
122
+		$timezone_string = 'UTC' // UTC
123
+	)
124
+	{
125
+		$timezone_string = $timezone_string !== '' ? $timezone_string : get_option('timezone_string', '');
126
+		$new_value = null;
127
+		if ($field_obj instanceof \EE_Infinite_Integer_Field
128
+			&& in_array($original_value, array(null, ''), true)
129
+		) {
130
+			$new_value = EE_INF;
131
+		} elseif ($field_obj instanceof \EE_Datetime_Field) {
132
+			list($offset_sign, $offset_secs) = Model_Data_Translator::parse_timezone_offset(
133
+				$field_obj->get_timezone_offset(
134
+					new \DateTimeZone($timezone_string)
135
+				)
136
+			);
137
+			$offset_string =
138
+				str_pad(
139
+					floor($offset_secs / HOUR_IN_SECONDS),
140
+					2,
141
+					'0',
142
+					STR_PAD_LEFT
143
+				)
144
+				. ':'
145
+				. str_pad(
146
+					($offset_secs % HOUR_IN_SECONDS) / MINUTE_IN_SECONDS,
147
+					2,
148
+					'0',
149
+					STR_PAD_LEFT
150
+				);
151
+			$new_value = rest_parse_date($original_value . $offset_sign . $offset_string);
152
+		} else {
153
+			$new_value = $original_value;
154
+		}
155
+		return $new_value;
156
+	}
157
+
158
+
159
+
160
+	/**
161
+	 * determines what's going on with them timezone strings
162
+	 *
163
+	 * @param int $timezone_offset
164
+	 * @return array
165
+	 */
166
+	private static function parse_timezone_offset($timezone_offset)
167
+	{
168
+		$first_char = substr((string)$timezone_offset, 0, 1);
169
+		if ($first_char === '+' || $first_char === '-') {
170
+			$offset_sign = $first_char;
171
+			$offset_secs = substr((string)$timezone_offset, 1);
172
+		} else {
173
+			$offset_sign = '+';
174
+			$offset_secs = $timezone_offset;
175
+		}
176
+		return array($offset_sign, $offset_secs);
177
+	}
178
+
179
+
180
+
181
+	/**
182
+	 * Prepares a field's value for display in the API
183
+	 *
184
+	 * @param \EE_Model_Field_Base $field_obj
185
+	 * @param mixed                $original_value
186
+	 * @param string               $requested_version
187
+	 * @return mixed
188
+	 */
189
+	public static function prepare_field_value_for_json($field_obj, $original_value, $requested_version)
190
+	{
191
+		if ($original_value === EE_INF) {
192
+			$new_value = Model_Data_Translator::ee_inf_in_rest;
193
+		} elseif ($field_obj instanceof \EE_Datetime_Field) {
194
+			if ($original_value instanceof \DateTime) {
195
+				$new_value = $original_value->format('Y-m-d H:i:s');
196
+			} elseif (is_int($original_value)) {
197
+				$new_value = date('Y-m-d H:i:s', $original_value);
198
+			} else {
199
+				$new_value = $original_value;
200
+			}
201
+			$new_value = mysql_to_rfc3339($new_value);
202
+		} else {
203
+			$new_value = $original_value;
204
+		}
205
+		return apply_filters('FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_field_for_rest_api',
206
+			$new_value,
207
+			$field_obj,
208
+			$original_value,
209
+			$requested_version
210
+		);
211
+	}
212
+
213
+
214
+
215
+	/**
216
+	 * Prepares condition-query-parameters (like what's in where and having) from
217
+	 * the format expected in the API to use in the models
218
+	 *
219
+	 * @param array     $inputted_query_params_of_this_type
220
+	 * @param \EEM_Base $model
221
+	 * @param string    $requested_version
222
+	 * @return array
223
+	 * @throws \DomainException
224
+	 * @throws \EE_Error
225
+	 */
226
+	public static function prepare_conditions_query_params_for_models(
227
+		$inputted_query_params_of_this_type,
228
+		\EEM_Base $model,
229
+		$requested_version
230
+	) {
231
+		$query_param_for_models = array();
232
+		foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
233
+			$query_param_sans_stars = Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($query_param_key);
234
+			$field = Model_Data_Translator::deduce_field_from_query_param(
235
+				$query_param_sans_stars,
236
+				$model
237
+			);
238
+			//double-check is it a *_gmt field?
239
+			if ( ! $field instanceof \EE_Model_Field_Base
240
+				 && Model_Data_Translator::is_gmt_date_field_name($query_param_sans_stars)
241
+			) {
242
+				//yep, take off '_gmt', and find the field
243
+				$query_param_key = Model_Data_Translator::remove_gmt_from_field_name($query_param_sans_stars);
244
+				$field = Model_Data_Translator::deduce_field_from_query_param(
245
+					$query_param_key,
246
+					$model
247
+				);
248
+				$timezone = 'UTC';
249
+			} else {
250
+				//so it's not a GMT field. Set the timezone on the model to the default
251
+				$timezone = \EEH_DTT_Helper::get_valid_timezone_string();
252
+			}
253
+			if ($field instanceof \EE_Model_Field_Base) {
254
+				//did they specify an operator?
255
+				if (is_array($query_param_value)) {
256
+					$op = $query_param_value[0];
257
+					$translated_value = array($op);
258
+					if (isset($query_param_value[1])) {
259
+						$value = $query_param_value[1];
260
+						$translated_value[1] = Model_Data_Translator::prepare_field_values_from_json($field, $value,
261
+							$requested_version, $timezone);
262
+					}
263
+				} else {
264
+					$translated_value = Model_Data_Translator::prepare_field_value_from_json($field, $query_param_value,
265
+						$requested_version, $timezone);
266
+				}
267
+				$query_param_for_models[$query_param_key] = $translated_value;
268
+			} else {
269
+				//so it's not for a field, assume it's a logic query param key
270
+				$query_param_for_models[$query_param_key] = Model_Data_Translator::prepare_conditions_query_params_for_models($query_param_value,
271
+					$model, $requested_version);
272
+			}
273
+		}
274
+		return $query_param_for_models;
275
+	}
276
+
277
+
278
+
279
+	/**
280
+	 * Mostly checks if the last 4 characters are "_gmt", indicating its a
281
+	 * gmt date field name
282
+	 *
283
+	 * @param string $field_name
284
+	 * @return boolean
285
+	 */
286
+	public static function is_gmt_date_field_name($field_name)
287
+	{
288
+		return substr(
289
+				   Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($field_name),
290
+				   -4,
291
+				   4
292
+			   ) === '_gmt';
293
+	}
294
+
295
+
296
+
297
+	/**
298
+	 * Removes the last "_gmt" part of a field name (and if there is no "_gmt" at the end, leave it alone)
299
+	 *
300
+	 * @param string $field_name
301
+	 * @return string
302
+	 */
303
+	public static function remove_gmt_from_field_name($field_name)
304
+	{
305
+		if ( ! Model_Data_Translator::is_gmt_date_field_name($field_name)) {
306
+			return $field_name;
307
+		}
308
+		$query_param_sans_stars = Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($field_name);
309
+		$query_param_sans_gmt_and_sans_stars = substr(
310
+			$query_param_sans_stars,
311
+			0,
312
+			strrpos(
313
+				$field_name,
314
+				'_gmt'
315
+			)
316
+		);
317
+		return str_replace($query_param_sans_stars, $query_param_sans_gmt_and_sans_stars, $field_name);
318
+	}
319
+
320
+
321
+
322
+	/**
323
+	 * Takes a field name from the REST API and prepares it for the model querying
324
+	 *
325
+	 * @param string $field_name
326
+	 * @return string
327
+	 */
328
+	public static function prepare_field_name_from_json($field_name)
329
+	{
330
+		if (Model_Data_Translator::is_gmt_date_field_name($field_name)) {
331
+			return Model_Data_Translator::remove_gmt_from_field_name($field_name);
332
+		}
333
+		return $field_name;
334
+	}
335
+
336
+
337
+
338
+	/**
339
+	 * Takes array of field names from REST API and prepares for models
340
+	 *
341
+	 * @param array $field_names
342
+	 * @return array of field names (possibly include model prefixes)
343
+	 */
344
+	public static function prepare_field_names_from_json(array $field_names)
345
+	{
346
+		$new_array = array();
347
+		foreach ($field_names as $key => $field_name) {
348
+			$new_array[$key] = Model_Data_Translator::prepare_field_name_from_json($field_name);
349
+		}
350
+		return $new_array;
351
+	}
352
+
353
+
354
+
355
+	/**
356
+	 * Takes array where array keys are field names (possibly with model path prefixes)
357
+	 * from the REST API and prepares them for model querying
358
+	 *
359
+	 * @param array $field_names_as_keys
360
+	 * @return array
361
+	 */
362
+	public static function prepare_field_names_in_array_keys_from_json(array $field_names_as_keys)
363
+	{
364
+		$new_array = array();
365
+		foreach ($field_names_as_keys as $field_name => $value) {
366
+			$new_array[Model_Data_Translator::prepare_field_name_from_json($field_name)] = $value;
367
+		}
368
+		return $new_array;
369
+	}
370
+
371
+
372
+
373
+	/**
374
+	 * Prepares an array of model query params for use in the REST API
375
+	 *
376
+	 * @param array     $model_query_params
377
+	 * @param \EEM_Base $model
378
+	 * @param string    $requested_version eg "4.8.36". If null is provided, defaults to the latest release of the EE4
379
+	 *                                     REST API
380
+	 * @return array which can be passed into the EE4 REST API when querying a model resource
381
+	 * @throws \EE_Error
382
+	 */
383
+	public static function prepare_query_params_for_rest_api(
384
+		array $model_query_params,
385
+		\EEM_Base $model,
386
+		$requested_version = null
387
+	) {
388
+		if ($requested_version === null) {
389
+			$requested_version = \EED_Core_Rest_Api::latest_rest_api_version();
390
+		}
391
+		$rest_query_params = $model_query_params;
392
+		if (isset($model_query_params[0])) {
393
+			$rest_query_params['where'] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api(
394
+				$model_query_params[0],
395
+				$model,
396
+				$requested_version
397
+			);
398
+			unset($rest_query_params[0]);
399
+		}
400
+		if (isset($model_query_params['having'])) {
401
+			$rest_query_params['having'] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api(
402
+				$model_query_params['having'],
403
+				$model,
404
+				$requested_version
405
+			);
406
+		}
407
+		return apply_filters('FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_query_params_for_rest_api',
408
+			$rest_query_params, $model_query_params, $model, $requested_version);
409
+	}
410
+
411
+
412
+
413
+	/**
414
+	 * Prepares all the sub-conditions query parameters (eg having or where conditions) for use in the rest api
415
+	 *
416
+	 * @param array     $inputted_query_params_of_this_type eg like the "where" or "having" conditions query params
417
+	 *                                                      passed into EEM_Base::get_all()
418
+	 * @param \EEM_Base $model
419
+	 * @param string    $requested_version                  eg "4.8.36"
420
+	 * @return array ready for use in the rest api query params
421
+	 * @throws \EE_Error
422
+	 */
423
+	public static function prepare_conditions_query_params_for_rest_api(
424
+		$inputted_query_params_of_this_type,
425
+		\EEM_Base $model,
426
+		$requested_version
427
+	) {
428
+		$query_param_for_models = array();
429
+		foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
430
+			$field = Model_Data_Translator::deduce_field_from_query_param(
431
+				Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($query_param_key),
432
+				$model
433
+			);
434
+			if ($field instanceof \EE_Model_Field_Base) {
435
+				//did they specify an operator?
436
+				if (is_array($query_param_value)) {
437
+					$op = $query_param_value[0];
438
+					$translated_value = array($op);
439
+					if (isset($query_param_value[1])) {
440
+						$value = $query_param_value[1];
441
+						$translated_value[1] = Model_Data_Translator::prepare_field_values_for_json($field, $value,
442
+							$requested_version);
443
+					}
444
+				} else {
445
+					$translated_value = Model_Data_Translator::prepare_field_value_for_json($field, $query_param_value,
446
+						$requested_version);
447
+				}
448
+				$query_param_for_models[$query_param_key] = $translated_value;
449
+			} else {
450
+				//so it's not for a field, assume it's a logic query param key
451
+				$query_param_for_models[$query_param_key] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api($query_param_value,
452
+					$model, $requested_version);
453
+			}
454
+		}
455
+		return $query_param_for_models;
456
+	}
457
+
458
+
459
+
460
+	/**
461
+	 * @param $condition_query_param_key
462
+	 * @return string
463
+	 */
464
+	public static function remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
465
+	{
466
+		$pos_of_star = strpos($condition_query_param_key, '*');
467
+		if ($pos_of_star === false) {
468
+			return $condition_query_param_key;
469
+		} else {
470
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
471
+			return $condition_query_param_sans_star;
472
+		}
473
+	}
474
+
475
+
476
+
477
+	/**
478
+	 * Takes the input parameter and finds the model field that it indicates.
479
+	 *
480
+	 * @param string    $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
481
+	 * @param \EEM_Base $model
482
+	 * @return \EE_Model_Field_Base
483
+	 * @throws \EE_Error
484
+	 */
485
+	public static function deduce_field_from_query_param($query_param_name, \EEM_Base $model)
486
+	{
487
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
488
+		//which will help us find the database table and column
489
+		$query_param_parts = explode('.', $query_param_name);
490
+		if (empty($query_param_parts)) {
491
+			throw new \EE_Error(sprintf(__('_extract_column_name is empty when trying to extract column and table name from %s',
492
+				'event_espresso'), $query_param_name));
493
+		}
494
+		$number_of_parts = count($query_param_parts);
495
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
496
+		if ($number_of_parts === 1) {
497
+			$field_name = $last_query_param_part;
498
+		} else {// $number_of_parts >= 2
499
+			//the last part is the column name, and there are only 2parts. therefore...
500
+			$field_name = $last_query_param_part;
501
+			$model = \EE_Registry::instance()->load_model($query_param_parts[$number_of_parts - 2]);
502
+		}
503
+		try {
504
+			return $model->field_settings_for($field_name);
505
+		} catch (\EE_Error $e) {
506
+			return null;
507
+		}
508
+	}
509 509
 
510 510
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
                     '0',
149 149
                     STR_PAD_LEFT
150 150
                 );
151
-            $new_value = rest_parse_date($original_value . $offset_sign . $offset_string);
151
+            $new_value = rest_parse_date($original_value.$offset_sign.$offset_string);
152 152
         } else {
153 153
             $new_value = $original_value;
154 154
         }
@@ -165,10 +165,10 @@  discard block
 block discarded – undo
165 165
      */
166 166
     private static function parse_timezone_offset($timezone_offset)
167 167
     {
168
-        $first_char = substr((string)$timezone_offset, 0, 1);
168
+        $first_char = substr((string) $timezone_offset, 0, 1);
169 169
         if ($first_char === '+' || $first_char === '-') {
170 170
             $offset_sign = $first_char;
171
-            $offset_secs = substr((string)$timezone_offset, 1);
171
+            $offset_secs = substr((string) $timezone_offset, 1);
172 172
         } else {
173 173
             $offset_sign = '+';
174 174
             $offset_secs = $timezone_offset;
Please login to merge, or discard this patch.
core/db_models/fields/EE_Field_With_Model_Name.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@
 block discarded – undo
35 35
      * Returns the name of the model(s) pointed to
36 36
      *
37 37
      * @deprecated since version 4.6.7
38
-     * @return mixed string or array of strings
38
+     * @return string string or array of strings
39 39
      */
40 40
     function get_model_name_pointed_to()
41 41
     {
Please login to merge, or discard this patch.
Indentation   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -8,83 +8,83 @@
 block discarded – undo
8 8
  */
9 9
 abstract class EE_Field_With_Model_Name extends EE_Model_Field_Base
10 10
 {
11
-    /**
12
-     * Usually the name of a single model. However, as in the case for custom post types,
13
-     * it can actually be an array of models
14
-     *
15
-     * @var string or array
16
-     */
17
-    protected $_model_name_pointed_to;
11
+	/**
12
+	 * Usually the name of a single model. However, as in the case for custom post types,
13
+	 * it can actually be an array of models
14
+	 *
15
+	 * @var string or array
16
+	 */
17
+	protected $_model_name_pointed_to;
18 18
 
19
-    /**
20
-     * @param string  $table_column  name fo column for field
21
-     * @param string  $nicename      should eb internationalized with __('blah','event_espresso')
22
-     * @param boolean $nullable
23
-     * @param mixed   $default_value if this is a integer field, it shoudl be an int. if it's a string field, it shoul
24
-     *                               dbe a string
25
-     * @param string  $model_name    eg 'Event','Answer','Term', etc. Basically its the model class's name without the
26
-     *                               "EEM_"
27
-     */
28
-    function __construct($table_column, $nicename, $nullable, $default_value, $model_name)
29
-    {
30
-        $this->_model_name_pointed_to = $model_name;
31
-        parent::__construct($table_column, $nicename, $nullable, $default_value);
32
-    }
19
+	/**
20
+	 * @param string  $table_column  name fo column for field
21
+	 * @param string  $nicename      should eb internationalized with __('blah','event_espresso')
22
+	 * @param boolean $nullable
23
+	 * @param mixed   $default_value if this is a integer field, it shoudl be an int. if it's a string field, it shoul
24
+	 *                               dbe a string
25
+	 * @param string  $model_name    eg 'Event','Answer','Term', etc. Basically its the model class's name without the
26
+	 *                               "EEM_"
27
+	 */
28
+	function __construct($table_column, $nicename, $nullable, $default_value, $model_name)
29
+	{
30
+		$this->_model_name_pointed_to = $model_name;
31
+		parent::__construct($table_column, $nicename, $nullable, $default_value);
32
+	}
33 33
 
34
-    /**
35
-     * Returns the name of the model(s) pointed to
36
-     *
37
-     * @deprecated since version 4.6.7
38
-     * @return mixed string or array of strings
39
-     */
40
-    function get_model_name_pointed_to()
41
-    {
42
-        EE_Error::doing_it_wrong('get_model_name_pointed_to',
43
-            __('This method has been deprecated in favour of instead using get_model_names_pointed_to, which consistently returns an array',
44
-                'event_espresso'), '4.6.7');
45
-        return $this->_model_name_pointed_to;
46
-    }
34
+	/**
35
+	 * Returns the name of the model(s) pointed to
36
+	 *
37
+	 * @deprecated since version 4.6.7
38
+	 * @return mixed string or array of strings
39
+	 */
40
+	function get_model_name_pointed_to()
41
+	{
42
+		EE_Error::doing_it_wrong('get_model_name_pointed_to',
43
+			__('This method has been deprecated in favour of instead using get_model_names_pointed_to, which consistently returns an array',
44
+				'event_espresso'), '4.6.7');
45
+		return $this->_model_name_pointed_to;
46
+	}
47 47
 
48
-    /**
49
-     * Gets the model names pointed to by this field, always as an array
50
-     * (even if there's only one)
51
-     *
52
-     * @return array of model names pointed to by this field
53
-     */
54
-    function get_model_names_pointed_to()
55
-    {
56
-        if (is_array($this->_model_name_pointed_to)) {
57
-            return $this->_model_name_pointed_to;
58
-        } else {
59
-            return array($this->_model_name_pointed_to);
60
-        }
61
-    }
48
+	/**
49
+	 * Gets the model names pointed to by this field, always as an array
50
+	 * (even if there's only one)
51
+	 *
52
+	 * @return array of model names pointed to by this field
53
+	 */
54
+	function get_model_names_pointed_to()
55
+	{
56
+		if (is_array($this->_model_name_pointed_to)) {
57
+			return $this->_model_name_pointed_to;
58
+		} else {
59
+			return array($this->_model_name_pointed_to);
60
+		}
61
+	}
62 62
 
63
-    /**
64
-     * Returns the model's classname (eg EE_Event instead of just Event)
65
-     *
66
-     * @return array
67
-     */
68
-    function get_model_class_names_pointed_to()
69
-    {
70
-        $model_names = array();
71
-        if (is_array($this->_model_name_pointed_to)) {
72
-            foreach ($this->_model_name_pointed_to as $model_name) {
73
-                $model_names[] = "EE_" . $model_name;
74
-            }
75
-        } else {
76
-            $model_names = array("EE_" . $this->_model_name_pointed_to);
77
-        }
78
-        return $model_names;
79
-    }
63
+	/**
64
+	 * Returns the model's classname (eg EE_Event instead of just Event)
65
+	 *
66
+	 * @return array
67
+	 */
68
+	function get_model_class_names_pointed_to()
69
+	{
70
+		$model_names = array();
71
+		if (is_array($this->_model_name_pointed_to)) {
72
+			foreach ($this->_model_name_pointed_to as $model_name) {
73
+				$model_names[] = "EE_" . $model_name;
74
+			}
75
+		} else {
76
+			$model_names = array("EE_" . $this->_model_name_pointed_to);
77
+		}
78
+		return $model_names;
79
+	}
80 80
 
81
-    function is_model_obj_of_type_pointed_to($model_obj_or_ID)
82
-    {
83
-        foreach ($this->get_model_class_names_pointed_to() as $model_obj_classname) {
84
-            if ($model_obj_or_ID instanceof $model_obj_classname) {
85
-                return true;
86
-            }
87
-        }
88
-        return false;
89
-    }
81
+	function is_model_obj_of_type_pointed_to($model_obj_or_ID)
82
+	{
83
+		foreach ($this->get_model_class_names_pointed_to() as $model_obj_classname) {
84
+			if ($model_obj_or_ID instanceof $model_obj_classname) {
85
+				return true;
86
+			}
87
+		}
88
+		return false;
89
+	}
90 90
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -70,10 +70,10 @@
 block discarded – undo
70 70
         $model_names = array();
71 71
         if (is_array($this->_model_name_pointed_to)) {
72 72
             foreach ($this->_model_name_pointed_to as $model_name) {
73
-                $model_names[] = "EE_" . $model_name;
73
+                $model_names[] = "EE_".$model_name;
74 74
             }
75 75
         } else {
76
-            $model_names = array("EE_" . $this->_model_name_pointed_to);
76
+            $model_names = array("EE_".$this->_model_name_pointed_to);
77 77
         }
78 78
         return $model_names;
79 79
     }
Please login to merge, or discard this patch.