Completed
Branch BUG-10851-events-shortcode (8345e4)
by
unknown
38:38 queued 25:37
created
core/db_models/EEM_Base.model.php 2 patches
Doc Comments   +18 added lines, -16 removed lines patch added patch discarded remove patch
@@ -960,7 +960,7 @@  discard block
 block discarded – undo
960 960
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961 961
      * foreign key to the WP_User table)
962 962
      *
963
-     * @return string|boolean string on success, boolean false when there is no
963
+     * @return string|false string on success, boolean false when there is no
964 964
      * foreign key to the WP_User table
965 965
      */
966 966
     public function wp_user_field_name()
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
      *
1067 1067
      * @param array  $query_params      like EEM_Base::get_all's $query_params
1068 1068
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1069
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070 1070
      *                                  fields on the model, and the models we joined to in the query. However, you can
1071 1071
      *                                  override this and set the select to "*", or a specific column name, like
1072 1072
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1458,7 +1458,7 @@  discard block
 block discarded – undo
1458 1458
      * @param string $field_name The name of the field the formats are being retrieved for.
1459 1459
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460 1460
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
-     * @return array formats in an array with the date format first, and the time format last.
1461
+     * @return string[] formats in an array with the date format first, and the time format last.
1462 1462
      */
1463 1463
     public function get_formats_for($field_name, $pretty = false)
1464 1464
     {
@@ -1491,7 +1491,7 @@  discard block
 block discarded – undo
1491 1491
      *                                 be returned.
1492 1492
      * @param string $what             Whether to return the string in just the time format, the date format, or both.
1493 1493
      * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1494
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1494
+     * @return string|null  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1495 1495
      *                                 exception is triggered.
1496 1496
      */
1497 1497
     public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
@@ -1531,7 +1531,7 @@  discard block
 block discarded – undo
1531 1531
      *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1532 1532
      *                                format is
1533 1533
      *                                'U', this is ignored.
1534
-     * @return DateTime
1534
+     * @return string
1535 1535
      * @throws \EE_Error
1536 1536
      */
1537 1537
     public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
@@ -1829,7 +1829,7 @@  discard block
 block discarded – undo
1829 1829
      * Wrapper for EEM_Base::delete_permanently()
1830 1830
      *
1831 1831
      * @param mixed $id
1832
-     * @return boolean whether the row got deleted or not
1832
+     * @return integer whether the row got deleted or not
1833 1833
      * @throws \EE_Error
1834 1834
      */
1835 1835
     public function delete_permanently_by_ID($id)
@@ -1849,7 +1849,7 @@  discard block
 block discarded – undo
1849 1849
      * Wrapper for EEM_Base::delete()
1850 1850
      *
1851 1851
      * @param mixed $id
1852
-     * @return boolean whether the row got deleted or not
1852
+     * @return integer whether the row got deleted or not
1853 1853
      * @throws \EE_Error
1854 1854
      */
1855 1855
     public function delete_by_ID($id)
@@ -2299,7 +2299,7 @@  discard block
 block discarded – undo
2299 2299
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2300 2300
      * EEM_Base::$_db_verification_level
2301 2301
      *
2302
-     * @param $wpdb_method
2302
+     * @param string $wpdb_method
2303 2303
      * @param $arguments_to_provide
2304 2304
      * @return string
2305 2305
      */
@@ -2423,6 +2423,7 @@  discard block
 block discarded – undo
2423 2423
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2424 2424
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2425 2425
      *                             because these will be inserted in any new rows created as well.
2426
+     * @param EE_Base_Class $id_or_obj
2426 2427
      */
2427 2428
     public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2428 2429
     {
@@ -2433,7 +2434,7 @@  discard block
 block discarded – undo
2433 2434
 
2434 2435
 
2435 2436
     /**
2436
-     * @param mixed           $id_or_obj
2437
+     * @param EE_Base_Class           $id_or_obj
2437 2438
      * @param string          $relationName
2438 2439
      * @param array           $where_query_params
2439 2440
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2474,7 +2475,7 @@  discard block
 block discarded – undo
2474 2475
      * However, if the model objects can't be deleted because of blocking related model objects, then
2475 2476
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2476 2477
      *
2477
-     * @param EE_Base_Class|int|string $id_or_obj
2478
+     * @param EE_Base_Class $id_or_obj
2478 2479
      * @param string                   $model_name
2479 2480
      * @param array                    $query_params
2480 2481
      * @return int how many deleted
@@ -2495,7 +2496,7 @@  discard block
 block discarded – undo
2495 2496
      * the model objects can't be hard deleted because of blocking related model objects,
2496 2497
      * just does a soft-delete on them instead.
2497 2498
      *
2498
-     * @param EE_Base_Class|int|string $id_or_obj
2499
+     * @param EE_Base_Class $id_or_obj
2499 2500
      * @param string                   $model_name
2500 2501
      * @param array                    $query_params
2501 2502
      * @return int how many deleted
@@ -2552,6 +2553,7 @@  discard block
 block discarded – undo
2552 2553
      * @param string $model_name   like 'Event', or 'Registration'
2553 2554
      * @param array  $query_params like EEM_Base::get_all's
2554 2555
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2556
+     * @param EE_Base_Class $id_or_obj
2555 2557
      * @return float
2556 2558
      * @throws \EE_Error
2557 2559
      */
@@ -3022,7 +3024,7 @@  discard block
 block discarded – undo
3022 3024
      * Finds all the fields that correspond to the given table
3023 3025
      *
3024 3026
      * @param string $table_alias , array key in EEM_Base::_tables
3025
-     * @return EE_Model_Field_Base[]
3027
+     * @return EE_Model_Field_Base
3026 3028
      */
3027 3029
     public function _get_fields_for_table($table_alias)
3028 3030
     {
@@ -3507,7 +3509,7 @@  discard block
 block discarded – undo
3507 3509
      * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3508 3510
      * We should use default where conditions on related models when they requested to use default where conditions
3509 3511
      * on all models, or specifically just on other related models
3510
-     * @param      $default_where_conditions_value
3512
+     * @param      string $default_where_conditions_value
3511 3513
      * @param bool $for_this_model false means this is for OTHER related models
3512 3514
      * @return bool
3513 3515
      */
@@ -3545,7 +3547,7 @@  discard block
 block discarded – undo
3545 3547
      * where conditions.
3546 3548
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3547 3549
      * on this model or others
3548
-     * @param      $default_where_conditions_value
3550
+     * @param      string $default_where_conditions_value
3549 3551
      * @param bool $for_this_model false means this is for OTHER related models
3550 3552
      * @return bool
3551 3553
      */
@@ -4598,7 +4600,7 @@  discard block
 block discarded – undo
4598 4600
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4599 4601
      * Eg, on EE_Answer that would be ANS_ID field object
4600 4602
      *
4601
-     * @param $field_obj
4603
+     * @param EE_Model_Field_Base $field_obj
4602 4604
      * @return boolean
4603 4605
      */
4604 4606
     public function is_primary_key_field($field_obj)
@@ -5320,7 +5322,7 @@  discard block
 block discarded – undo
5320 5322
     /**
5321 5323
      * Read comments for assume_values_already_prepared_by_model_object()
5322 5324
      *
5323
-     * @return int
5325
+     * @return boolean
5324 5326
      */
5325 5327
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5326 5328
     {
Please login to merge, or discard this patch.
Indentation   +5817 added lines, -5817 removed lines patch added patch discarded remove patch
@@ -28,5825 +28,5825 @@
 block discarded – undo
28 28
 abstract class EEM_Base extends EE_Base implements EventEspresso\core\interfaces\ResettableInterface
29 29
 {
30 30
 
31
-    //admin posty
32
-    //basic -> grants access to mine -> if they don't have it, select none
33
-    //*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
34
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
35
-    //*_published -> grants access to published -> if they dont have it, select non-published
36
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
37
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
38
-    //frontend posty
39
-    //by default has access to published
40
-    //basic -> grants access to mine that aren't published, and all published
41
-    //*_others ->grants access to others that aren't private, all mine
42
-    //*_private -> grants full access
43
-    //frontend non-posty
44
-    //like admin posty
45
-    //category-y
46
-    //assign -> grants access to join-table
47
-    //(delete, edit)
48
-    //payment-method-y
49
-    //for each registered payment method,
50
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
51
-    /**
52
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
53
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
54
-     * They almost always WILL NOT, but it's not necessarily a requirement.
55
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
56
-     *
57
-     * @var boolean
58
-     */
59
-    private $_values_already_prepared_by_model_object = 0;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the data is just like form input that needs to have the model fields'
64
-     * prepare_for_set and prepare_for_use_in_db called on it
65
-     */
66
-    const not_prepared_by_model_object = 0;
67
-
68
-    /**
69
-     * when $_values_already_prepared_by_model_object equals this, we
70
-     * assume this value is coming from a model object and doesn't need to have
71
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
72
-     */
73
-    const prepared_by_model_object = 1;
74
-
75
-    /**
76
-     * when $_values_already_prepared_by_model_object equals this, we assume
77
-     * the values are already to be used in the database (ie no processing is done
78
-     * on them by the model's fields)
79
-     */
80
-    const prepared_for_use_in_db = 2;
81
-
82
-
83
-    protected $singular_item = 'Item';
84
-
85
-    protected $plural_item   = 'Items';
86
-
87
-    /**
88
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
89
-     */
90
-    protected $_tables;
91
-
92
-    /**
93
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
94
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
95
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
96
-     *
97
-     * @var \EE_Model_Field_Base[] $_fields
98
-     */
99
-    protected $_fields;
100
-
101
-    /**
102
-     * array of different kinds of relations
103
-     *
104
-     * @var \EE_Model_Relation_Base[] $_model_relations
105
-     */
106
-    protected $_model_relations;
107
-
108
-    /**
109
-     * @var \EE_Index[] $_indexes
110
-     */
111
-    protected $_indexes = array();
112
-
113
-    /**
114
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
115
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
-     * by setting the same columns as used in these queries in the query yourself.
117
-     *
118
-     * @var EE_Default_Where_Conditions
119
-     */
120
-    protected $_default_where_conditions_strategy;
121
-
122
-    /**
123
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
-     * This is particularly useful when you want something between 'none' and 'default'
125
-     *
126
-     * @var EE_Default_Where_Conditions
127
-     */
128
-    protected $_minimum_where_conditions_strategy;
129
-
130
-    /**
131
-     * String describing how to find the "owner" of this model's objects.
132
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
133
-     * But when there isn't, this indicates which related model, or transiently-related model,
134
-     * has the foreign key to the wp_users table.
135
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
136
-     * related to events, and events have a foreign key to wp_users.
137
-     * On EEM_Transaction, this would be 'Transaction.Event'
138
-     *
139
-     * @var string
140
-     */
141
-    protected $_model_chain_to_wp_user = '';
142
-
143
-    /**
144
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
145
-     * don't need it (particularly CPT models)
146
-     *
147
-     * @var bool
148
-     */
149
-    protected $_ignore_where_strategy = false;
150
-
151
-    /**
152
-     * String used in caps relating to this model. Eg, if the caps relating to this
153
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
154
-     *
155
-     * @var string. If null it hasn't been initialized yet. If false then we
156
-     * have indicated capabilities don't apply to this
157
-     */
158
-    protected $_caps_slug = null;
159
-
160
-    /**
161
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
162
-     * and next-level keys are capability names, and each's value is a
163
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
164
-     * they specify which context to use (ie, frontend, backend, edit or delete)
165
-     * and then each capability in the corresponding sub-array that they're missing
166
-     * adds the where conditions onto the query.
167
-     *
168
-     * @var array
169
-     */
170
-    protected $_cap_restrictions = array(
171
-        self::caps_read       => array(),
172
-        self::caps_read_admin => array(),
173
-        self::caps_edit       => array(),
174
-        self::caps_delete     => array(),
175
-    );
176
-
177
-    /**
178
-     * Array defining which cap restriction generators to use to create default
179
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
180
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
181
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
182
-     * automatically set this to false (not just null).
183
-     *
184
-     * @var EE_Restriction_Generator_Base[]
185
-     */
186
-    protected $_cap_restriction_generators = array();
187
-
188
-    /**
189
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
190
-     */
191
-    const caps_read       = 'read';
192
-
193
-    const caps_read_admin = 'read_admin';
194
-
195
-    const caps_edit       = 'edit';
196
-
197
-    const caps_delete     = 'delete';
198
-
199
-    /**
200
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
201
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
202
-     * maps to 'read' because when looking for relevant permissions we're going to use
203
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
204
-     *
205
-     * @var array
206
-     */
207
-    protected $_cap_contexts_to_cap_action_map = array(
208
-        self::caps_read       => 'read',
209
-        self::caps_read_admin => 'read',
210
-        self::caps_edit       => 'edit',
211
-        self::caps_delete     => 'delete',
212
-    );
213
-
214
-    /**
215
-     * Timezone
216
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
217
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
218
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
219
-     * EE_Datetime_Field data type will have access to it.
220
-     *
221
-     * @var string
222
-     */
223
-    protected $_timezone;
224
-
225
-
226
-    /**
227
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
228
-     * multisite.
229
-     *
230
-     * @var int
231
-     */
232
-    protected static $_model_query_blog_id;
233
-
234
-    /**
235
-     * A copy of _fields, except the array keys are the model names pointed to by
236
-     * the field
237
-     *
238
-     * @var EE_Model_Field_Base[]
239
-     */
240
-    private $_cache_foreign_key_to_fields = array();
241
-
242
-    /**
243
-     * Cached list of all the fields on the model, indexed by their name
244
-     *
245
-     * @var EE_Model_Field_Base[]
246
-     */
247
-    private $_cached_fields = null;
248
-
249
-    /**
250
-     * Cached list of all the fields on the model, except those that are
251
-     * marked as only pertinent to the database
252
-     *
253
-     * @var EE_Model_Field_Base[]
254
-     */
255
-    private $_cached_fields_non_db_only = null;
256
-
257
-    /**
258
-     * A cached reference to the primary key for quick lookup
259
-     *
260
-     * @var EE_Model_Field_Base
261
-     */
262
-    private $_primary_key_field = null;
263
-
264
-    /**
265
-     * Flag indicating whether this model has a primary key or not
266
-     *
267
-     * @var boolean
268
-     */
269
-    protected $_has_primary_key_field = null;
270
-
271
-    /**
272
-     * Whether or not this model is based off a table in WP core only (CPTs should set
273
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
274
-     *
275
-     * @var boolean
276
-     */
277
-    protected $_wp_core_model = false;
278
-
279
-    /**
280
-     *    List of valid operators that can be used for querying.
281
-     * The keys are all operators we'll accept, the values are the real SQL
282
-     * operators used
283
-     *
284
-     * @var array
285
-     */
286
-    protected $_valid_operators = array(
287
-        '='           => '=',
288
-        '<='          => '<=',
289
-        '<'           => '<',
290
-        '>='          => '>=',
291
-        '>'           => '>',
292
-        '!='          => '!=',
293
-        'LIKE'        => 'LIKE',
294
-        'like'        => 'LIKE',
295
-        'NOT_LIKE'    => 'NOT LIKE',
296
-        'not_like'    => 'NOT LIKE',
297
-        'NOT LIKE'    => 'NOT LIKE',
298
-        'not like'    => 'NOT LIKE',
299
-        'IN'          => 'IN',
300
-        'in'          => 'IN',
301
-        'NOT_IN'      => 'NOT IN',
302
-        'not_in'      => 'NOT IN',
303
-        'NOT IN'      => 'NOT IN',
304
-        'not in'      => 'NOT IN',
305
-        'between'     => 'BETWEEN',
306
-        'BETWEEN'     => 'BETWEEN',
307
-        'IS_NOT_NULL' => 'IS NOT NULL',
308
-        'is_not_null' => 'IS NOT NULL',
309
-        'IS NOT NULL' => 'IS NOT NULL',
310
-        'is not null' => 'IS NOT NULL',
311
-        'IS_NULL'     => 'IS NULL',
312
-        'is_null'     => 'IS NULL',
313
-        'IS NULL'     => 'IS NULL',
314
-        'is null'     => 'IS NULL',
315
-        'REGEXP'      => 'REGEXP',
316
-        'regexp'      => 'REGEXP',
317
-        'NOT_REGEXP'  => 'NOT REGEXP',
318
-        'not_regexp'  => 'NOT REGEXP',
319
-        'NOT REGEXP'  => 'NOT REGEXP',
320
-        'not regexp'  => 'NOT REGEXP',
321
-    );
322
-
323
-    /**
324
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
325
-     *
326
-     * @var array
327
-     */
328
-    protected $_in_style_operators = array('IN', 'NOT IN');
329
-
330
-    /**
331
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
332
-     * '12-31-2012'"
333
-     *
334
-     * @var array
335
-     */
336
-    protected $_between_style_operators = array('BETWEEN');
337
-
338
-    /**
339
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
340
-     * on a join table.
341
-     *
342
-     * @var array
343
-     */
344
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
345
-
346
-    /**
347
-     * Allowed values for $query_params['order'] for ordering in queries
348
-     *
349
-     * @var array
350
-     */
351
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
352
-
353
-    /**
354
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
355
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
356
-     *
357
-     * @var array
358
-     */
359
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
360
-
361
-    /**
362
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
363
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
364
-     *
365
-     * @var array
366
-     */
367
-    private $_allowed_query_params = array(
368
-        0,
369
-        'limit',
370
-        'order_by',
371
-        'group_by',
372
-        'having',
373
-        'force_join',
374
-        'order',
375
-        'on_join_limit',
376
-        'default_where_conditions',
377
-        'caps',
378
-    );
379
-
380
-    /**
381
-     * All the data types that can be used in $wpdb->prepare statements.
382
-     *
383
-     * @var array
384
-     */
385
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
386
-
387
-    /**
388
-     *    EE_Registry Object
389
-     *
390
-     * @var    object
391
-     * @access    protected
392
-     */
393
-    protected $EE = null;
394
-
395
-
396
-    /**
397
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
398
-     *
399
-     * @var int
400
-     */
401
-    protected $_show_next_x_db_queries = 0;
402
-
403
-    /**
404
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
405
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
406
-     *
407
-     * @var array
408
-     */
409
-    protected $_custom_selections = array();
410
-
411
-    /**
412
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
413
-     * caches every model object we've fetched from the DB on this request
414
-     *
415
-     * @var array
416
-     */
417
-    protected $_entity_map;
418
-
419
-    /**
420
-     * constant used to show EEM_Base has not yet verified the db on this http request
421
-     */
422
-    const db_verified_none = 0;
423
-
424
-    /**
425
-     * constant used to show EEM_Base has verified the EE core db on this http request,
426
-     * but not the addons' dbs
427
-     */
428
-    const db_verified_core = 1;
429
-
430
-    /**
431
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
-     * the EE core db too)
433
-     */
434
-    const db_verified_addons = 2;
435
-
436
-    /**
437
-     * indicates whether an EEM_Base child has already re-verified the DB
438
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
-     * looking like EEM_Base::db_verified_*
440
-     *
441
-     * @var int - 0 = none, 1 = core, 2 = addons
442
-     */
443
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
-
445
-    /**
446
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
-     *        registrations for non-trashed tickets for non-trashed datetimes)
449
-     */
450
-    const default_where_conditions_all = 'all';
451
-
452
-    /**
453
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
-     *        models which share tables with other models, this can return data for the wrong model.
458
-     */
459
-    const default_where_conditions_this_only = 'this_model_only';
460
-
461
-    /**
462
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
-     */
466
-    const default_where_conditions_others_only = 'other_models_only';
467
-
468
-    /**
469
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
-     *        (regardless of whether those events and venues are trashed)
474
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
-     *        events.
476
-     */
477
-    const default_where_conditions_minimum_all = 'minimum';
478
-
479
-    /**
480
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
-     *        not)
484
-     */
485
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
-
487
-    /**
488
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
-     *        it's possible it will return table entries for other models. You should use
491
-     *        EEM_Base::default_where_conditions_minimum_all instead.
492
-     */
493
-    const default_where_conditions_none = 'none';
494
-
495
-
496
-
497
-    /**
498
-     * About all child constructors:
499
-     * they should define the _tables, _fields and _model_relations arrays.
500
-     * Should ALWAYS be called after child constructor.
501
-     * In order to make the child constructors to be as simple as possible, this parent constructor
502
-     * finalizes constructing all the object's attributes.
503
-     * Generally, rather than requiring a child to code
504
-     * $this->_tables = array(
505
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
-     *        ...);
507
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
-     * each EE_Table has a function to set the table's alias after the constructor, using
509
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
-     * do something similar.
511
-     *
512
-     * @param null $timezone
513
-     * @throws \EE_Error
514
-     */
515
-    protected function __construct($timezone = null)
516
-    {
517
-        // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
520
-                sprintf(
521
-                    __('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.',
522
-                        'event_espresso'),
523
-                    get_class($this)
524
-                )
525
-            );
526
-        }
527
-        /**
528
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
-         */
530
-        if (empty(EEM_Base::$_model_query_blog_id)) {
531
-            EEM_Base::set_model_query_blog_id();
532
-        }
533
-        /**
534
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
-         * just use EE_Register_Model_Extension
536
-         *
537
-         * @var EE_Table_Base[] $_tables
538
-         */
539
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
-        foreach ($this->_tables as $table_alias => $table_obj) {
541
-            /** @var $table_obj EE_Table_Base */
542
-            $table_obj->_construct_finalize_with_alias($table_alias);
543
-            if ($table_obj instanceof EE_Secondary_Table) {
544
-                /** @var $table_obj EE_Secondary_Table */
545
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
-            }
547
-        }
548
-        /**
549
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
-         * EE_Register_Model_Extension
551
-         *
552
-         * @param EE_Model_Field_Base[] $_fields
553
-         */
554
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
-        $this->_invalidate_field_caches();
556
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
558
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
-            }
561
-            foreach ($fields_for_table as $field_name => $field_obj) {
562
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
-                //primary key field base has a slightly different _construct_finalize
564
-                /** @var $field_obj EE_Model_Field_Base */
565
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
-            }
567
-        }
568
-        // everything is related to Extra_Meta
569
-        if (get_class($this) !== 'EEM_Extra_Meta') {
570
-            //make extra meta related to everything, but don't block deleting things just
571
-            //because they have related extra meta info. For now just orphan those extra meta
572
-            //in the future we should automatically delete them
573
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
-        }
575
-        //and change logs
576
-        if (get_class($this) !== 'EEM_Change_Log') {
577
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        /**
580
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
-         * EE_Register_Model_Extension
582
-         *
583
-         * @param EE_Model_Relation_Base[] $_model_relations
584
-         */
585
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
-            $this->_model_relations);
587
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
588
-            /** @var $relation_obj EE_Model_Relation_Base */
589
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
-        }
591
-        foreach ($this->_indexes as $index_name => $index_obj) {
592
-            /** @var $index_obj EE_Index */
593
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
-        }
595
-        $this->set_timezone($timezone);
596
-        //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
598
-            //nothing was set during child constructor, so set default
599
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
-        }
601
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
603
-            //nothing was set during child constructor, so set default
604
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
-        }
606
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
608
-        //to indicate to NOT set it, set it to the logical default
609
-        if ($this->_caps_slug === null) {
610
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
-        }
612
-        //initialize the standard cap restriction generators if none were specified by the child constructor
613
-        if ($this->_cap_restriction_generators !== false) {
614
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
617
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
-                        new EE_Restriction_Generator_Protected(),
619
-                        $cap_context,
620
-                        $this
621
-                    );
622
-                }
623
-            }
624
-        }
625
-        //if there are cap restriction generators, use them to make the default cap restrictions
626
-        if ($this->_cap_restriction_generators !== false) {
627
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
629
-                    continue;
630
-                }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
-                    throw new EE_Error(
633
-                        sprintf(
634
-                            __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
-                                'event_espresso'),
636
-                            $context,
637
-                            $this->get_this_model_name()
638
-                        )
639
-                    );
640
-                }
641
-                $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
643
-                    $generator_object->_construct_finalize($this, $action);
644
-                }
645
-            }
646
-        }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
648
-    }
649
-
650
-
651
-
652
-    /**
653
-     * Generates the cap restrictions for the given context, or if they were
654
-     * already generated just gets what's cached
655
-     *
656
-     * @param string $context one of EEM_Base::valid_cap_contexts()
657
-     * @return EE_Default_Where_Conditions[]
658
-     */
659
-    protected function _generate_cap_restrictions($context)
660
-    {
661
-        if (isset($this->_cap_restriction_generators[$context])
662
-            && $this->_cap_restriction_generators[$context]
663
-               instanceof
664
-               EE_Restriction_Generator_Base
665
-        ) {
666
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
667
-        } else {
668
-            return array();
669
-        }
670
-    }
671
-
672
-
673
-
674
-    /**
675
-     * Used to set the $_model_query_blog_id static property.
676
-     *
677
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
678
-     *                      value for get_current_blog_id() will be used.
679
-     */
680
-    public static function set_model_query_blog_id($blog_id = 0)
681
-    {
682
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
-    }
684
-
685
-
686
-
687
-    /**
688
-     * Returns whatever is set as the internal $model_query_blog_id.
689
-     *
690
-     * @return int
691
-     */
692
-    public static function get_model_query_blog_id()
693
-    {
694
-        return EEM_Base::$_model_query_blog_id;
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     *        This function is a singleton method used to instantiate the Espresso_model object
701
-     *
702
-     * @access public
703
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
704
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
705
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
706
-     *                         timezone in the 'timezone_string' wp option)
707
-     * @return static (as in the concrete child class)
708
-     */
709
-    public static function instance($timezone = null)
710
-    {
711
-        // check if instance of Espresso_model already exists
712
-        if (! static::$_instance instanceof static) {
713
-            // instantiate Espresso_model
714
-            static::$_instance = new static($timezone);
715
-        }
716
-        //we might have a timezone set, let set_timezone decide what to do with it
717
-        static::$_instance->set_timezone($timezone);
718
-        // Espresso_model object
719
-        return static::$_instance;
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * resets the model and returns it
726
-     *
727
-     * @param null | string $timezone
728
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
729
-     * all its properties reset; if it wasn't instantiated, returns null)
730
-     */
731
-    public static function reset($timezone = null)
732
-    {
733
-        if (static::$_instance instanceof EEM_Base) {
734
-            //let's try to NOT swap out the current instance for a new one
735
-            //because if someone has a reference to it, we can't remove their reference
736
-            //so it's best to keep using the same reference, but change the original object
737
-            //reset all its properties to their original values as defined in the class
738
-            $r = new ReflectionClass(get_class(static::$_instance));
739
-            $static_properties = $r->getStaticProperties();
740
-            foreach ($r->getDefaultProperties() as $property => $value) {
741
-                //don't set instance to null like it was originally,
742
-                //but it's static anyways, and we're ignoring static properties (for now at least)
743
-                if (! isset($static_properties[$property])) {
744
-                    static::$_instance->{$property} = $value;
745
-                }
746
-            }
747
-            //and then directly call its constructor again, like we would if we
748
-            //were creating a new one
749
-            static::$_instance->__construct($timezone);
750
-            return self::instance();
751
-        }
752
-        return null;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
759
-     *
760
-     * @param  boolean $translated return localized strings or JUST the array.
761
-     * @return array
762
-     * @throws \EE_Error
763
-     */
764
-    public function status_array($translated = false)
765
-    {
766
-        if (! array_key_exists('Status', $this->_model_relations)) {
767
-            return array();
768
-        }
769
-        $model_name = $this->get_this_model_name();
770
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
771
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
772
-        $status_array = array();
773
-        foreach ($stati as $status) {
774
-            $status_array[$status->ID()] = $status->get('STS_code');
775
-        }
776
-        return $translated
777
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
778
-            : $status_array;
779
-    }
780
-
781
-
782
-
783
-    /**
784
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
785
-     *
786
-     * @param array $query_params             {
787
-     * @var array $0 (where) array {
788
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
789
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
790
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
791
-     *                                        conditions based on related models (and even
792
-     *                                        models-related-to-related-models) prepend the model's name onto the field
793
-     *                                        name. Eg,
794
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
795
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
796
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
797
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
798
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
799
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
800
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
801
-     *                                        to Venues (even when each of those models actually consisted of two
802
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
803
-     *                                        just having
804
-     *                                        "Venue.VNU_ID", you could have
805
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
806
-     *                                        events are related to Registrations, which are related to Attendees). You
807
-     *                                        can take it even further with
808
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
809
-     *                                        (from the default of '='), change the value to an numerically-indexed
810
-     *                                        array, where the first item in the list is the operator. eg: array(
811
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
812
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
813
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
814
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
815
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
816
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
817
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
818
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
819
-     *                                        the value is a field, simply provide a third array item (true) to the
820
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
821
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
822
-     *                                        Note: you can also use related model field names like you would any other
823
-     *                                        field name. eg:
824
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
825
-     *                                        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__>' =>
826
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
827
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
828
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
829
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
830
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
831
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
832
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
833
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
834
-     *                                        "stick" until you specify an AND. eg
835
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
836
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
837
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
838
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
839
-     *                                        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 >>
840
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
841
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
842
-     *                                        too, eg:
843
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
844
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
845
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
846
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
847
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
848
-     *                                        the OFFSET, the 2nd is the LIMIT
849
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
850
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
851
-     *                                        following format array('on_join_limit'
852
-     *                                        => array( 'table_alias', array(1,2) ) ).
853
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
854
-     *                                        values are either 'ASC' or 'DESC'.
855
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
856
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
857
-     *                                        DESC..." respectively. Like the
858
-     *                                        'where' conditions, these fields can be on related models. Eg
859
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
860
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
861
-     *                                        Attendee, Price, Datetime, etc.)
862
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
863
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
864
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
865
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
866
-     *                                        order by the primary key. Eg,
867
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
868
-     *                                        //(will join with the Datetime model's table(s) and order by its field
869
-     *                                        DTT_EVT_start) or
870
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
871
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
872
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
873
-     *                                        'group_by'=>'VNU_ID', or
874
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
875
-     *                                        if no
876
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
877
-     *                                        model's primary key (or combined primary keys). This avoids some
878
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
879
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
880
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
881
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
882
-     *                                        results)
883
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
884
-     *                                        array where values are models to be joined in the query.Eg
885
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
886
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
887
-     *                                        probably only want to do this in hopes of increasing efficiency, as
888
-     *                                        related models which belongs to the current model
889
-     *                                        (ie, the current model has a foreign key to them, like how Registration
890
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
891
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
892
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
893
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
894
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
895
-     *                                        default where conditions set it to 'other_models_only'. If you only want
896
-     *                                        this model's default where conditions added to the query, use
897
-     *                                        'this_model_only'. If you want to use all default where conditions
898
-     *                                        (default), set to 'all'.
899
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
900
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
901
-     *                                        everything? Or should we only show the current user items they should be
902
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
903
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
904
-     *                                        }
905
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
906
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
907
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
908
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
909
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
910
-     *                                        array( array(
911
-     *                                        'OR'=>array(
912
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
913
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
914
-     *                                        )
915
-     *                                        ),
916
-     *                                        'limit'=>10,
917
-     *                                        'group_by'=>'TXN_ID'
918
-     *                                        ));
919
-     *                                        get all the answers to the question titled "shirt size" for event with id
920
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
921
-     *                                        'Question.QST_display_text'=>'shirt size',
922
-     *                                        'Registration.Event.EVT_ID'=>12
923
-     *                                        ),
924
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
925
-     *                                        ));
926
-     * @throws \EE_Error
927
-     */
928
-    public function get_all($query_params = array())
929
-    {
930
-        if (isset($query_params['limit'])
931
-            && ! isset($query_params['group_by'])
932
-        ) {
933
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
-        }
935
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
936
-    }
937
-
938
-
939
-
940
-    /**
941
-     * Modifies the query parameters so we only get back model objects
942
-     * that "belong" to the current user
943
-     *
944
-     * @param array $query_params @see EEM_Base::get_all()
945
-     * @return array like EEM_Base::get_all
946
-     */
947
-    public function alter_query_params_to_only_include_mine($query_params = array())
948
-    {
949
-        $wp_user_field_name = $this->wp_user_field_name();
950
-        if ($wp_user_field_name) {
951
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
952
-        }
953
-        return $query_params;
954
-    }
955
-
956
-
957
-
958
-    /**
959
-     * Returns the name of the field's name that points to the WP_User table
960
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
-     * foreign key to the WP_User table)
962
-     *
963
-     * @return string|boolean string on success, boolean false when there is no
964
-     * foreign key to the WP_User table
965
-     */
966
-    public function wp_user_field_name()
967
-    {
968
-        try {
969
-            if (! empty($this->_model_chain_to_wp_user)) {
970
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971
-                $last_model_name = end($models_to_follow_to_wp_users);
972
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
-            } else {
975
-                $model_with_fk_to_wp_users = $this;
976
-                $model_chain_to_wp_user = '';
977
-            }
978
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
980
-        } catch (EE_Error $e) {
981
-            return false;
982
-        }
983
-    }
984
-
985
-
986
-
987
-    /**
988
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
989
-     * (or transiently-related model) has a foreign key to the wp_users table;
990
-     * useful for finding if model objects of this type are 'owned' by the current user.
991
-     * This is an empty string when the foreign key is on this model and when it isn't,
992
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
993
-     * (or transiently-related model)
994
-     *
995
-     * @return string
996
-     */
997
-    public function model_chain_to_wp_user()
998
-    {
999
-        return $this->_model_chain_to_wp_user;
1000
-    }
1001
-
1002
-
1003
-
1004
-    /**
1005
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
-     * like how registrations don't have a foreign key to wp_users, but the
1007
-     * events they are for are), or is unrelated to wp users.
1008
-     * generally available
1009
-     *
1010
-     * @return boolean
1011
-     */
1012
-    public function is_owned()
1013
-    {
1014
-        if ($this->model_chain_to_wp_user()) {
1015
-            return true;
1016
-        } else {
1017
-            try {
1018
-                $this->get_foreign_key_to('WP_User');
1019
-                return true;
1020
-            } catch (EE_Error $e) {
1021
-                return false;
1022
-            }
1023
-        }
1024
-    }
1025
-
1026
-
1027
-
1028
-    /**
1029
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
-     * the model)
1032
-     *
1033
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1034
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1037
-     *                                  override this and set the select to "*", or a specific column name, like
1038
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
-     *                                  the aliases used to refer to this selection, and values are to be
1041
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
-     * @throws \EE_Error
1045
-     */
1046
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
-    {
1048
-        // remember the custom selections, if any, and type cast as array
1049
-        // (unless $columns_to_select is an object, then just set as an empty array)
1050
-        // Note: (array) 'some string' === array( 'some string' )
1051
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1053
-        $select_expressions = $columns_to_select !== null
1054
-            ? $this->_construct_select_from_input($columns_to_select)
1055
-            : $this->_construct_default_select_sql($model_query_info);
1056
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058
-    }
1059
-
1060
-
1061
-
1062
-    /**
1063
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1064
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1065
-     * take care of joins, field preparation etc.
1066
-     *
1067
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1068
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1071
-     *                                  override this and set the select to "*", or a specific column name, like
1072
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1073
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1074
-     *                                  the aliases used to refer to this selection, and values are to be
1075
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1076
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1077
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1078
-     * @throws \EE_Error
1079
-     */
1080
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1081
-    {
1082
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1083
-    }
1084
-
1085
-
1086
-
1087
-    /**
1088
-     * For creating a custom select statement
1089
-     *
1090
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1091
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1092
-     *                                 SQL, and 1=>is the datatype
1093
-     * @throws EE_Error
1094
-     * @return string
1095
-     */
1096
-    private function _construct_select_from_input($columns_to_select)
1097
-    {
1098
-        if (is_array($columns_to_select)) {
1099
-            $select_sql_array = array();
1100
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
-                    throw new EE_Error(
1103
-                        sprintf(
1104
-                            __(
1105
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1106
-                                "event_espresso"
1107
-                            ),
1108
-                            $selection_and_datatype,
1109
-                            $alias
1110
-                        )
1111
-                    );
1112
-                }
1113
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
-                    throw new EE_Error(
1115
-                        sprintf(
1116
-                            __(
1117
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1118
-                                "event_espresso"
1119
-                            ),
1120
-                            $selection_and_datatype[1],
1121
-                            $selection_and_datatype[0],
1122
-                            $alias,
1123
-                            implode(",", $this->_valid_wpdb_data_types)
1124
-                        )
1125
-                    );
1126
-                }
1127
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1128
-            }
1129
-            $columns_to_select_string = implode(", ", $select_sql_array);
1130
-        } else {
1131
-            $columns_to_select_string = $columns_to_select;
1132
-        }
1133
-        return $columns_to_select_string;
1134
-    }
1135
-
1136
-
1137
-
1138
-    /**
1139
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1140
-     *
1141
-     * @return string
1142
-     * @throws \EE_Error
1143
-     */
1144
-    public function primary_key_name()
1145
-    {
1146
-        return $this->get_primary_key_field()->get_name();
1147
-    }
1148
-
1149
-
1150
-
1151
-    /**
1152
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1153
-     * If there is no primary key on this model, $id is treated as primary key string
1154
-     *
1155
-     * @param mixed $id int or string, depending on the type of the model's primary key
1156
-     * @return EE_Base_Class
1157
-     */
1158
-    public function get_one_by_ID($id)
1159
-    {
1160
-        if ($this->get_from_entity_map($id)) {
1161
-            return $this->get_from_entity_map($id);
1162
-        }
1163
-        return $this->get_one(
1164
-            $this->alter_query_params_to_restrict_by_ID(
1165
-                $id,
1166
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1167
-            )
1168
-        );
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * Alters query parameters to only get items with this ID are returned.
1175
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1176
-     * or could just be a simple primary key ID
1177
-     *
1178
-     * @param int   $id
1179
-     * @param array $query_params
1180
-     * @return array of normal query params, @see EEM_Base::get_all
1181
-     * @throws \EE_Error
1182
-     */
1183
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184
-    {
1185
-        if (! isset($query_params[0])) {
1186
-            $query_params[0] = array();
1187
-        }
1188
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1189
-        if ($conditions_from_id === null) {
1190
-            $query_params[0][$this->primary_key_name()] = $id;
1191
-        } else {
1192
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1193
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1194
-        }
1195
-        return $query_params;
1196
-    }
1197
-
1198
-
1199
-
1200
-    /**
1201
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1202
-     * array. If no item is found, null is returned.
1203
-     *
1204
-     * @param array $query_params like EEM_Base's $query_params variable.
1205
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1206
-     * @throws \EE_Error
1207
-     */
1208
-    public function get_one($query_params = array())
1209
-    {
1210
-        if (! is_array($query_params)) {
1211
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1212
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213
-                    gettype($query_params)), '4.6.0');
1214
-            $query_params = array();
1215
-        }
1216
-        $query_params['limit'] = 1;
1217
-        $items = $this->get_all($query_params);
1218
-        if (empty($items)) {
1219
-            return null;
1220
-        } else {
1221
-            return array_shift($items);
1222
-        }
1223
-    }
1224
-
1225
-
1226
-
1227
-    /**
1228
-     * Returns the next x number of items in sequence from the given value as
1229
-     * found in the database matching the given query conditions.
1230
-     *
1231
-     * @param mixed $current_field_value    Value used for the reference point.
1232
-     * @param null  $field_to_order_by      What field is used for the
1233
-     *                                      reference point.
1234
-     * @param int   $limit                  How many to return.
1235
-     * @param array $query_params           Extra conditions on the query.
1236
-     * @param null  $columns_to_select      If left null, then an array of
1237
-     *                                      EE_Base_Class objects is returned,
1238
-     *                                      otherwise you can indicate just the
1239
-     *                                      columns you want returned.
1240
-     * @return EE_Base_Class[]|array
1241
-     * @throws \EE_Error
1242
-     */
1243
-    public function next_x(
1244
-        $current_field_value,
1245
-        $field_to_order_by = null,
1246
-        $limit = 1,
1247
-        $query_params = array(),
1248
-        $columns_to_select = null
1249
-    ) {
1250
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1251
-            $columns_to_select);
1252
-    }
1253
-
1254
-
1255
-
1256
-    /**
1257
-     * Returns the previous x number of items in sequence from the given value
1258
-     * as found in the database matching the given query conditions.
1259
-     *
1260
-     * @param mixed $current_field_value    Value used for the reference point.
1261
-     * @param null  $field_to_order_by      What field is used for the
1262
-     *                                      reference point.
1263
-     * @param int   $limit                  How many to return.
1264
-     * @param array $query_params           Extra conditions on the query.
1265
-     * @param null  $columns_to_select      If left null, then an array of
1266
-     *                                      EE_Base_Class objects is returned,
1267
-     *                                      otherwise you can indicate just the
1268
-     *                                      columns you want returned.
1269
-     * @return EE_Base_Class[]|array
1270
-     * @throws \EE_Error
1271
-     */
1272
-    public function previous_x(
1273
-        $current_field_value,
1274
-        $field_to_order_by = null,
1275
-        $limit = 1,
1276
-        $query_params = array(),
1277
-        $columns_to_select = null
1278
-    ) {
1279
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1280
-            $columns_to_select);
1281
-    }
1282
-
1283
-
1284
-
1285
-    /**
1286
-     * Returns the next item in sequence from the given value as found in the
1287
-     * database matching the given query conditions.
1288
-     *
1289
-     * @param mixed $current_field_value    Value used for the reference point.
1290
-     * @param null  $field_to_order_by      What field is used for the
1291
-     *                                      reference point.
1292
-     * @param array $query_params           Extra conditions on the query.
1293
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1294
-     *                                      object is returned, otherwise you
1295
-     *                                      can indicate just the columns you
1296
-     *                                      want and a single array indexed by
1297
-     *                                      the columns will be returned.
1298
-     * @return EE_Base_Class|null|array()
1299
-     * @throws \EE_Error
1300
-     */
1301
-    public function next(
1302
-        $current_field_value,
1303
-        $field_to_order_by = null,
1304
-        $query_params = array(),
1305
-        $columns_to_select = null
1306
-    ) {
1307
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1308
-            $columns_to_select);
1309
-        return empty($results) ? null : reset($results);
1310
-    }
1311
-
1312
-
1313
-
1314
-    /**
1315
-     * Returns the previous item in sequence from the given value as found in
1316
-     * the database matching the given query conditions.
1317
-     *
1318
-     * @param mixed $current_field_value    Value used for the reference point.
1319
-     * @param null  $field_to_order_by      What field is used for the
1320
-     *                                      reference point.
1321
-     * @param array $query_params           Extra conditions on the query.
1322
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1323
-     *                                      object is returned, otherwise you
1324
-     *                                      can indicate just the columns you
1325
-     *                                      want and a single array indexed by
1326
-     *                                      the columns will be returned.
1327
-     * @return EE_Base_Class|null|array()
1328
-     * @throws EE_Error
1329
-     */
1330
-    public function previous(
1331
-        $current_field_value,
1332
-        $field_to_order_by = null,
1333
-        $query_params = array(),
1334
-        $columns_to_select = null
1335
-    ) {
1336
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1337
-            $columns_to_select);
1338
-        return empty($results) ? null : reset($results);
1339
-    }
1340
-
1341
-
1342
-
1343
-    /**
1344
-     * Returns the a consecutive number of items in sequence from the given
1345
-     * value as found in the database matching the given query conditions.
1346
-     *
1347
-     * @param mixed  $current_field_value   Value used for the reference point.
1348
-     * @param string $operand               What operand is used for the sequence.
1349
-     * @param string $field_to_order_by     What field is used for the reference point.
1350
-     * @param int    $limit                 How many to return.
1351
-     * @param array  $query_params          Extra conditions on the query.
1352
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1353
-     *                                      otherwise you can indicate just the columns you want returned.
1354
-     * @return EE_Base_Class[]|array
1355
-     * @throws EE_Error
1356
-     */
1357
-    protected function _get_consecutive(
1358
-        $current_field_value,
1359
-        $operand = '>',
1360
-        $field_to_order_by = null,
1361
-        $limit = 1,
1362
-        $query_params = array(),
1363
-        $columns_to_select = null
1364
-    ) {
1365
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1366
-        if (empty($field_to_order_by)) {
1367
-            if ($this->has_primary_key_field()) {
1368
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1369
-            } else {
1370
-                if (WP_DEBUG) {
1371
-                    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).',
1372
-                        'event_espresso'));
1373
-                }
1374
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1375
-                return array();
1376
-            }
1377
-        }
1378
-        if (! is_array($query_params)) {
1379
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381
-                    gettype($query_params)), '4.6.0');
1382
-            $query_params = array();
1383
-        }
1384
-        //let's add the where query param for consecutive look up.
1385
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386
-        $query_params['limit'] = $limit;
1387
-        //set direction
1388
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
-        $query_params['order_by'] = $operand === '>'
1390
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1391
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1392
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1393
-        if (empty($columns_to_select)) {
1394
-            return $this->get_all($query_params);
1395
-        } else {
1396
-            //getting just the fields
1397
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1398
-        }
1399
-    }
1400
-
1401
-
1402
-
1403
-    /**
1404
-     * This sets the _timezone property after model object has been instantiated.
1405
-     *
1406
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
-     */
1408
-    public function set_timezone($timezone)
1409
-    {
1410
-        if ($timezone !== null) {
1411
-            $this->_timezone = $timezone;
1412
-        }
1413
-        //note we need to loop through relations and set the timezone on those objects as well.
1414
-        foreach ($this->_model_relations as $relation) {
1415
-            $relation->set_timezone($timezone);
1416
-        }
1417
-        //and finally we do the same for any datetime fields
1418
-        foreach ($this->_fields as $field) {
1419
-            if ($field instanceof EE_Datetime_Field) {
1420
-                $field->set_timezone($timezone);
1421
-            }
1422
-        }
1423
-    }
1424
-
1425
-
1426
-
1427
-    /**
1428
-     * This just returns whatever is set for the current timezone.
1429
-     *
1430
-     * @access public
1431
-     * @return string
1432
-     */
1433
-    public function get_timezone()
1434
-    {
1435
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
-        if (empty($this->_timezone)) {
1437
-            foreach ($this->_fields as $field) {
1438
-                if ($field instanceof EE_Datetime_Field) {
1439
-                    $this->set_timezone($field->get_timezone());
1440
-                    break;
1441
-                }
1442
-            }
1443
-        }
1444
-        //if timezone STILL empty then return the default timezone for the site.
1445
-        if (empty($this->_timezone)) {
1446
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
-        }
1448
-        return $this->_timezone;
1449
-    }
1450
-
1451
-
1452
-
1453
-    /**
1454
-     * This returns the date formats set for the given field name and also ensures that
1455
-     * $this->_timezone property is set correctly.
1456
-     *
1457
-     * @since 4.6.x
1458
-     * @param string $field_name The name of the field the formats are being retrieved for.
1459
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
-     * @return array formats in an array with the date format first, and the time format last.
1462
-     */
1463
-    public function get_formats_for($field_name, $pretty = false)
1464
-    {
1465
-        $field_settings = $this->field_settings_for($field_name);
1466
-        //if not a valid EE_Datetime_Field then throw error
1467
-        if (! $field_settings instanceof EE_Datetime_Field) {
1468
-            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.',
1469
-                'event_espresso'), $field_name));
1470
-        }
1471
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1472
-        //the field.
1473
-        $this->_timezone = $field_settings->get_timezone();
1474
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1475
-    }
1476
-
1477
-
1478
-
1479
-    /**
1480
-     * This returns the current time in a format setup for a query on this model.
1481
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1482
-     * it will return:
1483
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1484
-     *  NOW
1485
-     *  - or a unix timestamp (equivalent to time())
1486
-     *
1487
-     * @since 4.6.x
1488
-     * @param string $field_name       The field the current time is needed for.
1489
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1490
-     *                                 formatted string matching the set format for the field in the set timezone will
1491
-     *                                 be returned.
1492
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1493
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1494
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1495
-     *                                 exception is triggered.
1496
-     */
1497
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1498
-    {
1499
-        $formats = $this->get_formats_for($field_name);
1500
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1501
-        if ($timestamp) {
1502
-            return $DateTime->format('U');
1503
-        }
1504
-        //not returning timestamp, so return formatted string in timezone.
1505
-        switch ($what) {
1506
-            case 'time' :
1507
-                return $DateTime->format($formats[1]);
1508
-                break;
1509
-            case 'date' :
1510
-                return $DateTime->format($formats[0]);
1511
-                break;
1512
-            default :
1513
-                return $DateTime->format(implode(' ', $formats));
1514
-                break;
1515
-        }
1516
-    }
1517
-
1518
-
1519
-
1520
-    /**
1521
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1522
-     * for the model are.  Returns a DateTime object.
1523
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1524
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1525
-     * ignored.
1526
-     *
1527
-     * @param string $field_name      The field being setup.
1528
-     * @param string $timestring      The date time string being used.
1529
-     * @param string $incoming_format The format for the time string.
1530
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1531
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1532
-     *                                format is
1533
-     *                                'U', this is ignored.
1534
-     * @return DateTime
1535
-     * @throws \EE_Error
1536
-     */
1537
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1538
-    {
1539
-        //just using this to ensure the timezone is set correctly internally
1540
-        $this->get_formats_for($field_name);
1541
-        //load EEH_DTT_Helper
1542
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1543
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1544
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1545
-    }
1546
-
1547
-
1548
-
1549
-    /**
1550
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1551
-     *
1552
-     * @return EE_Table_Base[]
1553
-     */
1554
-    public function get_tables()
1555
-    {
1556
-        return $this->_tables;
1557
-    }
1558
-
1559
-
1560
-
1561
-    /**
1562
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1563
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1564
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1565
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1566
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1567
-     * model object with EVT_ID = 1
1568
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1569
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1570
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1571
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1572
-     * are not specified)
1573
-     *
1574
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1575
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1576
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1577
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1578
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1579
-     *                                         ID=34, we'd use this method as follows:
1580
-     *                                         EEM_Transaction::instance()->update(
1581
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1582
-     *                                         array(array('TXN_ID'=>34)));
1583
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1584
-     *                                         in client code into what's expected to be stored on each field. Eg,
1585
-     *                                         consider updating Question's QST_admin_label field is of type
1586
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1587
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1588
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1589
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1590
-     *                                         TRUE, it is assumed that you've already called
1591
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1592
-     *                                         malicious javascript. However, if
1593
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1594
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1595
-     *                                         and every other field, before insertion. We provide this parameter
1596
-     *                                         because model objects perform their prepare_for_set function on all
1597
-     *                                         their values, and so don't need to be called again (and in many cases,
1598
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1599
-     *                                         prepare_for_set method...)
1600
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1601
-     *                                         in this model's entity map according to $fields_n_values that match
1602
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1603
-     *                                         by setting this to FALSE, but be aware that model objects being used
1604
-     *                                         could get out-of-sync with the database
1605
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1606
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1607
-     *                                         bad)
1608
-     * @throws \EE_Error
1609
-     */
1610
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1611
-    {
1612
-        if (! is_array($query_params)) {
1613
-            EE_Error::doing_it_wrong('EEM_Base::update',
1614
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1615
-                    gettype($query_params)), '4.6.0');
1616
-            $query_params = array();
1617
-        }
1618
-        /**
1619
-         * Action called before a model update call has been made.
1620
-         *
1621
-         * @param EEM_Base $model
1622
-         * @param array    $fields_n_values the updated fields and their new values
1623
-         * @param array    $query_params    @see EEM_Base::get_all()
1624
-         */
1625
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1626
-        /**
1627
-         * Filters the fields about to be updated given the query parameters. You can provide the
1628
-         * $query_params to $this->get_all() to find exactly which records will be updated
1629
-         *
1630
-         * @param array    $fields_n_values fields and their new values
1631
-         * @param EEM_Base $model           the model being queried
1632
-         * @param array    $query_params    see EEM_Base::get_all()
1633
-         */
1634
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1635
-            $query_params);
1636
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1637
-        //to do that, for each table, verify that it's PK isn't null.
1638
-        $tables = $this->get_tables();
1639
-        //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
1640
-        //NOTE: we should make this code more efficient by NOT querying twice
1641
-        //before the real update, but that needs to first go through ALPHA testing
1642
-        //as it's dangerous. says Mike August 8 2014
1643
-        //we want to make sure the default_where strategy is ignored
1644
-        $this->_ignore_where_strategy = true;
1645
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1646
-        foreach ($wpdb_select_results as $wpdb_result) {
1647
-            // type cast stdClass as array
1648
-            $wpdb_result = (array)$wpdb_result;
1649
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1650
-            if ($this->has_primary_key_field()) {
1651
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1652
-            } else {
1653
-                //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)
1654
-                $main_table_pk_value = null;
1655
-            }
1656
-            //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
1657
-            //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
1658
-            if (count($tables) > 1) {
1659
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1660
-                //in that table, and so we'll want to insert one
1661
-                foreach ($tables as $table_obj) {
1662
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1663
-                    //if there is no private key for this table on the results, it means there's no entry
1664
-                    //in this table, right? so insert a row in the current table, using any fields available
1665
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1666
-                           && $wpdb_result[$this_table_pk_column])
1667
-                    ) {
1668
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1669
-                            $main_table_pk_value);
1670
-                        //if we died here, report the error
1671
-                        if (! $success) {
1672
-                            return false;
1673
-                        }
1674
-                    }
1675
-                }
1676
-            }
1677
-            //				//and now check that if we have cached any models by that ID on the model, that
1678
-            //				//they also get updated properly
1679
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1680
-            //				if( $model_object ){
1681
-            //					foreach( $fields_n_values as $field => $value ){
1682
-            //						$model_object->set($field, $value);
1683
-            //let's make sure default_where strategy is followed now
1684
-            $this->_ignore_where_strategy = false;
1685
-        }
1686
-        //if we want to keep model objects in sync, AND
1687
-        //if this wasn't called from a model object (to update itself)
1688
-        //then we want to make sure we keep all the existing
1689
-        //model objects in sync with the db
1690
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1691
-            if ($this->has_primary_key_field()) {
1692
-                $model_objs_affected_ids = $this->get_col($query_params);
1693
-            } else {
1694
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1695
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1696
-                $model_objs_affected_ids = array();
1697
-                foreach ($models_affected_key_columns as $row) {
1698
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1699
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1700
-                }
1701
-            }
1702
-            if (! $model_objs_affected_ids) {
1703
-                //wait wait wait- if nothing was affected let's stop here
1704
-                return 0;
1705
-            }
1706
-            foreach ($model_objs_affected_ids as $id) {
1707
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1708
-                if ($model_obj_in_entity_map) {
1709
-                    foreach ($fields_n_values as $field => $new_value) {
1710
-                        $model_obj_in_entity_map->set($field, $new_value);
1711
-                    }
1712
-                }
1713
-            }
1714
-            //if there is a primary key on this model, we can now do a slight optimization
1715
-            if ($this->has_primary_key_field()) {
1716
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1717
-                $query_params = array(
1718
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1719
-                    'limit'                    => count($model_objs_affected_ids),
1720
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1721
-                );
1722
-            }
1723
-        }
1724
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1725
-        $SQL = "UPDATE "
1726
-               . $model_query_info->get_full_join_sql()
1727
-               . " SET "
1728
-               . $this->_construct_update_sql($fields_n_values)
1729
-               . $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
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1731
-        /**
1732
-         * Action called after a model update call has been made.
1733
-         *
1734
-         * @param EEM_Base $model
1735
-         * @param array    $fields_n_values the updated fields and their new values
1736
-         * @param array    $query_params    @see EEM_Base::get_all()
1737
-         * @param int      $rows_affected
1738
-         */
1739
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1740
-        return $rows_affected;//how many supposedly got updated
1741
-    }
1742
-
1743
-
1744
-
1745
-    /**
1746
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1747
-     * are teh values of the field specified (or by default the primary key field)
1748
-     * that matched the query params. Note that you should pass the name of the
1749
-     * model FIELD, not the database table's column name.
1750
-     *
1751
-     * @param array  $query_params @see EEM_Base::get_all()
1752
-     * @param string $field_to_select
1753
-     * @return array just like $wpdb->get_col()
1754
-     * @throws \EE_Error
1755
-     */
1756
-    public function get_col($query_params = array(), $field_to_select = null)
1757
-    {
1758
-        if ($field_to_select) {
1759
-            $field = $this->field_settings_for($field_to_select);
1760
-        } elseif ($this->has_primary_key_field()) {
1761
-            $field = $this->get_primary_key_field();
1762
-        } else {
1763
-            //no primary key, just grab the first column
1764
-            $field = reset($this->field_settings());
1765
-        }
1766
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1767
-        $select_expressions = $field->get_qualified_column();
1768
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1769
-        return $this->_do_wpdb_query('get_col', array($SQL));
1770
-    }
1771
-
1772
-
1773
-
1774
-    /**
1775
-     * Returns a single column value for a single row from the database
1776
-     *
1777
-     * @param array  $query_params    @see EEM_Base::get_all()
1778
-     * @param string $field_to_select @see EEM_Base::get_col()
1779
-     * @return string
1780
-     * @throws \EE_Error
1781
-     */
1782
-    public function get_var($query_params = array(), $field_to_select = null)
1783
-    {
1784
-        $query_params['limit'] = 1;
1785
-        $col = $this->get_col($query_params, $field_to_select);
1786
-        if (! empty($col)) {
1787
-            return reset($col);
1788
-        } else {
1789
-            return null;
1790
-        }
1791
-    }
1792
-
1793
-
1794
-
1795
-    /**
1796
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1797
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1798
-     * injection, but currently no further filtering is done
1799
-     *
1800
-     * @global      $wpdb
1801
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1802
-     *                               be updated to in the DB
1803
-     * @return string of SQL
1804
-     * @throws \EE_Error
1805
-     */
1806
-    public function _construct_update_sql($fields_n_values)
1807
-    {
1808
-        /** @type WPDB $wpdb */
1809
-        global $wpdb;
1810
-        $cols_n_values = array();
1811
-        foreach ($fields_n_values as $field_name => $value) {
1812
-            $field_obj = $this->field_settings_for($field_name);
1813
-            //if the value is NULL, we want to assign the value to that.
1814
-            //wpdb->prepare doesn't really handle that properly
1815
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1816
-            $value_sql = $prepared_value === null ? 'NULL'
1817
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1818
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1819
-        }
1820
-        return implode(",", $cols_n_values);
1821
-    }
1822
-
1823
-
1824
-
1825
-    /**
1826
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1827
-     * Performs a HARD delete, meaning the database row should always be removed,
1828
-     * not just have a flag field on it switched
1829
-     * Wrapper for EEM_Base::delete_permanently()
1830
-     *
1831
-     * @param mixed $id
1832
-     * @return boolean whether the row got deleted or not
1833
-     * @throws \EE_Error
1834
-     */
1835
-    public function delete_permanently_by_ID($id)
1836
-    {
1837
-        return $this->delete_permanently(
1838
-            array(
1839
-                array($this->get_primary_key_field()->get_name() => $id),
1840
-                'limit' => 1,
1841
-            )
1842
-        );
1843
-    }
1844
-
1845
-
1846
-
1847
-    /**
1848
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1849
-     * Wrapper for EEM_Base::delete()
1850
-     *
1851
-     * @param mixed $id
1852
-     * @return boolean whether the row got deleted or not
1853
-     * @throws \EE_Error
1854
-     */
1855
-    public function delete_by_ID($id)
1856
-    {
1857
-        return $this->delete(
1858
-            array(
1859
-                array($this->get_primary_key_field()->get_name() => $id),
1860
-                'limit' => 1,
1861
-            )
1862
-        );
1863
-    }
1864
-
1865
-
1866
-
1867
-    /**
1868
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1869
-     * meaning if the model has a field that indicates its been "trashed" or
1870
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1871
-     *
1872
-     * @see EEM_Base::delete_permanently
1873
-     * @param array   $query_params
1874
-     * @param boolean $allow_blocking
1875
-     * @return int how many rows got deleted
1876
-     * @throws \EE_Error
1877
-     */
1878
-    public function delete($query_params, $allow_blocking = true)
1879
-    {
1880
-        return $this->delete_permanently($query_params, $allow_blocking);
1881
-    }
1882
-
1883
-
1884
-
1885
-    /**
1886
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1887
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1888
-     * as archived, not actually deleted
1889
-     *
1890
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1891
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1892
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1893
-     *                                deletes regardless of other objects which may depend on it. Its generally
1894
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1895
-     *                                DB
1896
-     * @return int how many rows got deleted
1897
-     * @throws \EE_Error
1898
-     */
1899
-    public function delete_permanently($query_params, $allow_blocking = true)
1900
-    {
1901
-        /**
1902
-         * Action called just before performing a real deletion query. You can use the
1903
-         * model and its $query_params to find exactly which items will be deleted
1904
-         *
1905
-         * @param EEM_Base $model
1906
-         * @param array    $query_params   @see EEM_Base::get_all()
1907
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1908
-         *                                 to block (prevent) this deletion
1909
-         */
1910
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1911
-        //some MySQL databases may be running safe mode, which may restrict
1912
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1913
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1914
-        //to delete them
1915
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1916
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1917
-        if ($deletion_where) {
1918
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1919
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1920
-            $table_aliases = array_keys($this->_tables);
1921
-            $SQL = "DELETE "
1922
-                   . implode(", ", $table_aliases)
1923
-                   . " FROM "
1924
-                   . $model_query_info->get_full_join_sql()
1925
-                   . " WHERE "
1926
-                   . $deletion_where;
1927
-            //		/echo "delete sql:$SQL";
1928
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1929
-        } else {
1930
-            $rows_deleted = 0;
1931
-        }
1932
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1933
-        if ($this->has_primary_key_field()) {
1934
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1935
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1936
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1937
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1938
-                }
1939
-            }
1940
-        }
1941
-        /**
1942
-         * Action called just after performing a real deletion query. Although at this point the
1943
-         * items should have been deleted
1944
-         *
1945
-         * @param EEM_Base $model
1946
-         * @param array    $query_params @see EEM_Base::get_all()
1947
-         * @param int      $rows_deleted
1948
-         */
1949
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1950
-        return $rows_deleted;//how many supposedly got deleted
1951
-    }
1952
-
1953
-
1954
-
1955
-    /**
1956
-     * Checks all the relations that throw error messages when there are blocking related objects
1957
-     * for related model objects. If there are any related model objects on those relations,
1958
-     * adds an EE_Error, and return true
1959
-     *
1960
-     * @param EE_Base_Class|int $this_model_obj_or_id
1961
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1962
-     *                                                 should be ignored when determining whether there are related
1963
-     *                                                 model objects which block this model object's deletion. Useful
1964
-     *                                                 if you know A is related to B and are considering deleting A,
1965
-     *                                                 but want to see if A has any other objects blocking its deletion
1966
-     *                                                 before removing the relation between A and B
1967
-     * @return boolean
1968
-     * @throws \EE_Error
1969
-     */
1970
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1971
-    {
1972
-        //first, if $ignore_this_model_obj was supplied, get its model
1973
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1974
-            $ignored_model = $ignore_this_model_obj->get_model();
1975
-        } else {
1976
-            $ignored_model = null;
1977
-        }
1978
-        //now check all the relations of $this_model_obj_or_id and see if there
1979
-        //are any related model objects blocking it?
1980
-        $is_blocked = false;
1981
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
1982
-            if ($relation_obj->block_delete_if_related_models_exist()) {
1983
-                //if $ignore_this_model_obj was supplied, then for the query
1984
-                //on that model needs to be told to ignore $ignore_this_model_obj
1985
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1986
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1987
-                        array(
1988
-                            $ignored_model->get_primary_key_field()->get_name() => array(
1989
-                                '!=',
1990
-                                $ignore_this_model_obj->ID(),
1991
-                            ),
1992
-                        ),
1993
-                    ));
1994
-                } else {
1995
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1996
-                }
1997
-                if ($related_model_objects) {
1998
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1999
-                    $is_blocked = true;
2000
-                }
2001
-            }
2002
-        }
2003
-        return $is_blocked;
2004
-    }
2005
-
2006
-
2007
-
2008
-    /**
2009
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2010
-     * well.
2011
-     *
2012
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2013
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2014
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
2015
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
2016
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
2017
-     *                                      easily corrupt your DB
2018
-     * @throws EE_Error
2019
-     * @return string    everything that comes after the WHERE statement.
2020
-     */
2021
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2022
-    {
2023
-        if ($this->has_primary_key_field()) {
2024
-            $primary_table = $this->_get_main_table();
2025
-            $other_tables = $this->_get_other_tables();
2026
-            $deletes = $query = array();
2027
-            foreach ($objects_for_deletion as $delete_object) {
2028
-                //before we mark this object for deletion,
2029
-                //make sure there's no related objects blocking its deletion (if we're checking)
2030
-                if (
2031
-                    $allow_blocking
2032
-                    && $this->delete_is_blocked_by_related_models(
2033
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
2034
-                    )
2035
-                ) {
2036
-                    continue;
2037
-                }
2038
-                //primary table deletes
2039
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2040
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2041
-                }
2042
-                //other tables
2043
-                if (! empty($other_tables)) {
2044
-                    foreach ($other_tables as $ot) {
2045
-                        //first check if we've got the foreign key column here.
2046
-                        if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2047
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2048
-                        }
2049
-                        // wait! it's entirely possible that we'll have a the primary key
2050
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
2051
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2052
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2053
-                        }
2054
-                        // finally, it is possible that the fk for this table is found
2055
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
2056
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2057
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2058
-                        }
2059
-                    }
2060
-                }
2061
-            }
2062
-            //we should have deletes now, so let's just go through and setup the where statement
2063
-            foreach ($deletes as $column => $values) {
2064
-                //make sure we have unique $values;
2065
-                $values = array_unique($values);
2066
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2067
-            }
2068
-            return ! empty($query) ? implode(' AND ', $query) : '';
2069
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2070
-            $ways_to_identify_a_row = array();
2071
-            $fields = $this->get_combined_primary_key_fields();
2072
-            //note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2073
-            foreach ($objects_for_deletion as $delete_object) {
2074
-                $values_for_each_cpk_for_a_row = array();
2075
-                foreach ($fields as $cpk_field) {
2076
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2077
-                        $values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2078
-                                                           . "="
2079
-                                                           . $delete_object[$cpk_field->get_qualified_column()];
2080
-                    }
2081
-                }
2082
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2083
-            }
2084
-            return implode(" OR ", $ways_to_identify_a_row);
2085
-        } else {
2086
-            //so there's no primary key and no combined key...
2087
-            //sorry, can't help you
2088
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2089
-                "event_espresso"), get_class($this)));
2090
-        }
2091
-    }
2092
-
2093
-
2094
-
2095
-    /**
2096
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2097
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2098
-     * column
2099
-     *
2100
-     * @param array  $query_params   like EEM_Base::get_all's
2101
-     * @param string $field_to_count field on model to count by (not column name)
2102
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2103
-     *                               that by the setting $distinct to TRUE;
2104
-     * @return int
2105
-     * @throws \EE_Error
2106
-     */
2107
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2108
-    {
2109
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2110
-        if ($field_to_count) {
2111
-            $field_obj = $this->field_settings_for($field_to_count);
2112
-            $column_to_count = $field_obj->get_qualified_column();
2113
-        } elseif ($this->has_primary_key_field()) {
2114
-            $pk_field_obj = $this->get_primary_key_field();
2115
-            $column_to_count = $pk_field_obj->get_qualified_column();
2116
-        } else {
2117
-            //there's no primary key
2118
-            //if we're counting distinct items, and there's no primary key,
2119
-            //we need to list out the columns for distinction;
2120
-            //otherwise we can just use star
2121
-            if ($distinct) {
2122
-                $columns_to_use = array();
2123
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2124
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2125
-                }
2126
-                $column_to_count = implode(',', $columns_to_use);
2127
-            } else {
2128
-                $column_to_count = '*';
2129
-            }
2130
-        }
2131
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2132
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2133
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2134
-    }
2135
-
2136
-
2137
-
2138
-    /**
2139
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2140
-     *
2141
-     * @param array  $query_params like EEM_Base::get_all
2142
-     * @param string $field_to_sum name of field (array key in $_fields array)
2143
-     * @return float
2144
-     * @throws \EE_Error
2145
-     */
2146
-    public function sum($query_params, $field_to_sum = null)
2147
-    {
2148
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2149
-        if ($field_to_sum) {
2150
-            $field_obj = $this->field_settings_for($field_to_sum);
2151
-        } else {
2152
-            $field_obj = $this->get_primary_key_field();
2153
-        }
2154
-        $column_to_count = $field_obj->get_qualified_column();
2155
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2156
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2157
-        $data_type = $field_obj->get_wpdb_data_type();
2158
-        if ($data_type === '%d' || $data_type === '%s') {
2159
-            return (float)$return_value;
2160
-        } else {//must be %f
2161
-            return (float)$return_value;
2162
-        }
2163
-    }
2164
-
2165
-
2166
-
2167
-    /**
2168
-     * Just calls the specified method on $wpdb with the given arguments
2169
-     * Consolidates a little extra error handling code
2170
-     *
2171
-     * @param string $wpdb_method
2172
-     * @param array  $arguments_to_provide
2173
-     * @throws EE_Error
2174
-     * @global wpdb  $wpdb
2175
-     * @return mixed
2176
-     */
2177
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2178
-    {
2179
-        //if we're in maintenance mode level 2, DON'T run any queries
2180
-        //because level 2 indicates the database needs updating and
2181
-        //is probably out of sync with the code
2182
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2183
-            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.",
2184
-                "event_espresso")));
2185
-        }
2186
-        /** @type WPDB $wpdb */
2187
-        global $wpdb;
2188
-        if (! method_exists($wpdb, $wpdb_method)) {
2189
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2190
-                'event_espresso'), $wpdb_method));
2191
-        }
2192
-        if (WP_DEBUG) {
2193
-            $old_show_errors_value = $wpdb->show_errors;
2194
-            $wpdb->show_errors(false);
2195
-        }
2196
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2197
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2198
-        if (WP_DEBUG) {
2199
-            $wpdb->show_errors($old_show_errors_value);
2200
-            if (! empty($wpdb->last_error)) {
2201
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2202
-            } elseif ($result === false) {
2203
-                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"',
2204
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2205
-            }
2206
-        } elseif ($result === false) {
2207
-            EE_Error::add_error(
2208
-                sprintf(
2209
-                    __('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"',
2210
-                        'event_espresso'),
2211
-                    $wpdb_method,
2212
-                    var_export($arguments_to_provide, true),
2213
-                    $wpdb->last_error
2214
-                ),
2215
-                __FILE__,
2216
-                __FUNCTION__,
2217
-                __LINE__
2218
-            );
2219
-        }
2220
-        return $result;
2221
-    }
2222
-
2223
-
2224
-
2225
-    /**
2226
-     * Attempts to run the indicated WPDB method with the provided arguments,
2227
-     * and if there's an error tries to verify the DB is correct. Uses
2228
-     * the static property EEM_Base::$_db_verification_level to determine whether
2229
-     * we should try to fix the EE core db, the addons, or just give up
2230
-     *
2231
-     * @param string $wpdb_method
2232
-     * @param array  $arguments_to_provide
2233
-     * @return mixed
2234
-     */
2235
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2236
-    {
2237
-        /** @type WPDB $wpdb */
2238
-        global $wpdb;
2239
-        $wpdb->last_error = null;
2240
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2241
-        // was there an error running the query? but we don't care on new activations
2242
-        // (we're going to setup the DB anyway on new activations)
2243
-        if (($result === false || ! empty($wpdb->last_error))
2244
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2245
-        ) {
2246
-            switch (EEM_Base::$_db_verification_level) {
2247
-                case EEM_Base::db_verified_none :
2248
-                    // let's double-check core's DB
2249
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2250
-                    break;
2251
-                case EEM_Base::db_verified_core :
2252
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2253
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2254
-                    break;
2255
-                case EEM_Base::db_verified_addons :
2256
-                    // ummmm... you in trouble
2257
-                    return $result;
2258
-                    break;
2259
-            }
2260
-            if (! empty($error_message)) {
2261
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2262
-                trigger_error($error_message);
2263
-            }
2264
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2265
-        }
2266
-        return $result;
2267
-    }
2268
-
2269
-
2270
-
2271
-    /**
2272
-     * Verifies the EE core database is up-to-date and records that we've done it on
2273
-     * EEM_Base::$_db_verification_level
2274
-     *
2275
-     * @param string $wpdb_method
2276
-     * @param array  $arguments_to_provide
2277
-     * @return string
2278
-     */
2279
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2280
-    {
2281
-        /** @type WPDB $wpdb */
2282
-        global $wpdb;
2283
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2284
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2285
-        $error_message = sprintf(
2286
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2287
-                'event_espresso'),
2288
-            $wpdb->last_error,
2289
-            $wpdb_method,
2290
-            wp_json_encode($arguments_to_provide)
2291
-        );
2292
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2293
-        return $error_message;
2294
-    }
2295
-
2296
-
2297
-
2298
-    /**
2299
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2300
-     * EEM_Base::$_db_verification_level
2301
-     *
2302
-     * @param $wpdb_method
2303
-     * @param $arguments_to_provide
2304
-     * @return string
2305
-     */
2306
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2307
-    {
2308
-        /** @type WPDB $wpdb */
2309
-        global $wpdb;
2310
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2311
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2312
-        $error_message = sprintf(
2313
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2314
-                'event_espresso'),
2315
-            $wpdb->last_error,
2316
-            $wpdb_method,
2317
-            wp_json_encode($arguments_to_provide)
2318
-        );
2319
-        EE_System::instance()->initialize_addons();
2320
-        return $error_message;
2321
-    }
2322
-
2323
-
2324
-
2325
-    /**
2326
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2327
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2328
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2329
-     * ..."
2330
-     *
2331
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2332
-     * @return string
2333
-     */
2334
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2335
-    {
2336
-        return " FROM " . $model_query_info->get_full_join_sql() .
2337
-               $model_query_info->get_where_sql() .
2338
-               $model_query_info->get_group_by_sql() .
2339
-               $model_query_info->get_having_sql() .
2340
-               $model_query_info->get_order_by_sql() .
2341
-               $model_query_info->get_limit_sql();
2342
-    }
2343
-
2344
-
2345
-
2346
-    /**
2347
-     * Set to easily debug the next X queries ran from this model.
2348
-     *
2349
-     * @param int $count
2350
-     */
2351
-    public function show_next_x_db_queries($count = 1)
2352
-    {
2353
-        $this->_show_next_x_db_queries = $count;
2354
-    }
2355
-
2356
-
2357
-
2358
-    /**
2359
-     * @param $sql_query
2360
-     */
2361
-    public function show_db_query_if_previously_requested($sql_query)
2362
-    {
2363
-        if ($this->_show_next_x_db_queries > 0) {
2364
-            echo $sql_query;
2365
-            $this->_show_next_x_db_queries--;
2366
-        }
2367
-    }
2368
-
2369
-
2370
-
2371
-    /**
2372
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2373
-     * There are the 3 cases:
2374
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2375
-     * $otherModelObject has no ID, it is first saved.
2376
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2377
-     * has no ID, it is first saved.
2378
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2379
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2380
-     * join table
2381
-     *
2382
-     * @param        EE_Base_Class                     /int $thisModelObject
2383
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2384
-     * @param string $relationName                     , key in EEM_Base::_relations
2385
-     *                                                 an attendee to a group, you also want to specify which role they
2386
-     *                                                 will have in that group. So you would use this parameter to
2387
-     *                                                 specify array('role-column-name'=>'role-id')
2388
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2389
-     *                                                 to for relation to methods that allow you to further specify
2390
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2391
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2392
-     *                                                 because these will be inserted in any new rows created as well.
2393
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2394
-     * @throws \EE_Error
2395
-     */
2396
-    public function add_relationship_to(
2397
-        $id_or_obj,
2398
-        $other_model_id_or_obj,
2399
-        $relationName,
2400
-        $extra_join_model_fields_n_values = array()
2401
-    ) {
2402
-        $relation_obj = $this->related_settings_for($relationName);
2403
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2404
-    }
2405
-
2406
-
2407
-
2408
-    /**
2409
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2410
-     * There are the 3 cases:
2411
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2412
-     * error
2413
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2414
-     * an error
2415
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2416
-     *
2417
-     * @param        EE_Base_Class /int $id_or_obj
2418
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2419
-     * @param string $relationName key in EEM_Base::_relations
2420
-     * @return boolean of success
2421
-     * @throws \EE_Error
2422
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2423
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2424
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2425
-     *                             because these will be inserted in any new rows created as well.
2426
-     */
2427
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2428
-    {
2429
-        $relation_obj = $this->related_settings_for($relationName);
2430
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2431
-    }
2432
-
2433
-
2434
-
2435
-    /**
2436
-     * @param mixed           $id_or_obj
2437
-     * @param string          $relationName
2438
-     * @param array           $where_query_params
2439
-     * @param EE_Base_Class[] objects to which relations were removed
2440
-     * @return \EE_Base_Class[]
2441
-     * @throws \EE_Error
2442
-     */
2443
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2444
-    {
2445
-        $relation_obj = $this->related_settings_for($relationName);
2446
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2447
-    }
2448
-
2449
-
2450
-
2451
-    /**
2452
-     * Gets all the related items of the specified $model_name, using $query_params.
2453
-     * Note: by default, we remove the "default query params"
2454
-     * because we want to get even deleted items etc.
2455
-     *
2456
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2457
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2458
-     * @param array  $query_params like EEM_Base::get_all
2459
-     * @return EE_Base_Class[]
2460
-     * @throws \EE_Error
2461
-     */
2462
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2463
-    {
2464
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2465
-        $relation_settings = $this->related_settings_for($model_name);
2466
-        return $relation_settings->get_all_related($model_obj, $query_params);
2467
-    }
2468
-
2469
-
2470
-
2471
-    /**
2472
-     * Deletes all the model objects across the relation indicated by $model_name
2473
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2474
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2475
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2476
-     *
2477
-     * @param EE_Base_Class|int|string $id_or_obj
2478
-     * @param string                   $model_name
2479
-     * @param array                    $query_params
2480
-     * @return int how many deleted
2481
-     * @throws \EE_Error
2482
-     */
2483
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2484
-    {
2485
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2486
-        $relation_settings = $this->related_settings_for($model_name);
2487
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2488
-    }
2489
-
2490
-
2491
-
2492
-    /**
2493
-     * Hard deletes all the model objects across the relation indicated by $model_name
2494
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2495
-     * the model objects can't be hard deleted because of blocking related model objects,
2496
-     * just does a soft-delete on them instead.
2497
-     *
2498
-     * @param EE_Base_Class|int|string $id_or_obj
2499
-     * @param string                   $model_name
2500
-     * @param array                    $query_params
2501
-     * @return int how many deleted
2502
-     * @throws \EE_Error
2503
-     */
2504
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2505
-    {
2506
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2507
-        $relation_settings = $this->related_settings_for($model_name);
2508
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2509
-    }
2510
-
2511
-
2512
-
2513
-    /**
2514
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2515
-     * unless otherwise specified in the $query_params
2516
-     *
2517
-     * @param        int             /EE_Base_Class $id_or_obj
2518
-     * @param string $model_name     like 'Event', or 'Registration'
2519
-     * @param array  $query_params   like EEM_Base::get_all's
2520
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2521
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2522
-     *                               that by the setting $distinct to TRUE;
2523
-     * @return int
2524
-     * @throws \EE_Error
2525
-     */
2526
-    public function count_related(
2527
-        $id_or_obj,
2528
-        $model_name,
2529
-        $query_params = array(),
2530
-        $field_to_count = null,
2531
-        $distinct = false
2532
-    ) {
2533
-        $related_model = $this->get_related_model_obj($model_name);
2534
-        //we're just going to use the query params on the related model's normal get_all query,
2535
-        //except add a condition to say to match the current mod
2536
-        if (! isset($query_params['default_where_conditions'])) {
2537
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2538
-        }
2539
-        $this_model_name = $this->get_this_model_name();
2540
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2541
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2542
-        return $related_model->count($query_params, $field_to_count, $distinct);
2543
-    }
2544
-
2545
-
2546
-
2547
-    /**
2548
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2549
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2550
-     *
2551
-     * @param        int           /EE_Base_Class $id_or_obj
2552
-     * @param string $model_name   like 'Event', or 'Registration'
2553
-     * @param array  $query_params like EEM_Base::get_all's
2554
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2555
-     * @return float
2556
-     * @throws \EE_Error
2557
-     */
2558
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2559
-    {
2560
-        $related_model = $this->get_related_model_obj($model_name);
2561
-        if (! is_array($query_params)) {
2562
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2563
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2564
-                    gettype($query_params)), '4.6.0');
2565
-            $query_params = array();
2566
-        }
2567
-        //we're just going to use the query params on the related model's normal get_all query,
2568
-        //except add a condition to say to match the current mod
2569
-        if (! isset($query_params['default_where_conditions'])) {
2570
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2571
-        }
2572
-        $this_model_name = $this->get_this_model_name();
2573
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2574
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2575
-        return $related_model->sum($query_params, $field_to_sum);
2576
-    }
2577
-
2578
-
2579
-
2580
-    /**
2581
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2582
-     * $modelObject
2583
-     *
2584
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2585
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2586
-     * @param array               $query_params     like EEM_Base::get_all's
2587
-     * @return EE_Base_Class
2588
-     * @throws \EE_Error
2589
-     */
2590
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2591
-    {
2592
-        $query_params['limit'] = 1;
2593
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2594
-        if ($results) {
2595
-            return array_shift($results);
2596
-        } else {
2597
-            return null;
2598
-        }
2599
-    }
2600
-
2601
-
2602
-
2603
-    /**
2604
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2605
-     *
2606
-     * @return string
2607
-     */
2608
-    public function get_this_model_name()
2609
-    {
2610
-        return str_replace("EEM_", "", get_class($this));
2611
-    }
2612
-
2613
-
2614
-
2615
-    /**
2616
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2617
-     *
2618
-     * @return EE_Any_Foreign_Model_Name_Field
2619
-     * @throws EE_Error
2620
-     */
2621
-    public function get_field_containing_related_model_name()
2622
-    {
2623
-        foreach ($this->field_settings(true) as $field) {
2624
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2625
-                $field_with_model_name = $field;
2626
-            }
2627
-        }
2628
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2629
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2630
-                $this->get_this_model_name()));
2631
-        }
2632
-        return $field_with_model_name;
2633
-    }
2634
-
2635
-
2636
-
2637
-    /**
2638
-     * Inserts a new entry into the database, for each table.
2639
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2640
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2641
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2642
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2643
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2644
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2645
-     *
2646
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2647
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2648
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2649
-     *                              of EEM_Base)
2650
-     * @return int new primary key on main table that got inserted
2651
-     * @throws EE_Error
2652
-     */
2653
-    public function insert($field_n_values)
2654
-    {
2655
-        /**
2656
-         * Filters the fields and their values before inserting an item using the models
2657
-         *
2658
-         * @param array    $fields_n_values keys are the fields and values are their new values
2659
-         * @param EEM_Base $model           the model used
2660
-         */
2661
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2662
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2663
-            $main_table = $this->_get_main_table();
2664
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2665
-            if ($new_id !== false) {
2666
-                foreach ($this->_get_other_tables() as $other_table) {
2667
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2668
-                }
2669
-            }
2670
-            /**
2671
-             * Done just after attempting to insert a new model object
2672
-             *
2673
-             * @param EEM_Base   $model           used
2674
-             * @param array      $fields_n_values fields and their values
2675
-             * @param int|string the              ID of the newly-inserted model object
2676
-             */
2677
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2678
-            return $new_id;
2679
-        } else {
2680
-            return false;
2681
-        }
2682
-    }
2683
-
2684
-
2685
-
2686
-    /**
2687
-     * Checks that the result would satisfy the unique indexes on this model
2688
-     *
2689
-     * @param array  $field_n_values
2690
-     * @param string $action
2691
-     * @return boolean
2692
-     * @throws \EE_Error
2693
-     */
2694
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2695
-    {
2696
-        foreach ($this->unique_indexes() as $index_name => $index) {
2697
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2698
-            if ($this->exists(array($uniqueness_where_params))) {
2699
-                EE_Error::add_error(
2700
-                    sprintf(
2701
-                        __(
2702
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2703
-                            "event_espresso"
2704
-                        ),
2705
-                        $action,
2706
-                        $this->_get_class_name(),
2707
-                        $index_name,
2708
-                        implode(",", $index->field_names()),
2709
-                        http_build_query($uniqueness_where_params)
2710
-                    ),
2711
-                    __FILE__,
2712
-                    __FUNCTION__,
2713
-                    __LINE__
2714
-                );
2715
-                return false;
2716
-            }
2717
-        }
2718
-        return true;
2719
-    }
2720
-
2721
-
2722
-
2723
-    /**
2724
-     * Checks the database for an item that conflicts (ie, if this item were
2725
-     * saved to the DB would break some uniqueness requirement, like a primary key
2726
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2727
-     * can be either an EE_Base_Class or an array of fields n values
2728
-     *
2729
-     * @param EE_Base_Class|array $obj_or_fields_array
2730
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2731
-     *                                                 when looking for conflicts
2732
-     *                                                 (ie, if false, we ignore the model object's primary key
2733
-     *                                                 when finding "conflicts". If true, it's also considered).
2734
-     *                                                 Only works for INT primary key,
2735
-     *                                                 STRING primary keys cannot be ignored
2736
-     * @throws EE_Error
2737
-     * @return EE_Base_Class|array
2738
-     */
2739
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2740
-    {
2741
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2742
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2743
-        } elseif (is_array($obj_or_fields_array)) {
2744
-            $fields_n_values = $obj_or_fields_array;
2745
-        } else {
2746
-            throw new EE_Error(
2747
-                sprintf(
2748
-                    __(
2749
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2750
-                        "event_espresso"
2751
-                    ),
2752
-                    get_class($this),
2753
-                    $obj_or_fields_array
2754
-                )
2755
-            );
2756
-        }
2757
-        $query_params = array();
2758
-        if ($this->has_primary_key_field()
2759
-            && ($include_primary_key
2760
-                || $this->get_primary_key_field()
2761
-                   instanceof
2762
-                   EE_Primary_Key_String_Field)
2763
-            && isset($fields_n_values[$this->primary_key_name()])
2764
-        ) {
2765
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2766
-        }
2767
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2768
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2769
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2770
-        }
2771
-        //if there is nothing to base this search on, then we shouldn't find anything
2772
-        if (empty($query_params)) {
2773
-            return array();
2774
-        } else {
2775
-            return $this->get_one($query_params);
2776
-        }
2777
-    }
2778
-
2779
-
2780
-
2781
-    /**
2782
-     * Like count, but is optimized and returns a boolean instead of an int
2783
-     *
2784
-     * @param array $query_params
2785
-     * @return boolean
2786
-     * @throws \EE_Error
2787
-     */
2788
-    public function exists($query_params)
2789
-    {
2790
-        $query_params['limit'] = 1;
2791
-        return $this->count($query_params) > 0;
2792
-    }
2793
-
2794
-
2795
-
2796
-    /**
2797
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2798
-     *
2799
-     * @param int|string $id
2800
-     * @return boolean
2801
-     * @throws \EE_Error
2802
-     */
2803
-    public function exists_by_ID($id)
2804
-    {
2805
-        return $this->exists(
2806
-            array(
2807
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2808
-                array(
2809
-                    $this->primary_key_name() => $id,
2810
-                ),
2811
-            )
2812
-        );
2813
-    }
2814
-
2815
-
2816
-
2817
-    /**
2818
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2819
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2820
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2821
-     * on the main table)
2822
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2823
-     * cases where we want to call it directly rather than via insert().
2824
-     *
2825
-     * @access   protected
2826
-     * @param EE_Table_Base $table
2827
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2828
-     *                                       float
2829
-     * @param int           $new_id          for now we assume only int keys
2830
-     * @throws EE_Error
2831
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2832
-     * @return int ID of new row inserted, or FALSE on failure
2833
-     */
2834
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2835
-    {
2836
-        global $wpdb;
2837
-        $insertion_col_n_values = array();
2838
-        $format_for_insertion = array();
2839
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2840
-        foreach ($fields_on_table as $field_name => $field_obj) {
2841
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2842
-            if ($field_obj->is_auto_increment()) {
2843
-                continue;
2844
-            }
2845
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2846
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2847
-            if ($prepared_value !== null) {
2848
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2849
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2850
-            }
2851
-        }
2852
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2853
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2854
-            //so add the fk to the main table as a column
2855
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2856
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2857
-        }
2858
-        //insert the new entry
2859
-        $result = $this->_do_wpdb_query('insert',
2860
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2861
-        if ($result === false) {
2862
-            return false;
2863
-        }
2864
-        //ok, now what do we return for the ID of the newly-inserted thing?
2865
-        if ($this->has_primary_key_field()) {
2866
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2867
-                return $wpdb->insert_id;
2868
-            } else {
2869
-                //it's not an auto-increment primary key, so
2870
-                //it must have been supplied
2871
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2872
-            }
2873
-        } else {
2874
-            //we can't return a  primary key because there is none. instead return
2875
-            //a unique string indicating this model
2876
-            return $this->get_index_primary_key_string($fields_n_values);
2877
-        }
2878
-    }
2879
-
2880
-
2881
-
2882
-    /**
2883
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2884
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2885
-     * and there is no default, we pass it along. WPDB will take care of it)
2886
-     *
2887
-     * @param EE_Model_Field_Base $field_obj
2888
-     * @param array               $fields_n_values
2889
-     * @return mixed string|int|float depending on what the table column will be expecting
2890
-     * @throws \EE_Error
2891
-     */
2892
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2893
-    {
2894
-        //if this field doesn't allow nullable, don't allow it
2895
-        if (! $field_obj->is_nullable()
2896
-            && (
2897
-                ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2898
-        ) {
2899
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2900
-        }
2901
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2902
-            : null;
2903
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2904
-    }
2905
-
2906
-
2907
-
2908
-    /**
2909
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2910
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2911
-     * the field's prepare_for_set() method.
2912
-     *
2913
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2914
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2915
-     *                                   top of file)
2916
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2917
-     *                                   $value is a custom selection
2918
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2919
-     */
2920
-    private function _prepare_value_for_use_in_db($value, $field)
2921
-    {
2922
-        if ($field && $field instanceof EE_Model_Field_Base) {
2923
-            switch ($this->_values_already_prepared_by_model_object) {
2924
-                /** @noinspection PhpMissingBreakStatementInspection */
2925
-                case self::not_prepared_by_model_object:
2926
-                    $value = $field->prepare_for_set($value);
2927
-                //purposefully left out "return"
2928
-                case self::prepared_by_model_object:
2929
-                    $value = $field->prepare_for_use_in_db($value);
2930
-                case self::prepared_for_use_in_db:
2931
-                    //leave the value alone
2932
-            }
2933
-            return $value;
2934
-        } else {
2935
-            return $value;
2936
-        }
2937
-    }
2938
-
2939
-
2940
-
2941
-    /**
2942
-     * Returns the main table on this model
2943
-     *
2944
-     * @return EE_Primary_Table
2945
-     * @throws EE_Error
2946
-     */
2947
-    protected function _get_main_table()
2948
-    {
2949
-        foreach ($this->_tables as $table) {
2950
-            if ($table instanceof EE_Primary_Table) {
2951
-                return $table;
2952
-            }
2953
-        }
2954
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2955
-            'event_espresso'), get_class($this)));
2956
-    }
2957
-
2958
-
2959
-
2960
-    /**
2961
-     * table
2962
-     * returns EE_Primary_Table table name
2963
-     *
2964
-     * @return string
2965
-     * @throws \EE_Error
2966
-     */
2967
-    public function table()
2968
-    {
2969
-        return $this->_get_main_table()->get_table_name();
2970
-    }
2971
-
2972
-
2973
-
2974
-    /**
2975
-     * table
2976
-     * returns first EE_Secondary_Table table name
2977
-     *
2978
-     * @return string
2979
-     */
2980
-    public function second_table()
2981
-    {
2982
-        // grab second table from tables array
2983
-        $second_table = end($this->_tables);
2984
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2985
-    }
2986
-
2987
-
2988
-
2989
-    /**
2990
-     * get_table_obj_by_alias
2991
-     * returns table name given it's alias
2992
-     *
2993
-     * @param string $table_alias
2994
-     * @return EE_Primary_Table | EE_Secondary_Table
2995
-     */
2996
-    public function get_table_obj_by_alias($table_alias = '')
2997
-    {
2998
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
2999
-    }
3000
-
3001
-
3002
-
3003
-    /**
3004
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3005
-     *
3006
-     * @return EE_Secondary_Table[]
3007
-     */
3008
-    protected function _get_other_tables()
3009
-    {
3010
-        $other_tables = array();
3011
-        foreach ($this->_tables as $table_alias => $table) {
3012
-            if ($table instanceof EE_Secondary_Table) {
3013
-                $other_tables[$table_alias] = $table;
3014
-            }
3015
-        }
3016
-        return $other_tables;
3017
-    }
3018
-
3019
-
3020
-
3021
-    /**
3022
-     * Finds all the fields that correspond to the given table
3023
-     *
3024
-     * @param string $table_alias , array key in EEM_Base::_tables
3025
-     * @return EE_Model_Field_Base[]
3026
-     */
3027
-    public function _get_fields_for_table($table_alias)
3028
-    {
3029
-        return $this->_fields[$table_alias];
3030
-    }
3031
-
3032
-
3033
-
3034
-    /**
3035
-     * Recurses through all the where parameters, and finds all the related models we'll need
3036
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3037
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3038
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3039
-     * related Registration, Transaction, and Payment models.
3040
-     *
3041
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3042
-     * @return EE_Model_Query_Info_Carrier
3043
-     * @throws \EE_Error
3044
-     */
3045
-    public function _extract_related_models_from_query($query_params)
3046
-    {
3047
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3048
-        if (array_key_exists(0, $query_params)) {
3049
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3050
-        }
3051
-        if (array_key_exists('group_by', $query_params)) {
3052
-            if (is_array($query_params['group_by'])) {
3053
-                $this->_extract_related_models_from_sub_params_array_values(
3054
-                    $query_params['group_by'],
3055
-                    $query_info_carrier,
3056
-                    'group_by'
3057
-                );
3058
-            } elseif (! empty ($query_params['group_by'])) {
3059
-                $this->_extract_related_model_info_from_query_param(
3060
-                    $query_params['group_by'],
3061
-                    $query_info_carrier,
3062
-                    'group_by'
3063
-                );
3064
-            }
3065
-        }
3066
-        if (array_key_exists('having', $query_params)) {
3067
-            $this->_extract_related_models_from_sub_params_array_keys(
3068
-                $query_params[0],
3069
-                $query_info_carrier,
3070
-                'having'
3071
-            );
3072
-        }
3073
-        if (array_key_exists('order_by', $query_params)) {
3074
-            if (is_array($query_params['order_by'])) {
3075
-                $this->_extract_related_models_from_sub_params_array_keys(
3076
-                    $query_params['order_by'],
3077
-                    $query_info_carrier,
3078
-                    'order_by'
3079
-                );
3080
-            } elseif (! empty($query_params['order_by'])) {
3081
-                $this->_extract_related_model_info_from_query_param(
3082
-                    $query_params['order_by'],
3083
-                    $query_info_carrier,
3084
-                    'order_by'
3085
-                );
3086
-            }
3087
-        }
3088
-        if (array_key_exists('force_join', $query_params)) {
3089
-            $this->_extract_related_models_from_sub_params_array_values(
3090
-                $query_params['force_join'],
3091
-                $query_info_carrier,
3092
-                'force_join'
3093
-            );
3094
-        }
3095
-        return $query_info_carrier;
3096
-    }
3097
-
3098
-
3099
-
3100
-    /**
3101
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3102
-     *
3103
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3104
-     *                                                      $query_params['having']
3105
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3106
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3107
-     * @throws EE_Error
3108
-     * @return \EE_Model_Query_Info_Carrier
3109
-     */
3110
-    private function _extract_related_models_from_sub_params_array_keys(
3111
-        $sub_query_params,
3112
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3113
-        $query_param_type
3114
-    ) {
3115
-        if (! empty($sub_query_params)) {
3116
-            $sub_query_params = (array)$sub_query_params;
3117
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3118
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3119
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3120
-                    $query_param_type);
3121
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3122
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3123
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3124
-                //of array('Registration.TXN_ID'=>23)
3125
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3126
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3127
-                    if (! is_array($possibly_array_of_params)) {
3128
-                        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'))",
3129
-                            "event_espresso"),
3130
-                            $param, $possibly_array_of_params));
3131
-                    } else {
3132
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3133
-                            $model_query_info_carrier, $query_param_type);
3134
-                    }
3135
-                } elseif ($query_param_type === 0 //ie WHERE
3136
-                          && is_array($possibly_array_of_params)
3137
-                          && isset($possibly_array_of_params[2])
3138
-                          && $possibly_array_of_params[2] == true
3139
-                ) {
3140
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3141
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3142
-                    //from which we should extract query parameters!
3143
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3144
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3145
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3146
-                    }
3147
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3148
-                        $model_query_info_carrier, $query_param_type);
3149
-                }
3150
-            }
3151
-        }
3152
-        return $model_query_info_carrier;
3153
-    }
3154
-
3155
-
3156
-
3157
-    /**
3158
-     * For extracting related models from forced_joins, where the array values contain the info about what
3159
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3160
-     *
3161
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3162
-     *                                                      $query_params['having']
3163
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3164
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3165
-     * @throws EE_Error
3166
-     * @return \EE_Model_Query_Info_Carrier
3167
-     */
3168
-    private function _extract_related_models_from_sub_params_array_values(
3169
-        $sub_query_params,
3170
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3171
-        $query_param_type
3172
-    ) {
3173
-        if (! empty($sub_query_params)) {
3174
-            if (! is_array($sub_query_params)) {
3175
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3176
-                    $sub_query_params));
3177
-            }
3178
-            foreach ($sub_query_params as $param) {
3179
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3180
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3181
-                    $query_param_type);
3182
-            }
3183
-        }
3184
-        return $model_query_info_carrier;
3185
-    }
3186
-
3187
-
3188
-
3189
-    /**
3190
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3191
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3192
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3193
-     * but use them in a different order. Eg, we need to know what models we are querying
3194
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3195
-     * other models before we can finalize the where clause SQL.
3196
-     *
3197
-     * @param array $query_params
3198
-     * @throws EE_Error
3199
-     * @return EE_Model_Query_Info_Carrier
3200
-     */
3201
-    public function _create_model_query_info_carrier($query_params)
3202
-    {
3203
-        if (! is_array($query_params)) {
3204
-            EE_Error::doing_it_wrong(
3205
-                'EEM_Base::_create_model_query_info_carrier',
3206
-                sprintf(
3207
-                    __(
3208
-                        '$query_params should be an array, you passed a variable of type %s',
3209
-                        'event_espresso'
3210
-                    ),
3211
-                    gettype($query_params)
3212
-                ),
3213
-                '4.6.0'
3214
-            );
3215
-            $query_params = array();
3216
-        }
3217
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3218
-        //first check if we should alter the query to account for caps or not
3219
-        //because the caps might require us to do extra joins
3220
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3221
-            $query_params[0] = $where_query_params = array_replace_recursive(
3222
-                $where_query_params,
3223
-                $this->caps_where_conditions(
3224
-                    $query_params['caps']
3225
-                )
3226
-            );
3227
-        }
3228
-        $query_object = $this->_extract_related_models_from_query($query_params);
3229
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3230
-        foreach ($where_query_params as $key => $value) {
3231
-            if (is_int($key)) {
3232
-                throw new EE_Error(
3233
-                    sprintf(
3234
-                        __(
3235
-                            "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.",
3236
-                            "event_espresso"
3237
-                        ),
3238
-                        $key,
3239
-                        var_export($value, true),
3240
-                        var_export($query_params, true),
3241
-                        get_class($this)
3242
-                    )
3243
-                );
3244
-            }
3245
-        }
3246
-        if (
3247
-            array_key_exists('default_where_conditions', $query_params)
3248
-            && ! empty($query_params['default_where_conditions'])
3249
-        ) {
3250
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3251
-        } else {
3252
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3253
-        }
3254
-        $where_query_params = array_merge(
3255
-            $this->_get_default_where_conditions_for_models_in_query(
3256
-                $query_object,
3257
-                $use_default_where_conditions,
3258
-                $where_query_params
3259
-            ),
3260
-            $where_query_params
3261
-        );
3262
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3263
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3264
-        // So we need to setup a subquery and use that for the main join.
3265
-        // Note for now this only works on the primary table for the model.
3266
-        // So for instance, you could set the limit array like this:
3267
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3268
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3269
-            $query_object->set_main_model_join_sql(
3270
-                $this->_construct_limit_join_select(
3271
-                    $query_params['on_join_limit'][0],
3272
-                    $query_params['on_join_limit'][1]
3273
-                )
3274
-            );
3275
-        }
3276
-        //set limit
3277
-        if (array_key_exists('limit', $query_params)) {
3278
-            if (is_array($query_params['limit'])) {
3279
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3280
-                    $e = sprintf(
3281
-                        __(
3282
-                            "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)",
3283
-                            "event_espresso"
3284
-                        ),
3285
-                        http_build_query($query_params['limit'])
3286
-                    );
3287
-                    throw new EE_Error($e . "|" . $e);
3288
-                }
3289
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3290
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3291
-            } elseif (! empty ($query_params['limit'])) {
3292
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3293
-            }
3294
-        }
3295
-        //set order by
3296
-        if (array_key_exists('order_by', $query_params)) {
3297
-            if (is_array($query_params['order_by'])) {
3298
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3299
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3300
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3301
-                if (array_key_exists('order', $query_params)) {
3302
-                    throw new EE_Error(
3303
-                        sprintf(
3304
-                            __(
3305
-                                "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 ",
3306
-                                "event_espresso"
3307
-                            ),
3308
-                            get_class($this),
3309
-                            implode(", ", array_keys($query_params['order_by'])),
3310
-                            implode(", ", $query_params['order_by']),
3311
-                            $query_params['order']
3312
-                        )
3313
-                    );
3314
-                }
3315
-                $this->_extract_related_models_from_sub_params_array_keys(
3316
-                    $query_params['order_by'],
3317
-                    $query_object,
3318
-                    'order_by'
3319
-                );
3320
-                //assume it's an array of fields to order by
3321
-                $order_array = array();
3322
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3323
-                    $order = $this->_extract_order($order);
3324
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3325
-                }
3326
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3327
-            } elseif (! empty ($query_params['order_by'])) {
3328
-                $this->_extract_related_model_info_from_query_param(
3329
-                    $query_params['order_by'],
3330
-                    $query_object,
3331
-                    'order',
3332
-                    $query_params['order_by']
3333
-                );
3334
-                $order = isset($query_params['order'])
3335
-                    ? $this->_extract_order($query_params['order'])
3336
-                    : 'DESC';
3337
-                $query_object->set_order_by_sql(
3338
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3339
-                );
3340
-            }
3341
-        }
3342
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3343
-        if (! array_key_exists('order_by', $query_params)
3344
-            && array_key_exists('order', $query_params)
3345
-            && ! empty($query_params['order'])
3346
-        ) {
3347
-            $pk_field = $this->get_primary_key_field();
3348
-            $order = $this->_extract_order($query_params['order']);
3349
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3350
-        }
3351
-        //set group by
3352
-        if (array_key_exists('group_by', $query_params)) {
3353
-            if (is_array($query_params['group_by'])) {
3354
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3355
-                $group_by_array = array();
3356
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3357
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3358
-                }
3359
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3360
-            } elseif (! empty ($query_params['group_by'])) {
3361
-                $query_object->set_group_by_sql(
3362
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3363
-                );
3364
-            }
3365
-        }
3366
-        //set having
3367
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3368
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3369
-        }
3370
-        //now, just verify they didn't pass anything wack
3371
-        foreach ($query_params as $query_key => $query_value) {
3372
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3373
-                throw new EE_Error(
3374
-                    sprintf(
3375
-                        __(
3376
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3377
-                            'event_espresso'
3378
-                        ),
3379
-                        $query_key,
3380
-                        get_class($this),
3381
-                        //						print_r( $this->_allowed_query_params, TRUE )
3382
-                        implode(',', $this->_allowed_query_params)
3383
-                    )
3384
-                );
3385
-            }
3386
-        }
3387
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3388
-        if (empty($main_model_join_sql)) {
3389
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3390
-        }
3391
-        return $query_object;
3392
-    }
3393
-
3394
-
3395
-
3396
-    /**
3397
-     * Gets the where conditions that should be imposed on the query based on the
3398
-     * context (eg reading frontend, backend, edit or delete).
3399
-     *
3400
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3401
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3402
-     * @throws \EE_Error
3403
-     */
3404
-    public function caps_where_conditions($context = self::caps_read)
3405
-    {
3406
-        EEM_Base::verify_is_valid_cap_context($context);
3407
-        $cap_where_conditions = array();
3408
-        $cap_restrictions = $this->caps_missing($context);
3409
-        /**
3410
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3411
-         */
3412
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3413
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3414
-                $restriction_if_no_cap->get_default_where_conditions());
3415
-        }
3416
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3417
-            $cap_restrictions);
3418
-    }
3419
-
3420
-
3421
-
3422
-    /**
3423
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3424
-     * otherwise throws an exception
3425
-     *
3426
-     * @param string $should_be_order_string
3427
-     * @return string either ASC, asc, DESC or desc
3428
-     * @throws EE_Error
3429
-     */
3430
-    private function _extract_order($should_be_order_string)
3431
-    {
3432
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3433
-            return $should_be_order_string;
3434
-        } else {
3435
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3436
-                "event_espresso"), get_class($this), $should_be_order_string));
3437
-        }
3438
-    }
3439
-
3440
-
3441
-
3442
-    /**
3443
-     * Looks at all the models which are included in this query, and asks each
3444
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3445
-     * so they can be merged
3446
-     *
3447
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3448
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3449
-     *                                                                  'none' means NO default where conditions will
3450
-     *                                                                  be used AT ALL during this query.
3451
-     *                                                                  'other_models_only' means default where
3452
-     *                                                                  conditions from other models will be used, but
3453
-     *                                                                  not for this primary model. 'all', the default,
3454
-     *                                                                  means default where conditions will apply as
3455
-     *                                                                  normal
3456
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3457
-     * @throws EE_Error
3458
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3459
-     */
3460
-    private function _get_default_where_conditions_for_models_in_query(
3461
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3462
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3463
-        $where_query_params = array()
3464
-    ) {
3465
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3466
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3467
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3468
-                "event_espresso"), $use_default_where_conditions,
3469
-                implode(", ", $allowed_used_default_where_conditions_values)));
3470
-        }
3471
-        $universal_query_params = array();
3472
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3473
-            $universal_query_params = $this->_get_default_where_conditions();
3474
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3475
-            $universal_query_params = $this->_get_minimum_where_conditions();
3476
-        }
3477
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3478
-            $related_model = $this->get_related_model_obj($model_name);
3479
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3480
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3481
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3482
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3483
-            } else {
3484
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3485
-                continue;
3486
-            }
3487
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3488
-                $related_model_universal_where_params,
3489
-                $where_query_params,
3490
-                $related_model,
3491
-                $model_relation_path
3492
-            );
3493
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3494
-                $universal_query_params,
3495
-                $overrides
3496
-            );
3497
-        }
3498
-        return $universal_query_params;
3499
-    }
3500
-
3501
-
3502
-
3503
-    /**
3504
-     * Determines whether or not we should use default where conditions for the model in question
3505
-     * (this model, or other related models).
3506
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3507
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3508
-     * We should use default where conditions on related models when they requested to use default where conditions
3509
-     * on all models, or specifically just on other related models
3510
-     * @param      $default_where_conditions_value
3511
-     * @param bool $for_this_model false means this is for OTHER related models
3512
-     * @return bool
3513
-     */
3514
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3515
-    {
3516
-        return (
3517
-                   $for_this_model
3518
-                   && in_array(
3519
-                       $default_where_conditions_value,
3520
-                       array(
3521
-                           EEM_Base::default_where_conditions_all,
3522
-                           EEM_Base::default_where_conditions_this_only,
3523
-                           EEM_Base::default_where_conditions_minimum_others,
3524
-                       ),
3525
-                       true
3526
-                   )
3527
-               )
3528
-               || (
3529
-                   ! $for_this_model
3530
-                   && in_array(
3531
-                       $default_where_conditions_value,
3532
-                       array(
3533
-                           EEM_Base::default_where_conditions_all,
3534
-                           EEM_Base::default_where_conditions_others_only,
3535
-                       ),
3536
-                       true
3537
-                   )
3538
-               );
3539
-    }
3540
-
3541
-    /**
3542
-     * Determines whether or not we should use default minimum conditions for the model in question
3543
-     * (this model, or other related models).
3544
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3545
-     * where conditions.
3546
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3547
-     * on this model or others
3548
-     * @param      $default_where_conditions_value
3549
-     * @param bool $for_this_model false means this is for OTHER related models
3550
-     * @return bool
3551
-     */
3552
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3553
-    {
3554
-        return (
3555
-                   $for_this_model
3556
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3557
-               )
3558
-               || (
3559
-                   ! $for_this_model
3560
-                   && in_array(
3561
-                       $default_where_conditions_value,
3562
-                       array(
3563
-                           EEM_Base::default_where_conditions_minimum_others,
3564
-                           EEM_Base::default_where_conditions_minimum_all,
3565
-                       ),
3566
-                       true
3567
-                   )
3568
-               );
3569
-    }
3570
-
3571
-
3572
-    /**
3573
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3574
-     * then we also add a special where condition which allows for that model's primary key
3575
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3576
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3577
-     *
3578
-     * @param array    $default_where_conditions
3579
-     * @param array    $provided_where_conditions
3580
-     * @param EEM_Base $model
3581
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3582
-     * @return array like EEM_Base::get_all's $query_params[0]
3583
-     * @throws \EE_Error
3584
-     */
3585
-    private function _override_defaults_or_make_null_friendly(
3586
-        $default_where_conditions,
3587
-        $provided_where_conditions,
3588
-        $model,
3589
-        $model_relation_path
3590
-    ) {
3591
-        $null_friendly_where_conditions = array();
3592
-        $none_overridden = true;
3593
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3594
-        foreach ($default_where_conditions as $key => $val) {
3595
-            if (isset($provided_where_conditions[$key])) {
3596
-                $none_overridden = false;
3597
-            } else {
3598
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3599
-            }
3600
-        }
3601
-        if ($none_overridden && $default_where_conditions) {
3602
-            if ($model->has_primary_key_field()) {
3603
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3604
-                                                                                . "."
3605
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3606
-            }/*else{
31
+	//admin posty
32
+	//basic -> grants access to mine -> if they don't have it, select none
33
+	//*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
34
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
35
+	//*_published -> grants access to published -> if they dont have it, select non-published
36
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
37
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
38
+	//frontend posty
39
+	//by default has access to published
40
+	//basic -> grants access to mine that aren't published, and all published
41
+	//*_others ->grants access to others that aren't private, all mine
42
+	//*_private -> grants full access
43
+	//frontend non-posty
44
+	//like admin posty
45
+	//category-y
46
+	//assign -> grants access to join-table
47
+	//(delete, edit)
48
+	//payment-method-y
49
+	//for each registered payment method,
50
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
51
+	/**
52
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
53
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
54
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
55
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
56
+	 *
57
+	 * @var boolean
58
+	 */
59
+	private $_values_already_prepared_by_model_object = 0;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the data is just like form input that needs to have the model fields'
64
+	 * prepare_for_set and prepare_for_use_in_db called on it
65
+	 */
66
+	const not_prepared_by_model_object = 0;
67
+
68
+	/**
69
+	 * when $_values_already_prepared_by_model_object equals this, we
70
+	 * assume this value is coming from a model object and doesn't need to have
71
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
72
+	 */
73
+	const prepared_by_model_object = 1;
74
+
75
+	/**
76
+	 * when $_values_already_prepared_by_model_object equals this, we assume
77
+	 * the values are already to be used in the database (ie no processing is done
78
+	 * on them by the model's fields)
79
+	 */
80
+	const prepared_for_use_in_db = 2;
81
+
82
+
83
+	protected $singular_item = 'Item';
84
+
85
+	protected $plural_item   = 'Items';
86
+
87
+	/**
88
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
89
+	 */
90
+	protected $_tables;
91
+
92
+	/**
93
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
94
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
95
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
96
+	 *
97
+	 * @var \EE_Model_Field_Base[] $_fields
98
+	 */
99
+	protected $_fields;
100
+
101
+	/**
102
+	 * array of different kinds of relations
103
+	 *
104
+	 * @var \EE_Model_Relation_Base[] $_model_relations
105
+	 */
106
+	protected $_model_relations;
107
+
108
+	/**
109
+	 * @var \EE_Index[] $_indexes
110
+	 */
111
+	protected $_indexes = array();
112
+
113
+	/**
114
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
115
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
+	 * by setting the same columns as used in these queries in the query yourself.
117
+	 *
118
+	 * @var EE_Default_Where_Conditions
119
+	 */
120
+	protected $_default_where_conditions_strategy;
121
+
122
+	/**
123
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
+	 * This is particularly useful when you want something between 'none' and 'default'
125
+	 *
126
+	 * @var EE_Default_Where_Conditions
127
+	 */
128
+	protected $_minimum_where_conditions_strategy;
129
+
130
+	/**
131
+	 * String describing how to find the "owner" of this model's objects.
132
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
133
+	 * But when there isn't, this indicates which related model, or transiently-related model,
134
+	 * has the foreign key to the wp_users table.
135
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
136
+	 * related to events, and events have a foreign key to wp_users.
137
+	 * On EEM_Transaction, this would be 'Transaction.Event'
138
+	 *
139
+	 * @var string
140
+	 */
141
+	protected $_model_chain_to_wp_user = '';
142
+
143
+	/**
144
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
145
+	 * don't need it (particularly CPT models)
146
+	 *
147
+	 * @var bool
148
+	 */
149
+	protected $_ignore_where_strategy = false;
150
+
151
+	/**
152
+	 * String used in caps relating to this model. Eg, if the caps relating to this
153
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
154
+	 *
155
+	 * @var string. If null it hasn't been initialized yet. If false then we
156
+	 * have indicated capabilities don't apply to this
157
+	 */
158
+	protected $_caps_slug = null;
159
+
160
+	/**
161
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
162
+	 * and next-level keys are capability names, and each's value is a
163
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
164
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
165
+	 * and then each capability in the corresponding sub-array that they're missing
166
+	 * adds the where conditions onto the query.
167
+	 *
168
+	 * @var array
169
+	 */
170
+	protected $_cap_restrictions = array(
171
+		self::caps_read       => array(),
172
+		self::caps_read_admin => array(),
173
+		self::caps_edit       => array(),
174
+		self::caps_delete     => array(),
175
+	);
176
+
177
+	/**
178
+	 * Array defining which cap restriction generators to use to create default
179
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
180
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
181
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
182
+	 * automatically set this to false (not just null).
183
+	 *
184
+	 * @var EE_Restriction_Generator_Base[]
185
+	 */
186
+	protected $_cap_restriction_generators = array();
187
+
188
+	/**
189
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
190
+	 */
191
+	const caps_read       = 'read';
192
+
193
+	const caps_read_admin = 'read_admin';
194
+
195
+	const caps_edit       = 'edit';
196
+
197
+	const caps_delete     = 'delete';
198
+
199
+	/**
200
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
201
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
202
+	 * maps to 'read' because when looking for relevant permissions we're going to use
203
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
204
+	 *
205
+	 * @var array
206
+	 */
207
+	protected $_cap_contexts_to_cap_action_map = array(
208
+		self::caps_read       => 'read',
209
+		self::caps_read_admin => 'read',
210
+		self::caps_edit       => 'edit',
211
+		self::caps_delete     => 'delete',
212
+	);
213
+
214
+	/**
215
+	 * Timezone
216
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
217
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
218
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
219
+	 * EE_Datetime_Field data type will have access to it.
220
+	 *
221
+	 * @var string
222
+	 */
223
+	protected $_timezone;
224
+
225
+
226
+	/**
227
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
228
+	 * multisite.
229
+	 *
230
+	 * @var int
231
+	 */
232
+	protected static $_model_query_blog_id;
233
+
234
+	/**
235
+	 * A copy of _fields, except the array keys are the model names pointed to by
236
+	 * the field
237
+	 *
238
+	 * @var EE_Model_Field_Base[]
239
+	 */
240
+	private $_cache_foreign_key_to_fields = array();
241
+
242
+	/**
243
+	 * Cached list of all the fields on the model, indexed by their name
244
+	 *
245
+	 * @var EE_Model_Field_Base[]
246
+	 */
247
+	private $_cached_fields = null;
248
+
249
+	/**
250
+	 * Cached list of all the fields on the model, except those that are
251
+	 * marked as only pertinent to the database
252
+	 *
253
+	 * @var EE_Model_Field_Base[]
254
+	 */
255
+	private $_cached_fields_non_db_only = null;
256
+
257
+	/**
258
+	 * A cached reference to the primary key for quick lookup
259
+	 *
260
+	 * @var EE_Model_Field_Base
261
+	 */
262
+	private $_primary_key_field = null;
263
+
264
+	/**
265
+	 * Flag indicating whether this model has a primary key or not
266
+	 *
267
+	 * @var boolean
268
+	 */
269
+	protected $_has_primary_key_field = null;
270
+
271
+	/**
272
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
273
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
274
+	 *
275
+	 * @var boolean
276
+	 */
277
+	protected $_wp_core_model = false;
278
+
279
+	/**
280
+	 *    List of valid operators that can be used for querying.
281
+	 * The keys are all operators we'll accept, the values are the real SQL
282
+	 * operators used
283
+	 *
284
+	 * @var array
285
+	 */
286
+	protected $_valid_operators = array(
287
+		'='           => '=',
288
+		'<='          => '<=',
289
+		'<'           => '<',
290
+		'>='          => '>=',
291
+		'>'           => '>',
292
+		'!='          => '!=',
293
+		'LIKE'        => 'LIKE',
294
+		'like'        => 'LIKE',
295
+		'NOT_LIKE'    => 'NOT LIKE',
296
+		'not_like'    => 'NOT LIKE',
297
+		'NOT LIKE'    => 'NOT LIKE',
298
+		'not like'    => 'NOT LIKE',
299
+		'IN'          => 'IN',
300
+		'in'          => 'IN',
301
+		'NOT_IN'      => 'NOT IN',
302
+		'not_in'      => 'NOT IN',
303
+		'NOT IN'      => 'NOT IN',
304
+		'not in'      => 'NOT IN',
305
+		'between'     => 'BETWEEN',
306
+		'BETWEEN'     => 'BETWEEN',
307
+		'IS_NOT_NULL' => 'IS NOT NULL',
308
+		'is_not_null' => 'IS NOT NULL',
309
+		'IS NOT NULL' => 'IS NOT NULL',
310
+		'is not null' => 'IS NOT NULL',
311
+		'IS_NULL'     => 'IS NULL',
312
+		'is_null'     => 'IS NULL',
313
+		'IS NULL'     => 'IS NULL',
314
+		'is null'     => 'IS NULL',
315
+		'REGEXP'      => 'REGEXP',
316
+		'regexp'      => 'REGEXP',
317
+		'NOT_REGEXP'  => 'NOT REGEXP',
318
+		'not_regexp'  => 'NOT REGEXP',
319
+		'NOT REGEXP'  => 'NOT REGEXP',
320
+		'not regexp'  => 'NOT REGEXP',
321
+	);
322
+
323
+	/**
324
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
325
+	 *
326
+	 * @var array
327
+	 */
328
+	protected $_in_style_operators = array('IN', 'NOT IN');
329
+
330
+	/**
331
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
332
+	 * '12-31-2012'"
333
+	 *
334
+	 * @var array
335
+	 */
336
+	protected $_between_style_operators = array('BETWEEN');
337
+
338
+	/**
339
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
340
+	 * on a join table.
341
+	 *
342
+	 * @var array
343
+	 */
344
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
345
+
346
+	/**
347
+	 * Allowed values for $query_params['order'] for ordering in queries
348
+	 *
349
+	 * @var array
350
+	 */
351
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
352
+
353
+	/**
354
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
355
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
356
+	 *
357
+	 * @var array
358
+	 */
359
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
360
+
361
+	/**
362
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
363
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
364
+	 *
365
+	 * @var array
366
+	 */
367
+	private $_allowed_query_params = array(
368
+		0,
369
+		'limit',
370
+		'order_by',
371
+		'group_by',
372
+		'having',
373
+		'force_join',
374
+		'order',
375
+		'on_join_limit',
376
+		'default_where_conditions',
377
+		'caps',
378
+	);
379
+
380
+	/**
381
+	 * All the data types that can be used in $wpdb->prepare statements.
382
+	 *
383
+	 * @var array
384
+	 */
385
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
386
+
387
+	/**
388
+	 *    EE_Registry Object
389
+	 *
390
+	 * @var    object
391
+	 * @access    protected
392
+	 */
393
+	protected $EE = null;
394
+
395
+
396
+	/**
397
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
398
+	 *
399
+	 * @var int
400
+	 */
401
+	protected $_show_next_x_db_queries = 0;
402
+
403
+	/**
404
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
405
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
406
+	 *
407
+	 * @var array
408
+	 */
409
+	protected $_custom_selections = array();
410
+
411
+	/**
412
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
413
+	 * caches every model object we've fetched from the DB on this request
414
+	 *
415
+	 * @var array
416
+	 */
417
+	protected $_entity_map;
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has not yet verified the db on this http request
421
+	 */
422
+	const db_verified_none = 0;
423
+
424
+	/**
425
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
426
+	 * but not the addons' dbs
427
+	 */
428
+	const db_verified_core = 1;
429
+
430
+	/**
431
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
+	 * the EE core db too)
433
+	 */
434
+	const db_verified_addons = 2;
435
+
436
+	/**
437
+	 * indicates whether an EEM_Base child has already re-verified the DB
438
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
439
+	 * looking like EEM_Base::db_verified_*
440
+	 *
441
+	 * @var int - 0 = none, 1 = core, 2 = addons
442
+	 */
443
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
444
+
445
+	/**
446
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
449
+	 */
450
+	const default_where_conditions_all = 'all';
451
+
452
+	/**
453
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
+	 *        models which share tables with other models, this can return data for the wrong model.
458
+	 */
459
+	const default_where_conditions_this_only = 'this_model_only';
460
+
461
+	/**
462
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
+	 */
466
+	const default_where_conditions_others_only = 'other_models_only';
467
+
468
+	/**
469
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
472
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
+	 *        (regardless of whether those events and venues are trashed)
474
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
+	 *        events.
476
+	 */
477
+	const default_where_conditions_minimum_all = 'minimum';
478
+
479
+	/**
480
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
+	 *        not)
484
+	 */
485
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
+
487
+	/**
488
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
+	 *        it's possible it will return table entries for other models. You should use
491
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
492
+	 */
493
+	const default_where_conditions_none = 'none';
494
+
495
+
496
+
497
+	/**
498
+	 * About all child constructors:
499
+	 * they should define the _tables, _fields and _model_relations arrays.
500
+	 * Should ALWAYS be called after child constructor.
501
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
502
+	 * finalizes constructing all the object's attributes.
503
+	 * Generally, rather than requiring a child to code
504
+	 * $this->_tables = array(
505
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
+	 *        ...);
507
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
+	 * each EE_Table has a function to set the table's alias after the constructor, using
509
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
+	 * do something similar.
511
+	 *
512
+	 * @param null $timezone
513
+	 * @throws \EE_Error
514
+	 */
515
+	protected function __construct($timezone = null)
516
+	{
517
+		// check that the model has not been loaded too soon
518
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+			throw new EE_Error (
520
+				sprintf(
521
+					__('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.',
522
+						'event_espresso'),
523
+					get_class($this)
524
+				)
525
+			);
526
+		}
527
+		/**
528
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
+		 */
530
+		if (empty(EEM_Base::$_model_query_blog_id)) {
531
+			EEM_Base::set_model_query_blog_id();
532
+		}
533
+		/**
534
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
+		 * just use EE_Register_Model_Extension
536
+		 *
537
+		 * @var EE_Table_Base[] $_tables
538
+		 */
539
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
+		foreach ($this->_tables as $table_alias => $table_obj) {
541
+			/** @var $table_obj EE_Table_Base */
542
+			$table_obj->_construct_finalize_with_alias($table_alias);
543
+			if ($table_obj instanceof EE_Secondary_Table) {
544
+				/** @var $table_obj EE_Secondary_Table */
545
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
+			}
547
+		}
548
+		/**
549
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
+		 * EE_Register_Model_Extension
551
+		 *
552
+		 * @param EE_Model_Field_Base[] $_fields
553
+		 */
554
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
+		$this->_invalidate_field_caches();
556
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
557
+			if (! array_key_exists($table_alias, $this->_tables)) {
558
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
+			}
561
+			foreach ($fields_for_table as $field_name => $field_obj) {
562
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
+				//primary key field base has a slightly different _construct_finalize
564
+				/** @var $field_obj EE_Model_Field_Base */
565
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
+			}
567
+		}
568
+		// everything is related to Extra_Meta
569
+		if (get_class($this) !== 'EEM_Extra_Meta') {
570
+			//make extra meta related to everything, but don't block deleting things just
571
+			//because they have related extra meta info. For now just orphan those extra meta
572
+			//in the future we should automatically delete them
573
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
+		}
575
+		//and change logs
576
+		if (get_class($this) !== 'EEM_Change_Log') {
577
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		/**
580
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
+		 * EE_Register_Model_Extension
582
+		 *
583
+		 * @param EE_Model_Relation_Base[] $_model_relations
584
+		 */
585
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
+			$this->_model_relations);
587
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
588
+			/** @var $relation_obj EE_Model_Relation_Base */
589
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
+		}
591
+		foreach ($this->_indexes as $index_name => $index_obj) {
592
+			/** @var $index_obj EE_Index */
593
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
+		}
595
+		$this->set_timezone($timezone);
596
+		//finalize default where condition strategy, or set default
597
+		if (! $this->_default_where_conditions_strategy) {
598
+			//nothing was set during child constructor, so set default
599
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
+		}
601
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
602
+		if (! $this->_minimum_where_conditions_strategy) {
603
+			//nothing was set during child constructor, so set default
604
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
+		}
606
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
608
+		//to indicate to NOT set it, set it to the logical default
609
+		if ($this->_caps_slug === null) {
610
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
+		}
612
+		//initialize the standard cap restriction generators if none were specified by the child constructor
613
+		if ($this->_cap_restriction_generators !== false) {
614
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
617
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
+						new EE_Restriction_Generator_Protected(),
619
+						$cap_context,
620
+						$this
621
+					);
622
+				}
623
+			}
624
+		}
625
+		//if there are cap restriction generators, use them to make the default cap restrictions
626
+		if ($this->_cap_restriction_generators !== false) {
627
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
+				if (! $generator_object) {
629
+					continue;
630
+				}
631
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
+					throw new EE_Error(
633
+						sprintf(
634
+							__('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
+								'event_espresso'),
636
+							$context,
637
+							$this->get_this_model_name()
638
+						)
639
+					);
640
+				}
641
+				$action = $this->cap_action_for_context($context);
642
+				if (! $generator_object->construction_finalized()) {
643
+					$generator_object->_construct_finalize($this, $action);
644
+				}
645
+			}
646
+		}
647
+		do_action('AHEE__' . get_class($this) . '__construct__end');
648
+	}
649
+
650
+
651
+
652
+	/**
653
+	 * Generates the cap restrictions for the given context, or if they were
654
+	 * already generated just gets what's cached
655
+	 *
656
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
657
+	 * @return EE_Default_Where_Conditions[]
658
+	 */
659
+	protected function _generate_cap_restrictions($context)
660
+	{
661
+		if (isset($this->_cap_restriction_generators[$context])
662
+			&& $this->_cap_restriction_generators[$context]
663
+			   instanceof
664
+			   EE_Restriction_Generator_Base
665
+		) {
666
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
667
+		} else {
668
+			return array();
669
+		}
670
+	}
671
+
672
+
673
+
674
+	/**
675
+	 * Used to set the $_model_query_blog_id static property.
676
+	 *
677
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
678
+	 *                      value for get_current_blog_id() will be used.
679
+	 */
680
+	public static function set_model_query_blog_id($blog_id = 0)
681
+	{
682
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
+	}
684
+
685
+
686
+
687
+	/**
688
+	 * Returns whatever is set as the internal $model_query_blog_id.
689
+	 *
690
+	 * @return int
691
+	 */
692
+	public static function get_model_query_blog_id()
693
+	{
694
+		return EEM_Base::$_model_query_blog_id;
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 *        This function is a singleton method used to instantiate the Espresso_model object
701
+	 *
702
+	 * @access public
703
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
704
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
705
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
706
+	 *                         timezone in the 'timezone_string' wp option)
707
+	 * @return static (as in the concrete child class)
708
+	 */
709
+	public static function instance($timezone = null)
710
+	{
711
+		// check if instance of Espresso_model already exists
712
+		if (! static::$_instance instanceof static) {
713
+			// instantiate Espresso_model
714
+			static::$_instance = new static($timezone);
715
+		}
716
+		//we might have a timezone set, let set_timezone decide what to do with it
717
+		static::$_instance->set_timezone($timezone);
718
+		// Espresso_model object
719
+		return static::$_instance;
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * resets the model and returns it
726
+	 *
727
+	 * @param null | string $timezone
728
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
729
+	 * all its properties reset; if it wasn't instantiated, returns null)
730
+	 */
731
+	public static function reset($timezone = null)
732
+	{
733
+		if (static::$_instance instanceof EEM_Base) {
734
+			//let's try to NOT swap out the current instance for a new one
735
+			//because if someone has a reference to it, we can't remove their reference
736
+			//so it's best to keep using the same reference, but change the original object
737
+			//reset all its properties to their original values as defined in the class
738
+			$r = new ReflectionClass(get_class(static::$_instance));
739
+			$static_properties = $r->getStaticProperties();
740
+			foreach ($r->getDefaultProperties() as $property => $value) {
741
+				//don't set instance to null like it was originally,
742
+				//but it's static anyways, and we're ignoring static properties (for now at least)
743
+				if (! isset($static_properties[$property])) {
744
+					static::$_instance->{$property} = $value;
745
+				}
746
+			}
747
+			//and then directly call its constructor again, like we would if we
748
+			//were creating a new one
749
+			static::$_instance->__construct($timezone);
750
+			return self::instance();
751
+		}
752
+		return null;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
759
+	 *
760
+	 * @param  boolean $translated return localized strings or JUST the array.
761
+	 * @return array
762
+	 * @throws \EE_Error
763
+	 */
764
+	public function status_array($translated = false)
765
+	{
766
+		if (! array_key_exists('Status', $this->_model_relations)) {
767
+			return array();
768
+		}
769
+		$model_name = $this->get_this_model_name();
770
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
771
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
772
+		$status_array = array();
773
+		foreach ($stati as $status) {
774
+			$status_array[$status->ID()] = $status->get('STS_code');
775
+		}
776
+		return $translated
777
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
778
+			: $status_array;
779
+	}
780
+
781
+
782
+
783
+	/**
784
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
785
+	 *
786
+	 * @param array $query_params             {
787
+	 * @var array $0 (where) array {
788
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
789
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
790
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
791
+	 *                                        conditions based on related models (and even
792
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
793
+	 *                                        name. Eg,
794
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
795
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
796
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
797
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
798
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
799
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
800
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
801
+	 *                                        to Venues (even when each of those models actually consisted of two
802
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
803
+	 *                                        just having
804
+	 *                                        "Venue.VNU_ID", you could have
805
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
806
+	 *                                        events are related to Registrations, which are related to Attendees). You
807
+	 *                                        can take it even further with
808
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
809
+	 *                                        (from the default of '='), change the value to an numerically-indexed
810
+	 *                                        array, where the first item in the list is the operator. eg: array(
811
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
812
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
813
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
814
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
815
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
816
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
817
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
818
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
819
+	 *                                        the value is a field, simply provide a third array item (true) to the
820
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
821
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
822
+	 *                                        Note: you can also use related model field names like you would any other
823
+	 *                                        field name. eg:
824
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
825
+	 *                                        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__>' =>
826
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
827
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
828
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
829
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
830
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
831
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
832
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
833
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
834
+	 *                                        "stick" until you specify an AND. eg
835
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
836
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
837
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
838
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
839
+	 *                                        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 >>
840
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
841
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
842
+	 *                                        too, eg:
843
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
844
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
845
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
846
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
847
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
848
+	 *                                        the OFFSET, the 2nd is the LIMIT
849
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
850
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
851
+	 *                                        following format array('on_join_limit'
852
+	 *                                        => array( 'table_alias', array(1,2) ) ).
853
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
854
+	 *                                        values are either 'ASC' or 'DESC'.
855
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
856
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
857
+	 *                                        DESC..." respectively. Like the
858
+	 *                                        'where' conditions, these fields can be on related models. Eg
859
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
860
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
861
+	 *                                        Attendee, Price, Datetime, etc.)
862
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
863
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
864
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
865
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
866
+	 *                                        order by the primary key. Eg,
867
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
868
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
869
+	 *                                        DTT_EVT_start) or
870
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
871
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
872
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
873
+	 *                                        'group_by'=>'VNU_ID', or
874
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
875
+	 *                                        if no
876
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
877
+	 *                                        model's primary key (or combined primary keys). This avoids some
878
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
879
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
880
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
881
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
882
+	 *                                        results)
883
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
884
+	 *                                        array where values are models to be joined in the query.Eg
885
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
886
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
887
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
888
+	 *                                        related models which belongs to the current model
889
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
890
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
891
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
892
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
893
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
894
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
895
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
896
+	 *                                        this model's default where conditions added to the query, use
897
+	 *                                        'this_model_only'. If you want to use all default where conditions
898
+	 *                                        (default), set to 'all'.
899
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
900
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
901
+	 *                                        everything? Or should we only show the current user items they should be
902
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
903
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
904
+	 *                                        }
905
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
906
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
907
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
908
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
909
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
910
+	 *                                        array( array(
911
+	 *                                        'OR'=>array(
912
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
913
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
914
+	 *                                        )
915
+	 *                                        ),
916
+	 *                                        'limit'=>10,
917
+	 *                                        'group_by'=>'TXN_ID'
918
+	 *                                        ));
919
+	 *                                        get all the answers to the question titled "shirt size" for event with id
920
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
921
+	 *                                        'Question.QST_display_text'=>'shirt size',
922
+	 *                                        'Registration.Event.EVT_ID'=>12
923
+	 *                                        ),
924
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
925
+	 *                                        ));
926
+	 * @throws \EE_Error
927
+	 */
928
+	public function get_all($query_params = array())
929
+	{
930
+		if (isset($query_params['limit'])
931
+			&& ! isset($query_params['group_by'])
932
+		) {
933
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
+		}
935
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
936
+	}
937
+
938
+
939
+
940
+	/**
941
+	 * Modifies the query parameters so we only get back model objects
942
+	 * that "belong" to the current user
943
+	 *
944
+	 * @param array $query_params @see EEM_Base::get_all()
945
+	 * @return array like EEM_Base::get_all
946
+	 */
947
+	public function alter_query_params_to_only_include_mine($query_params = array())
948
+	{
949
+		$wp_user_field_name = $this->wp_user_field_name();
950
+		if ($wp_user_field_name) {
951
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
952
+		}
953
+		return $query_params;
954
+	}
955
+
956
+
957
+
958
+	/**
959
+	 * Returns the name of the field's name that points to the WP_User table
960
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
+	 * foreign key to the WP_User table)
962
+	 *
963
+	 * @return string|boolean string on success, boolean false when there is no
964
+	 * foreign key to the WP_User table
965
+	 */
966
+	public function wp_user_field_name()
967
+	{
968
+		try {
969
+			if (! empty($this->_model_chain_to_wp_user)) {
970
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971
+				$last_model_name = end($models_to_follow_to_wp_users);
972
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
+			} else {
975
+				$model_with_fk_to_wp_users = $this;
976
+				$model_chain_to_wp_user = '';
977
+			}
978
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
980
+		} catch (EE_Error $e) {
981
+			return false;
982
+		}
983
+	}
984
+
985
+
986
+
987
+	/**
988
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
989
+	 * (or transiently-related model) has a foreign key to the wp_users table;
990
+	 * useful for finding if model objects of this type are 'owned' by the current user.
991
+	 * This is an empty string when the foreign key is on this model and when it isn't,
992
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
993
+	 * (or transiently-related model)
994
+	 *
995
+	 * @return string
996
+	 */
997
+	public function model_chain_to_wp_user()
998
+	{
999
+		return $this->_model_chain_to_wp_user;
1000
+	}
1001
+
1002
+
1003
+
1004
+	/**
1005
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
+	 * like how registrations don't have a foreign key to wp_users, but the
1007
+	 * events they are for are), or is unrelated to wp users.
1008
+	 * generally available
1009
+	 *
1010
+	 * @return boolean
1011
+	 */
1012
+	public function is_owned()
1013
+	{
1014
+		if ($this->model_chain_to_wp_user()) {
1015
+			return true;
1016
+		} else {
1017
+			try {
1018
+				$this->get_foreign_key_to('WP_User');
1019
+				return true;
1020
+			} catch (EE_Error $e) {
1021
+				return false;
1022
+			}
1023
+		}
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
+	 * the model)
1032
+	 *
1033
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1034
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1037
+	 *                                  override this and set the select to "*", or a specific column name, like
1038
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
+	 *                                  the aliases used to refer to this selection, and values are to be
1041
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
+	 * @throws \EE_Error
1045
+	 */
1046
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
+	{
1048
+		// remember the custom selections, if any, and type cast as array
1049
+		// (unless $columns_to_select is an object, then just set as an empty array)
1050
+		// Note: (array) 'some string' === array( 'some string' )
1051
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1053
+		$select_expressions = $columns_to_select !== null
1054
+			? $this->_construct_select_from_input($columns_to_select)
1055
+			: $this->_construct_default_select_sql($model_query_info);
1056
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058
+	}
1059
+
1060
+
1061
+
1062
+	/**
1063
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1064
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1065
+	 * take care of joins, field preparation etc.
1066
+	 *
1067
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1068
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1071
+	 *                                  override this and set the select to "*", or a specific column name, like
1072
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1073
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1074
+	 *                                  the aliases used to refer to this selection, and values are to be
1075
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1076
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1077
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1078
+	 * @throws \EE_Error
1079
+	 */
1080
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1081
+	{
1082
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1083
+	}
1084
+
1085
+
1086
+
1087
+	/**
1088
+	 * For creating a custom select statement
1089
+	 *
1090
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1091
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1092
+	 *                                 SQL, and 1=>is the datatype
1093
+	 * @throws EE_Error
1094
+	 * @return string
1095
+	 */
1096
+	private function _construct_select_from_input($columns_to_select)
1097
+	{
1098
+		if (is_array($columns_to_select)) {
1099
+			$select_sql_array = array();
1100
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
+					throw new EE_Error(
1103
+						sprintf(
1104
+							__(
1105
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1106
+								"event_espresso"
1107
+							),
1108
+							$selection_and_datatype,
1109
+							$alias
1110
+						)
1111
+					);
1112
+				}
1113
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
+					throw new EE_Error(
1115
+						sprintf(
1116
+							__(
1117
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1118
+								"event_espresso"
1119
+							),
1120
+							$selection_and_datatype[1],
1121
+							$selection_and_datatype[0],
1122
+							$alias,
1123
+							implode(",", $this->_valid_wpdb_data_types)
1124
+						)
1125
+					);
1126
+				}
1127
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1128
+			}
1129
+			$columns_to_select_string = implode(", ", $select_sql_array);
1130
+		} else {
1131
+			$columns_to_select_string = $columns_to_select;
1132
+		}
1133
+		return $columns_to_select_string;
1134
+	}
1135
+
1136
+
1137
+
1138
+	/**
1139
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1140
+	 *
1141
+	 * @return string
1142
+	 * @throws \EE_Error
1143
+	 */
1144
+	public function primary_key_name()
1145
+	{
1146
+		return $this->get_primary_key_field()->get_name();
1147
+	}
1148
+
1149
+
1150
+
1151
+	/**
1152
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1153
+	 * If there is no primary key on this model, $id is treated as primary key string
1154
+	 *
1155
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1156
+	 * @return EE_Base_Class
1157
+	 */
1158
+	public function get_one_by_ID($id)
1159
+	{
1160
+		if ($this->get_from_entity_map($id)) {
1161
+			return $this->get_from_entity_map($id);
1162
+		}
1163
+		return $this->get_one(
1164
+			$this->alter_query_params_to_restrict_by_ID(
1165
+				$id,
1166
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1167
+			)
1168
+		);
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * Alters query parameters to only get items with this ID are returned.
1175
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1176
+	 * or could just be a simple primary key ID
1177
+	 *
1178
+	 * @param int   $id
1179
+	 * @param array $query_params
1180
+	 * @return array of normal query params, @see EEM_Base::get_all
1181
+	 * @throws \EE_Error
1182
+	 */
1183
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184
+	{
1185
+		if (! isset($query_params[0])) {
1186
+			$query_params[0] = array();
1187
+		}
1188
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1189
+		if ($conditions_from_id === null) {
1190
+			$query_params[0][$this->primary_key_name()] = $id;
1191
+		} else {
1192
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1193
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1194
+		}
1195
+		return $query_params;
1196
+	}
1197
+
1198
+
1199
+
1200
+	/**
1201
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1202
+	 * array. If no item is found, null is returned.
1203
+	 *
1204
+	 * @param array $query_params like EEM_Base's $query_params variable.
1205
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1206
+	 * @throws \EE_Error
1207
+	 */
1208
+	public function get_one($query_params = array())
1209
+	{
1210
+		if (! is_array($query_params)) {
1211
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1212
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213
+					gettype($query_params)), '4.6.0');
1214
+			$query_params = array();
1215
+		}
1216
+		$query_params['limit'] = 1;
1217
+		$items = $this->get_all($query_params);
1218
+		if (empty($items)) {
1219
+			return null;
1220
+		} else {
1221
+			return array_shift($items);
1222
+		}
1223
+	}
1224
+
1225
+
1226
+
1227
+	/**
1228
+	 * Returns the next x number of items in sequence from the given value as
1229
+	 * found in the database matching the given query conditions.
1230
+	 *
1231
+	 * @param mixed $current_field_value    Value used for the reference point.
1232
+	 * @param null  $field_to_order_by      What field is used for the
1233
+	 *                                      reference point.
1234
+	 * @param int   $limit                  How many to return.
1235
+	 * @param array $query_params           Extra conditions on the query.
1236
+	 * @param null  $columns_to_select      If left null, then an array of
1237
+	 *                                      EE_Base_Class objects is returned,
1238
+	 *                                      otherwise you can indicate just the
1239
+	 *                                      columns you want returned.
1240
+	 * @return EE_Base_Class[]|array
1241
+	 * @throws \EE_Error
1242
+	 */
1243
+	public function next_x(
1244
+		$current_field_value,
1245
+		$field_to_order_by = null,
1246
+		$limit = 1,
1247
+		$query_params = array(),
1248
+		$columns_to_select = null
1249
+	) {
1250
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1251
+			$columns_to_select);
1252
+	}
1253
+
1254
+
1255
+
1256
+	/**
1257
+	 * Returns the previous x number of items in sequence from the given value
1258
+	 * as found in the database matching the given query conditions.
1259
+	 *
1260
+	 * @param mixed $current_field_value    Value used for the reference point.
1261
+	 * @param null  $field_to_order_by      What field is used for the
1262
+	 *                                      reference point.
1263
+	 * @param int   $limit                  How many to return.
1264
+	 * @param array $query_params           Extra conditions on the query.
1265
+	 * @param null  $columns_to_select      If left null, then an array of
1266
+	 *                                      EE_Base_Class objects is returned,
1267
+	 *                                      otherwise you can indicate just the
1268
+	 *                                      columns you want returned.
1269
+	 * @return EE_Base_Class[]|array
1270
+	 * @throws \EE_Error
1271
+	 */
1272
+	public function previous_x(
1273
+		$current_field_value,
1274
+		$field_to_order_by = null,
1275
+		$limit = 1,
1276
+		$query_params = array(),
1277
+		$columns_to_select = null
1278
+	) {
1279
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1280
+			$columns_to_select);
1281
+	}
1282
+
1283
+
1284
+
1285
+	/**
1286
+	 * Returns the next item in sequence from the given value as found in the
1287
+	 * database matching the given query conditions.
1288
+	 *
1289
+	 * @param mixed $current_field_value    Value used for the reference point.
1290
+	 * @param null  $field_to_order_by      What field is used for the
1291
+	 *                                      reference point.
1292
+	 * @param array $query_params           Extra conditions on the query.
1293
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1294
+	 *                                      object is returned, otherwise you
1295
+	 *                                      can indicate just the columns you
1296
+	 *                                      want and a single array indexed by
1297
+	 *                                      the columns will be returned.
1298
+	 * @return EE_Base_Class|null|array()
1299
+	 * @throws \EE_Error
1300
+	 */
1301
+	public function next(
1302
+		$current_field_value,
1303
+		$field_to_order_by = null,
1304
+		$query_params = array(),
1305
+		$columns_to_select = null
1306
+	) {
1307
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1308
+			$columns_to_select);
1309
+		return empty($results) ? null : reset($results);
1310
+	}
1311
+
1312
+
1313
+
1314
+	/**
1315
+	 * Returns the previous item in sequence from the given value as found in
1316
+	 * the database matching the given query conditions.
1317
+	 *
1318
+	 * @param mixed $current_field_value    Value used for the reference point.
1319
+	 * @param null  $field_to_order_by      What field is used for the
1320
+	 *                                      reference point.
1321
+	 * @param array $query_params           Extra conditions on the query.
1322
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1323
+	 *                                      object is returned, otherwise you
1324
+	 *                                      can indicate just the columns you
1325
+	 *                                      want and a single array indexed by
1326
+	 *                                      the columns will be returned.
1327
+	 * @return EE_Base_Class|null|array()
1328
+	 * @throws EE_Error
1329
+	 */
1330
+	public function previous(
1331
+		$current_field_value,
1332
+		$field_to_order_by = null,
1333
+		$query_params = array(),
1334
+		$columns_to_select = null
1335
+	) {
1336
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1337
+			$columns_to_select);
1338
+		return empty($results) ? null : reset($results);
1339
+	}
1340
+
1341
+
1342
+
1343
+	/**
1344
+	 * Returns the a consecutive number of items in sequence from the given
1345
+	 * value as found in the database matching the given query conditions.
1346
+	 *
1347
+	 * @param mixed  $current_field_value   Value used for the reference point.
1348
+	 * @param string $operand               What operand is used for the sequence.
1349
+	 * @param string $field_to_order_by     What field is used for the reference point.
1350
+	 * @param int    $limit                 How many to return.
1351
+	 * @param array  $query_params          Extra conditions on the query.
1352
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1353
+	 *                                      otherwise you can indicate just the columns you want returned.
1354
+	 * @return EE_Base_Class[]|array
1355
+	 * @throws EE_Error
1356
+	 */
1357
+	protected function _get_consecutive(
1358
+		$current_field_value,
1359
+		$operand = '>',
1360
+		$field_to_order_by = null,
1361
+		$limit = 1,
1362
+		$query_params = array(),
1363
+		$columns_to_select = null
1364
+	) {
1365
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1366
+		if (empty($field_to_order_by)) {
1367
+			if ($this->has_primary_key_field()) {
1368
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1369
+			} else {
1370
+				if (WP_DEBUG) {
1371
+					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).',
1372
+						'event_espresso'));
1373
+				}
1374
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1375
+				return array();
1376
+			}
1377
+		}
1378
+		if (! is_array($query_params)) {
1379
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381
+					gettype($query_params)), '4.6.0');
1382
+			$query_params = array();
1383
+		}
1384
+		//let's add the where query param for consecutive look up.
1385
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386
+		$query_params['limit'] = $limit;
1387
+		//set direction
1388
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
+		$query_params['order_by'] = $operand === '>'
1390
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1391
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1392
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1393
+		if (empty($columns_to_select)) {
1394
+			return $this->get_all($query_params);
1395
+		} else {
1396
+			//getting just the fields
1397
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1398
+		}
1399
+	}
1400
+
1401
+
1402
+
1403
+	/**
1404
+	 * This sets the _timezone property after model object has been instantiated.
1405
+	 *
1406
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
+	 */
1408
+	public function set_timezone($timezone)
1409
+	{
1410
+		if ($timezone !== null) {
1411
+			$this->_timezone = $timezone;
1412
+		}
1413
+		//note we need to loop through relations and set the timezone on those objects as well.
1414
+		foreach ($this->_model_relations as $relation) {
1415
+			$relation->set_timezone($timezone);
1416
+		}
1417
+		//and finally we do the same for any datetime fields
1418
+		foreach ($this->_fields as $field) {
1419
+			if ($field instanceof EE_Datetime_Field) {
1420
+				$field->set_timezone($timezone);
1421
+			}
1422
+		}
1423
+	}
1424
+
1425
+
1426
+
1427
+	/**
1428
+	 * This just returns whatever is set for the current timezone.
1429
+	 *
1430
+	 * @access public
1431
+	 * @return string
1432
+	 */
1433
+	public function get_timezone()
1434
+	{
1435
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
+		if (empty($this->_timezone)) {
1437
+			foreach ($this->_fields as $field) {
1438
+				if ($field instanceof EE_Datetime_Field) {
1439
+					$this->set_timezone($field->get_timezone());
1440
+					break;
1441
+				}
1442
+			}
1443
+		}
1444
+		//if timezone STILL empty then return the default timezone for the site.
1445
+		if (empty($this->_timezone)) {
1446
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
+		}
1448
+		return $this->_timezone;
1449
+	}
1450
+
1451
+
1452
+
1453
+	/**
1454
+	 * This returns the date formats set for the given field name and also ensures that
1455
+	 * $this->_timezone property is set correctly.
1456
+	 *
1457
+	 * @since 4.6.x
1458
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1459
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
+	 * @return array formats in an array with the date format first, and the time format last.
1462
+	 */
1463
+	public function get_formats_for($field_name, $pretty = false)
1464
+	{
1465
+		$field_settings = $this->field_settings_for($field_name);
1466
+		//if not a valid EE_Datetime_Field then throw error
1467
+		if (! $field_settings instanceof EE_Datetime_Field) {
1468
+			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.',
1469
+				'event_espresso'), $field_name));
1470
+		}
1471
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1472
+		//the field.
1473
+		$this->_timezone = $field_settings->get_timezone();
1474
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1475
+	}
1476
+
1477
+
1478
+
1479
+	/**
1480
+	 * This returns the current time in a format setup for a query on this model.
1481
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1482
+	 * it will return:
1483
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1484
+	 *  NOW
1485
+	 *  - or a unix timestamp (equivalent to time())
1486
+	 *
1487
+	 * @since 4.6.x
1488
+	 * @param string $field_name       The field the current time is needed for.
1489
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1490
+	 *                                 formatted string matching the set format for the field in the set timezone will
1491
+	 *                                 be returned.
1492
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1493
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1494
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1495
+	 *                                 exception is triggered.
1496
+	 */
1497
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1498
+	{
1499
+		$formats = $this->get_formats_for($field_name);
1500
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1501
+		if ($timestamp) {
1502
+			return $DateTime->format('U');
1503
+		}
1504
+		//not returning timestamp, so return formatted string in timezone.
1505
+		switch ($what) {
1506
+			case 'time' :
1507
+				return $DateTime->format($formats[1]);
1508
+				break;
1509
+			case 'date' :
1510
+				return $DateTime->format($formats[0]);
1511
+				break;
1512
+			default :
1513
+				return $DateTime->format(implode(' ', $formats));
1514
+				break;
1515
+		}
1516
+	}
1517
+
1518
+
1519
+
1520
+	/**
1521
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1522
+	 * for the model are.  Returns a DateTime object.
1523
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1524
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1525
+	 * ignored.
1526
+	 *
1527
+	 * @param string $field_name      The field being setup.
1528
+	 * @param string $timestring      The date time string being used.
1529
+	 * @param string $incoming_format The format for the time string.
1530
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1531
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1532
+	 *                                format is
1533
+	 *                                'U', this is ignored.
1534
+	 * @return DateTime
1535
+	 * @throws \EE_Error
1536
+	 */
1537
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1538
+	{
1539
+		//just using this to ensure the timezone is set correctly internally
1540
+		$this->get_formats_for($field_name);
1541
+		//load EEH_DTT_Helper
1542
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1543
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1544
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1545
+	}
1546
+
1547
+
1548
+
1549
+	/**
1550
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1551
+	 *
1552
+	 * @return EE_Table_Base[]
1553
+	 */
1554
+	public function get_tables()
1555
+	{
1556
+		return $this->_tables;
1557
+	}
1558
+
1559
+
1560
+
1561
+	/**
1562
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1563
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1564
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1565
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1566
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1567
+	 * model object with EVT_ID = 1
1568
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1569
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1570
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1571
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1572
+	 * are not specified)
1573
+	 *
1574
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1575
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1576
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1577
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1578
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1579
+	 *                                         ID=34, we'd use this method as follows:
1580
+	 *                                         EEM_Transaction::instance()->update(
1581
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1582
+	 *                                         array(array('TXN_ID'=>34)));
1583
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1584
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1585
+	 *                                         consider updating Question's QST_admin_label field is of type
1586
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1587
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1588
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1589
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1590
+	 *                                         TRUE, it is assumed that you've already called
1591
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1592
+	 *                                         malicious javascript. However, if
1593
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1594
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1595
+	 *                                         and every other field, before insertion. We provide this parameter
1596
+	 *                                         because model objects perform their prepare_for_set function on all
1597
+	 *                                         their values, and so don't need to be called again (and in many cases,
1598
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1599
+	 *                                         prepare_for_set method...)
1600
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1601
+	 *                                         in this model's entity map according to $fields_n_values that match
1602
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1603
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1604
+	 *                                         could get out-of-sync with the database
1605
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1606
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1607
+	 *                                         bad)
1608
+	 * @throws \EE_Error
1609
+	 */
1610
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1611
+	{
1612
+		if (! is_array($query_params)) {
1613
+			EE_Error::doing_it_wrong('EEM_Base::update',
1614
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1615
+					gettype($query_params)), '4.6.0');
1616
+			$query_params = array();
1617
+		}
1618
+		/**
1619
+		 * Action called before a model update call has been made.
1620
+		 *
1621
+		 * @param EEM_Base $model
1622
+		 * @param array    $fields_n_values the updated fields and their new values
1623
+		 * @param array    $query_params    @see EEM_Base::get_all()
1624
+		 */
1625
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1626
+		/**
1627
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1628
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1629
+		 *
1630
+		 * @param array    $fields_n_values fields and their new values
1631
+		 * @param EEM_Base $model           the model being queried
1632
+		 * @param array    $query_params    see EEM_Base::get_all()
1633
+		 */
1634
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1635
+			$query_params);
1636
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1637
+		//to do that, for each table, verify that it's PK isn't null.
1638
+		$tables = $this->get_tables();
1639
+		//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
1640
+		//NOTE: we should make this code more efficient by NOT querying twice
1641
+		//before the real update, but that needs to first go through ALPHA testing
1642
+		//as it's dangerous. says Mike August 8 2014
1643
+		//we want to make sure the default_where strategy is ignored
1644
+		$this->_ignore_where_strategy = true;
1645
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1646
+		foreach ($wpdb_select_results as $wpdb_result) {
1647
+			// type cast stdClass as array
1648
+			$wpdb_result = (array)$wpdb_result;
1649
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1650
+			if ($this->has_primary_key_field()) {
1651
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1652
+			} else {
1653
+				//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)
1654
+				$main_table_pk_value = null;
1655
+			}
1656
+			//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
1657
+			//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
1658
+			if (count($tables) > 1) {
1659
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1660
+				//in that table, and so we'll want to insert one
1661
+				foreach ($tables as $table_obj) {
1662
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1663
+					//if there is no private key for this table on the results, it means there's no entry
1664
+					//in this table, right? so insert a row in the current table, using any fields available
1665
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1666
+						   && $wpdb_result[$this_table_pk_column])
1667
+					) {
1668
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1669
+							$main_table_pk_value);
1670
+						//if we died here, report the error
1671
+						if (! $success) {
1672
+							return false;
1673
+						}
1674
+					}
1675
+				}
1676
+			}
1677
+			//				//and now check that if we have cached any models by that ID on the model, that
1678
+			//				//they also get updated properly
1679
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1680
+			//				if( $model_object ){
1681
+			//					foreach( $fields_n_values as $field => $value ){
1682
+			//						$model_object->set($field, $value);
1683
+			//let's make sure default_where strategy is followed now
1684
+			$this->_ignore_where_strategy = false;
1685
+		}
1686
+		//if we want to keep model objects in sync, AND
1687
+		//if this wasn't called from a model object (to update itself)
1688
+		//then we want to make sure we keep all the existing
1689
+		//model objects in sync with the db
1690
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1691
+			if ($this->has_primary_key_field()) {
1692
+				$model_objs_affected_ids = $this->get_col($query_params);
1693
+			} else {
1694
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1695
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1696
+				$model_objs_affected_ids = array();
1697
+				foreach ($models_affected_key_columns as $row) {
1698
+					$combined_index_key = $this->get_index_primary_key_string($row);
1699
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1700
+				}
1701
+			}
1702
+			if (! $model_objs_affected_ids) {
1703
+				//wait wait wait- if nothing was affected let's stop here
1704
+				return 0;
1705
+			}
1706
+			foreach ($model_objs_affected_ids as $id) {
1707
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1708
+				if ($model_obj_in_entity_map) {
1709
+					foreach ($fields_n_values as $field => $new_value) {
1710
+						$model_obj_in_entity_map->set($field, $new_value);
1711
+					}
1712
+				}
1713
+			}
1714
+			//if there is a primary key on this model, we can now do a slight optimization
1715
+			if ($this->has_primary_key_field()) {
1716
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1717
+				$query_params = array(
1718
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1719
+					'limit'                    => count($model_objs_affected_ids),
1720
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1721
+				);
1722
+			}
1723
+		}
1724
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1725
+		$SQL = "UPDATE "
1726
+			   . $model_query_info->get_full_join_sql()
1727
+			   . " SET "
1728
+			   . $this->_construct_update_sql($fields_n_values)
1729
+			   . $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
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1731
+		/**
1732
+		 * Action called after a model update call has been made.
1733
+		 *
1734
+		 * @param EEM_Base $model
1735
+		 * @param array    $fields_n_values the updated fields and their new values
1736
+		 * @param array    $query_params    @see EEM_Base::get_all()
1737
+		 * @param int      $rows_affected
1738
+		 */
1739
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1740
+		return $rows_affected;//how many supposedly got updated
1741
+	}
1742
+
1743
+
1744
+
1745
+	/**
1746
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1747
+	 * are teh values of the field specified (or by default the primary key field)
1748
+	 * that matched the query params. Note that you should pass the name of the
1749
+	 * model FIELD, not the database table's column name.
1750
+	 *
1751
+	 * @param array  $query_params @see EEM_Base::get_all()
1752
+	 * @param string $field_to_select
1753
+	 * @return array just like $wpdb->get_col()
1754
+	 * @throws \EE_Error
1755
+	 */
1756
+	public function get_col($query_params = array(), $field_to_select = null)
1757
+	{
1758
+		if ($field_to_select) {
1759
+			$field = $this->field_settings_for($field_to_select);
1760
+		} elseif ($this->has_primary_key_field()) {
1761
+			$field = $this->get_primary_key_field();
1762
+		} else {
1763
+			//no primary key, just grab the first column
1764
+			$field = reset($this->field_settings());
1765
+		}
1766
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1767
+		$select_expressions = $field->get_qualified_column();
1768
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1769
+		return $this->_do_wpdb_query('get_col', array($SQL));
1770
+	}
1771
+
1772
+
1773
+
1774
+	/**
1775
+	 * Returns a single column value for a single row from the database
1776
+	 *
1777
+	 * @param array  $query_params    @see EEM_Base::get_all()
1778
+	 * @param string $field_to_select @see EEM_Base::get_col()
1779
+	 * @return string
1780
+	 * @throws \EE_Error
1781
+	 */
1782
+	public function get_var($query_params = array(), $field_to_select = null)
1783
+	{
1784
+		$query_params['limit'] = 1;
1785
+		$col = $this->get_col($query_params, $field_to_select);
1786
+		if (! empty($col)) {
1787
+			return reset($col);
1788
+		} else {
1789
+			return null;
1790
+		}
1791
+	}
1792
+
1793
+
1794
+
1795
+	/**
1796
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1797
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1798
+	 * injection, but currently no further filtering is done
1799
+	 *
1800
+	 * @global      $wpdb
1801
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1802
+	 *                               be updated to in the DB
1803
+	 * @return string of SQL
1804
+	 * @throws \EE_Error
1805
+	 */
1806
+	public function _construct_update_sql($fields_n_values)
1807
+	{
1808
+		/** @type WPDB $wpdb */
1809
+		global $wpdb;
1810
+		$cols_n_values = array();
1811
+		foreach ($fields_n_values as $field_name => $value) {
1812
+			$field_obj = $this->field_settings_for($field_name);
1813
+			//if the value is NULL, we want to assign the value to that.
1814
+			//wpdb->prepare doesn't really handle that properly
1815
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1816
+			$value_sql = $prepared_value === null ? 'NULL'
1817
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1818
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1819
+		}
1820
+		return implode(",", $cols_n_values);
1821
+	}
1822
+
1823
+
1824
+
1825
+	/**
1826
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1827
+	 * Performs a HARD delete, meaning the database row should always be removed,
1828
+	 * not just have a flag field on it switched
1829
+	 * Wrapper for EEM_Base::delete_permanently()
1830
+	 *
1831
+	 * @param mixed $id
1832
+	 * @return boolean whether the row got deleted or not
1833
+	 * @throws \EE_Error
1834
+	 */
1835
+	public function delete_permanently_by_ID($id)
1836
+	{
1837
+		return $this->delete_permanently(
1838
+			array(
1839
+				array($this->get_primary_key_field()->get_name() => $id),
1840
+				'limit' => 1,
1841
+			)
1842
+		);
1843
+	}
1844
+
1845
+
1846
+
1847
+	/**
1848
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1849
+	 * Wrapper for EEM_Base::delete()
1850
+	 *
1851
+	 * @param mixed $id
1852
+	 * @return boolean whether the row got deleted or not
1853
+	 * @throws \EE_Error
1854
+	 */
1855
+	public function delete_by_ID($id)
1856
+	{
1857
+		return $this->delete(
1858
+			array(
1859
+				array($this->get_primary_key_field()->get_name() => $id),
1860
+				'limit' => 1,
1861
+			)
1862
+		);
1863
+	}
1864
+
1865
+
1866
+
1867
+	/**
1868
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1869
+	 * meaning if the model has a field that indicates its been "trashed" or
1870
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1871
+	 *
1872
+	 * @see EEM_Base::delete_permanently
1873
+	 * @param array   $query_params
1874
+	 * @param boolean $allow_blocking
1875
+	 * @return int how many rows got deleted
1876
+	 * @throws \EE_Error
1877
+	 */
1878
+	public function delete($query_params, $allow_blocking = true)
1879
+	{
1880
+		return $this->delete_permanently($query_params, $allow_blocking);
1881
+	}
1882
+
1883
+
1884
+
1885
+	/**
1886
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1887
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1888
+	 * as archived, not actually deleted
1889
+	 *
1890
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1891
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1892
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1893
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1894
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1895
+	 *                                DB
1896
+	 * @return int how many rows got deleted
1897
+	 * @throws \EE_Error
1898
+	 */
1899
+	public function delete_permanently($query_params, $allow_blocking = true)
1900
+	{
1901
+		/**
1902
+		 * Action called just before performing a real deletion query. You can use the
1903
+		 * model and its $query_params to find exactly which items will be deleted
1904
+		 *
1905
+		 * @param EEM_Base $model
1906
+		 * @param array    $query_params   @see EEM_Base::get_all()
1907
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1908
+		 *                                 to block (prevent) this deletion
1909
+		 */
1910
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1911
+		//some MySQL databases may be running safe mode, which may restrict
1912
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1913
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1914
+		//to delete them
1915
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1916
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1917
+		if ($deletion_where) {
1918
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1919
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1920
+			$table_aliases = array_keys($this->_tables);
1921
+			$SQL = "DELETE "
1922
+				   . implode(", ", $table_aliases)
1923
+				   . " FROM "
1924
+				   . $model_query_info->get_full_join_sql()
1925
+				   . " WHERE "
1926
+				   . $deletion_where;
1927
+			//		/echo "delete sql:$SQL";
1928
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1929
+		} else {
1930
+			$rows_deleted = 0;
1931
+		}
1932
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1933
+		if ($this->has_primary_key_field()) {
1934
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1935
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1936
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1937
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1938
+				}
1939
+			}
1940
+		}
1941
+		/**
1942
+		 * Action called just after performing a real deletion query. Although at this point the
1943
+		 * items should have been deleted
1944
+		 *
1945
+		 * @param EEM_Base $model
1946
+		 * @param array    $query_params @see EEM_Base::get_all()
1947
+		 * @param int      $rows_deleted
1948
+		 */
1949
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1950
+		return $rows_deleted;//how many supposedly got deleted
1951
+	}
1952
+
1953
+
1954
+
1955
+	/**
1956
+	 * Checks all the relations that throw error messages when there are blocking related objects
1957
+	 * for related model objects. If there are any related model objects on those relations,
1958
+	 * adds an EE_Error, and return true
1959
+	 *
1960
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1961
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1962
+	 *                                                 should be ignored when determining whether there are related
1963
+	 *                                                 model objects which block this model object's deletion. Useful
1964
+	 *                                                 if you know A is related to B and are considering deleting A,
1965
+	 *                                                 but want to see if A has any other objects blocking its deletion
1966
+	 *                                                 before removing the relation between A and B
1967
+	 * @return boolean
1968
+	 * @throws \EE_Error
1969
+	 */
1970
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1971
+	{
1972
+		//first, if $ignore_this_model_obj was supplied, get its model
1973
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1974
+			$ignored_model = $ignore_this_model_obj->get_model();
1975
+		} else {
1976
+			$ignored_model = null;
1977
+		}
1978
+		//now check all the relations of $this_model_obj_or_id and see if there
1979
+		//are any related model objects blocking it?
1980
+		$is_blocked = false;
1981
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
1982
+			if ($relation_obj->block_delete_if_related_models_exist()) {
1983
+				//if $ignore_this_model_obj was supplied, then for the query
1984
+				//on that model needs to be told to ignore $ignore_this_model_obj
1985
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1986
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1987
+						array(
1988
+							$ignored_model->get_primary_key_field()->get_name() => array(
1989
+								'!=',
1990
+								$ignore_this_model_obj->ID(),
1991
+							),
1992
+						),
1993
+					));
1994
+				} else {
1995
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1996
+				}
1997
+				if ($related_model_objects) {
1998
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1999
+					$is_blocked = true;
2000
+				}
2001
+			}
2002
+		}
2003
+		return $is_blocked;
2004
+	}
2005
+
2006
+
2007
+
2008
+	/**
2009
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2010
+	 * well.
2011
+	 *
2012
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2013
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2014
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
2015
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
2016
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
2017
+	 *                                      easily corrupt your DB
2018
+	 * @throws EE_Error
2019
+	 * @return string    everything that comes after the WHERE statement.
2020
+	 */
2021
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2022
+	{
2023
+		if ($this->has_primary_key_field()) {
2024
+			$primary_table = $this->_get_main_table();
2025
+			$other_tables = $this->_get_other_tables();
2026
+			$deletes = $query = array();
2027
+			foreach ($objects_for_deletion as $delete_object) {
2028
+				//before we mark this object for deletion,
2029
+				//make sure there's no related objects blocking its deletion (if we're checking)
2030
+				if (
2031
+					$allow_blocking
2032
+					&& $this->delete_is_blocked_by_related_models(
2033
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
2034
+					)
2035
+				) {
2036
+					continue;
2037
+				}
2038
+				//primary table deletes
2039
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2040
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2041
+				}
2042
+				//other tables
2043
+				if (! empty($other_tables)) {
2044
+					foreach ($other_tables as $ot) {
2045
+						//first check if we've got the foreign key column here.
2046
+						if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2047
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2048
+						}
2049
+						// wait! it's entirely possible that we'll have a the primary key
2050
+						// for this table in here, if it's a foreign key for one of the other secondary tables
2051
+						if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2052
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2053
+						}
2054
+						// finally, it is possible that the fk for this table is found
2055
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
2056
+						if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2057
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2058
+						}
2059
+					}
2060
+				}
2061
+			}
2062
+			//we should have deletes now, so let's just go through and setup the where statement
2063
+			foreach ($deletes as $column => $values) {
2064
+				//make sure we have unique $values;
2065
+				$values = array_unique($values);
2066
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
2067
+			}
2068
+			return ! empty($query) ? implode(' AND ', $query) : '';
2069
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2070
+			$ways_to_identify_a_row = array();
2071
+			$fields = $this->get_combined_primary_key_fields();
2072
+			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2073
+			foreach ($objects_for_deletion as $delete_object) {
2074
+				$values_for_each_cpk_for_a_row = array();
2075
+				foreach ($fields as $cpk_field) {
2076
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2077
+						$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2078
+														   . "="
2079
+														   . $delete_object[$cpk_field->get_qualified_column()];
2080
+					}
2081
+				}
2082
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2083
+			}
2084
+			return implode(" OR ", $ways_to_identify_a_row);
2085
+		} else {
2086
+			//so there's no primary key and no combined key...
2087
+			//sorry, can't help you
2088
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2089
+				"event_espresso"), get_class($this)));
2090
+		}
2091
+	}
2092
+
2093
+
2094
+
2095
+	/**
2096
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2097
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2098
+	 * column
2099
+	 *
2100
+	 * @param array  $query_params   like EEM_Base::get_all's
2101
+	 * @param string $field_to_count field on model to count by (not column name)
2102
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2103
+	 *                               that by the setting $distinct to TRUE;
2104
+	 * @return int
2105
+	 * @throws \EE_Error
2106
+	 */
2107
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2108
+	{
2109
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2110
+		if ($field_to_count) {
2111
+			$field_obj = $this->field_settings_for($field_to_count);
2112
+			$column_to_count = $field_obj->get_qualified_column();
2113
+		} elseif ($this->has_primary_key_field()) {
2114
+			$pk_field_obj = $this->get_primary_key_field();
2115
+			$column_to_count = $pk_field_obj->get_qualified_column();
2116
+		} else {
2117
+			//there's no primary key
2118
+			//if we're counting distinct items, and there's no primary key,
2119
+			//we need to list out the columns for distinction;
2120
+			//otherwise we can just use star
2121
+			if ($distinct) {
2122
+				$columns_to_use = array();
2123
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2124
+					$columns_to_use[] = $field_obj->get_qualified_column();
2125
+				}
2126
+				$column_to_count = implode(',', $columns_to_use);
2127
+			} else {
2128
+				$column_to_count = '*';
2129
+			}
2130
+		}
2131
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2132
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2133
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2134
+	}
2135
+
2136
+
2137
+
2138
+	/**
2139
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2140
+	 *
2141
+	 * @param array  $query_params like EEM_Base::get_all
2142
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2143
+	 * @return float
2144
+	 * @throws \EE_Error
2145
+	 */
2146
+	public function sum($query_params, $field_to_sum = null)
2147
+	{
2148
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2149
+		if ($field_to_sum) {
2150
+			$field_obj = $this->field_settings_for($field_to_sum);
2151
+		} else {
2152
+			$field_obj = $this->get_primary_key_field();
2153
+		}
2154
+		$column_to_count = $field_obj->get_qualified_column();
2155
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2156
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2157
+		$data_type = $field_obj->get_wpdb_data_type();
2158
+		if ($data_type === '%d' || $data_type === '%s') {
2159
+			return (float)$return_value;
2160
+		} else {//must be %f
2161
+			return (float)$return_value;
2162
+		}
2163
+	}
2164
+
2165
+
2166
+
2167
+	/**
2168
+	 * Just calls the specified method on $wpdb with the given arguments
2169
+	 * Consolidates a little extra error handling code
2170
+	 *
2171
+	 * @param string $wpdb_method
2172
+	 * @param array  $arguments_to_provide
2173
+	 * @throws EE_Error
2174
+	 * @global wpdb  $wpdb
2175
+	 * @return mixed
2176
+	 */
2177
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2178
+	{
2179
+		//if we're in maintenance mode level 2, DON'T run any queries
2180
+		//because level 2 indicates the database needs updating and
2181
+		//is probably out of sync with the code
2182
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2183
+			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.",
2184
+				"event_espresso")));
2185
+		}
2186
+		/** @type WPDB $wpdb */
2187
+		global $wpdb;
2188
+		if (! method_exists($wpdb, $wpdb_method)) {
2189
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2190
+				'event_espresso'), $wpdb_method));
2191
+		}
2192
+		if (WP_DEBUG) {
2193
+			$old_show_errors_value = $wpdb->show_errors;
2194
+			$wpdb->show_errors(false);
2195
+		}
2196
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2197
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2198
+		if (WP_DEBUG) {
2199
+			$wpdb->show_errors($old_show_errors_value);
2200
+			if (! empty($wpdb->last_error)) {
2201
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2202
+			} elseif ($result === false) {
2203
+				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"',
2204
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2205
+			}
2206
+		} elseif ($result === false) {
2207
+			EE_Error::add_error(
2208
+				sprintf(
2209
+					__('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"',
2210
+						'event_espresso'),
2211
+					$wpdb_method,
2212
+					var_export($arguments_to_provide, true),
2213
+					$wpdb->last_error
2214
+				),
2215
+				__FILE__,
2216
+				__FUNCTION__,
2217
+				__LINE__
2218
+			);
2219
+		}
2220
+		return $result;
2221
+	}
2222
+
2223
+
2224
+
2225
+	/**
2226
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2227
+	 * and if there's an error tries to verify the DB is correct. Uses
2228
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2229
+	 * we should try to fix the EE core db, the addons, or just give up
2230
+	 *
2231
+	 * @param string $wpdb_method
2232
+	 * @param array  $arguments_to_provide
2233
+	 * @return mixed
2234
+	 */
2235
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2236
+	{
2237
+		/** @type WPDB $wpdb */
2238
+		global $wpdb;
2239
+		$wpdb->last_error = null;
2240
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2241
+		// was there an error running the query? but we don't care on new activations
2242
+		// (we're going to setup the DB anyway on new activations)
2243
+		if (($result === false || ! empty($wpdb->last_error))
2244
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2245
+		) {
2246
+			switch (EEM_Base::$_db_verification_level) {
2247
+				case EEM_Base::db_verified_none :
2248
+					// let's double-check core's DB
2249
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2250
+					break;
2251
+				case EEM_Base::db_verified_core :
2252
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2253
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2254
+					break;
2255
+				case EEM_Base::db_verified_addons :
2256
+					// ummmm... you in trouble
2257
+					return $result;
2258
+					break;
2259
+			}
2260
+			if (! empty($error_message)) {
2261
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2262
+				trigger_error($error_message);
2263
+			}
2264
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2265
+		}
2266
+		return $result;
2267
+	}
2268
+
2269
+
2270
+
2271
+	/**
2272
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2273
+	 * EEM_Base::$_db_verification_level
2274
+	 *
2275
+	 * @param string $wpdb_method
2276
+	 * @param array  $arguments_to_provide
2277
+	 * @return string
2278
+	 */
2279
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2280
+	{
2281
+		/** @type WPDB $wpdb */
2282
+		global $wpdb;
2283
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2284
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2285
+		$error_message = sprintf(
2286
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2287
+				'event_espresso'),
2288
+			$wpdb->last_error,
2289
+			$wpdb_method,
2290
+			wp_json_encode($arguments_to_provide)
2291
+		);
2292
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2293
+		return $error_message;
2294
+	}
2295
+
2296
+
2297
+
2298
+	/**
2299
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2300
+	 * EEM_Base::$_db_verification_level
2301
+	 *
2302
+	 * @param $wpdb_method
2303
+	 * @param $arguments_to_provide
2304
+	 * @return string
2305
+	 */
2306
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2307
+	{
2308
+		/** @type WPDB $wpdb */
2309
+		global $wpdb;
2310
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2311
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2312
+		$error_message = sprintf(
2313
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2314
+				'event_espresso'),
2315
+			$wpdb->last_error,
2316
+			$wpdb_method,
2317
+			wp_json_encode($arguments_to_provide)
2318
+		);
2319
+		EE_System::instance()->initialize_addons();
2320
+		return $error_message;
2321
+	}
2322
+
2323
+
2324
+
2325
+	/**
2326
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2327
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2328
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2329
+	 * ..."
2330
+	 *
2331
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2332
+	 * @return string
2333
+	 */
2334
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2335
+	{
2336
+		return " FROM " . $model_query_info->get_full_join_sql() .
2337
+			   $model_query_info->get_where_sql() .
2338
+			   $model_query_info->get_group_by_sql() .
2339
+			   $model_query_info->get_having_sql() .
2340
+			   $model_query_info->get_order_by_sql() .
2341
+			   $model_query_info->get_limit_sql();
2342
+	}
2343
+
2344
+
2345
+
2346
+	/**
2347
+	 * Set to easily debug the next X queries ran from this model.
2348
+	 *
2349
+	 * @param int $count
2350
+	 */
2351
+	public function show_next_x_db_queries($count = 1)
2352
+	{
2353
+		$this->_show_next_x_db_queries = $count;
2354
+	}
2355
+
2356
+
2357
+
2358
+	/**
2359
+	 * @param $sql_query
2360
+	 */
2361
+	public function show_db_query_if_previously_requested($sql_query)
2362
+	{
2363
+		if ($this->_show_next_x_db_queries > 0) {
2364
+			echo $sql_query;
2365
+			$this->_show_next_x_db_queries--;
2366
+		}
2367
+	}
2368
+
2369
+
2370
+
2371
+	/**
2372
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2373
+	 * There are the 3 cases:
2374
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2375
+	 * $otherModelObject has no ID, it is first saved.
2376
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2377
+	 * has no ID, it is first saved.
2378
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2379
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2380
+	 * join table
2381
+	 *
2382
+	 * @param        EE_Base_Class                     /int $thisModelObject
2383
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2384
+	 * @param string $relationName                     , key in EEM_Base::_relations
2385
+	 *                                                 an attendee to a group, you also want to specify which role they
2386
+	 *                                                 will have in that group. So you would use this parameter to
2387
+	 *                                                 specify array('role-column-name'=>'role-id')
2388
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2389
+	 *                                                 to for relation to methods that allow you to further specify
2390
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2391
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2392
+	 *                                                 because these will be inserted in any new rows created as well.
2393
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2394
+	 * @throws \EE_Error
2395
+	 */
2396
+	public function add_relationship_to(
2397
+		$id_or_obj,
2398
+		$other_model_id_or_obj,
2399
+		$relationName,
2400
+		$extra_join_model_fields_n_values = array()
2401
+	) {
2402
+		$relation_obj = $this->related_settings_for($relationName);
2403
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2404
+	}
2405
+
2406
+
2407
+
2408
+	/**
2409
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2410
+	 * There are the 3 cases:
2411
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2412
+	 * error
2413
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2414
+	 * an error
2415
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2416
+	 *
2417
+	 * @param        EE_Base_Class /int $id_or_obj
2418
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2419
+	 * @param string $relationName key in EEM_Base::_relations
2420
+	 * @return boolean of success
2421
+	 * @throws \EE_Error
2422
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2423
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2424
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2425
+	 *                             because these will be inserted in any new rows created as well.
2426
+	 */
2427
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2428
+	{
2429
+		$relation_obj = $this->related_settings_for($relationName);
2430
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2431
+	}
2432
+
2433
+
2434
+
2435
+	/**
2436
+	 * @param mixed           $id_or_obj
2437
+	 * @param string          $relationName
2438
+	 * @param array           $where_query_params
2439
+	 * @param EE_Base_Class[] objects to which relations were removed
2440
+	 * @return \EE_Base_Class[]
2441
+	 * @throws \EE_Error
2442
+	 */
2443
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2444
+	{
2445
+		$relation_obj = $this->related_settings_for($relationName);
2446
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2447
+	}
2448
+
2449
+
2450
+
2451
+	/**
2452
+	 * Gets all the related items of the specified $model_name, using $query_params.
2453
+	 * Note: by default, we remove the "default query params"
2454
+	 * because we want to get even deleted items etc.
2455
+	 *
2456
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2457
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2458
+	 * @param array  $query_params like EEM_Base::get_all
2459
+	 * @return EE_Base_Class[]
2460
+	 * @throws \EE_Error
2461
+	 */
2462
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2463
+	{
2464
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2465
+		$relation_settings = $this->related_settings_for($model_name);
2466
+		return $relation_settings->get_all_related($model_obj, $query_params);
2467
+	}
2468
+
2469
+
2470
+
2471
+	/**
2472
+	 * Deletes all the model objects across the relation indicated by $model_name
2473
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2474
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2475
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2476
+	 *
2477
+	 * @param EE_Base_Class|int|string $id_or_obj
2478
+	 * @param string                   $model_name
2479
+	 * @param array                    $query_params
2480
+	 * @return int how many deleted
2481
+	 * @throws \EE_Error
2482
+	 */
2483
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2484
+	{
2485
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2486
+		$relation_settings = $this->related_settings_for($model_name);
2487
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2488
+	}
2489
+
2490
+
2491
+
2492
+	/**
2493
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2494
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2495
+	 * the model objects can't be hard deleted because of blocking related model objects,
2496
+	 * just does a soft-delete on them instead.
2497
+	 *
2498
+	 * @param EE_Base_Class|int|string $id_or_obj
2499
+	 * @param string                   $model_name
2500
+	 * @param array                    $query_params
2501
+	 * @return int how many deleted
2502
+	 * @throws \EE_Error
2503
+	 */
2504
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2505
+	{
2506
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2507
+		$relation_settings = $this->related_settings_for($model_name);
2508
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2509
+	}
2510
+
2511
+
2512
+
2513
+	/**
2514
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2515
+	 * unless otherwise specified in the $query_params
2516
+	 *
2517
+	 * @param        int             /EE_Base_Class $id_or_obj
2518
+	 * @param string $model_name     like 'Event', or 'Registration'
2519
+	 * @param array  $query_params   like EEM_Base::get_all's
2520
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2521
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2522
+	 *                               that by the setting $distinct to TRUE;
2523
+	 * @return int
2524
+	 * @throws \EE_Error
2525
+	 */
2526
+	public function count_related(
2527
+		$id_or_obj,
2528
+		$model_name,
2529
+		$query_params = array(),
2530
+		$field_to_count = null,
2531
+		$distinct = false
2532
+	) {
2533
+		$related_model = $this->get_related_model_obj($model_name);
2534
+		//we're just going to use the query params on the related model's normal get_all query,
2535
+		//except add a condition to say to match the current mod
2536
+		if (! isset($query_params['default_where_conditions'])) {
2537
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2538
+		}
2539
+		$this_model_name = $this->get_this_model_name();
2540
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2541
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2542
+		return $related_model->count($query_params, $field_to_count, $distinct);
2543
+	}
2544
+
2545
+
2546
+
2547
+	/**
2548
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2549
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2550
+	 *
2551
+	 * @param        int           /EE_Base_Class $id_or_obj
2552
+	 * @param string $model_name   like 'Event', or 'Registration'
2553
+	 * @param array  $query_params like EEM_Base::get_all's
2554
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2555
+	 * @return float
2556
+	 * @throws \EE_Error
2557
+	 */
2558
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2559
+	{
2560
+		$related_model = $this->get_related_model_obj($model_name);
2561
+		if (! is_array($query_params)) {
2562
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2563
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2564
+					gettype($query_params)), '4.6.0');
2565
+			$query_params = array();
2566
+		}
2567
+		//we're just going to use the query params on the related model's normal get_all query,
2568
+		//except add a condition to say to match the current mod
2569
+		if (! isset($query_params['default_where_conditions'])) {
2570
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2571
+		}
2572
+		$this_model_name = $this->get_this_model_name();
2573
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2574
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2575
+		return $related_model->sum($query_params, $field_to_sum);
2576
+	}
2577
+
2578
+
2579
+
2580
+	/**
2581
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2582
+	 * $modelObject
2583
+	 *
2584
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2585
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2586
+	 * @param array               $query_params     like EEM_Base::get_all's
2587
+	 * @return EE_Base_Class
2588
+	 * @throws \EE_Error
2589
+	 */
2590
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2591
+	{
2592
+		$query_params['limit'] = 1;
2593
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2594
+		if ($results) {
2595
+			return array_shift($results);
2596
+		} else {
2597
+			return null;
2598
+		}
2599
+	}
2600
+
2601
+
2602
+
2603
+	/**
2604
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2605
+	 *
2606
+	 * @return string
2607
+	 */
2608
+	public function get_this_model_name()
2609
+	{
2610
+		return str_replace("EEM_", "", get_class($this));
2611
+	}
2612
+
2613
+
2614
+
2615
+	/**
2616
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2617
+	 *
2618
+	 * @return EE_Any_Foreign_Model_Name_Field
2619
+	 * @throws EE_Error
2620
+	 */
2621
+	public function get_field_containing_related_model_name()
2622
+	{
2623
+		foreach ($this->field_settings(true) as $field) {
2624
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2625
+				$field_with_model_name = $field;
2626
+			}
2627
+		}
2628
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2629
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2630
+				$this->get_this_model_name()));
2631
+		}
2632
+		return $field_with_model_name;
2633
+	}
2634
+
2635
+
2636
+
2637
+	/**
2638
+	 * Inserts a new entry into the database, for each table.
2639
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2640
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2641
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2642
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2643
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2644
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2645
+	 *
2646
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2647
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2648
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2649
+	 *                              of EEM_Base)
2650
+	 * @return int new primary key on main table that got inserted
2651
+	 * @throws EE_Error
2652
+	 */
2653
+	public function insert($field_n_values)
2654
+	{
2655
+		/**
2656
+		 * Filters the fields and their values before inserting an item using the models
2657
+		 *
2658
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2659
+		 * @param EEM_Base $model           the model used
2660
+		 */
2661
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2662
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2663
+			$main_table = $this->_get_main_table();
2664
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2665
+			if ($new_id !== false) {
2666
+				foreach ($this->_get_other_tables() as $other_table) {
2667
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2668
+				}
2669
+			}
2670
+			/**
2671
+			 * Done just after attempting to insert a new model object
2672
+			 *
2673
+			 * @param EEM_Base   $model           used
2674
+			 * @param array      $fields_n_values fields and their values
2675
+			 * @param int|string the              ID of the newly-inserted model object
2676
+			 */
2677
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2678
+			return $new_id;
2679
+		} else {
2680
+			return false;
2681
+		}
2682
+	}
2683
+
2684
+
2685
+
2686
+	/**
2687
+	 * Checks that the result would satisfy the unique indexes on this model
2688
+	 *
2689
+	 * @param array  $field_n_values
2690
+	 * @param string $action
2691
+	 * @return boolean
2692
+	 * @throws \EE_Error
2693
+	 */
2694
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2695
+	{
2696
+		foreach ($this->unique_indexes() as $index_name => $index) {
2697
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2698
+			if ($this->exists(array($uniqueness_where_params))) {
2699
+				EE_Error::add_error(
2700
+					sprintf(
2701
+						__(
2702
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2703
+							"event_espresso"
2704
+						),
2705
+						$action,
2706
+						$this->_get_class_name(),
2707
+						$index_name,
2708
+						implode(",", $index->field_names()),
2709
+						http_build_query($uniqueness_where_params)
2710
+					),
2711
+					__FILE__,
2712
+					__FUNCTION__,
2713
+					__LINE__
2714
+				);
2715
+				return false;
2716
+			}
2717
+		}
2718
+		return true;
2719
+	}
2720
+
2721
+
2722
+
2723
+	/**
2724
+	 * Checks the database for an item that conflicts (ie, if this item were
2725
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2726
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2727
+	 * can be either an EE_Base_Class or an array of fields n values
2728
+	 *
2729
+	 * @param EE_Base_Class|array $obj_or_fields_array
2730
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2731
+	 *                                                 when looking for conflicts
2732
+	 *                                                 (ie, if false, we ignore the model object's primary key
2733
+	 *                                                 when finding "conflicts". If true, it's also considered).
2734
+	 *                                                 Only works for INT primary key,
2735
+	 *                                                 STRING primary keys cannot be ignored
2736
+	 * @throws EE_Error
2737
+	 * @return EE_Base_Class|array
2738
+	 */
2739
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2740
+	{
2741
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2742
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2743
+		} elseif (is_array($obj_or_fields_array)) {
2744
+			$fields_n_values = $obj_or_fields_array;
2745
+		} else {
2746
+			throw new EE_Error(
2747
+				sprintf(
2748
+					__(
2749
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2750
+						"event_espresso"
2751
+					),
2752
+					get_class($this),
2753
+					$obj_or_fields_array
2754
+				)
2755
+			);
2756
+		}
2757
+		$query_params = array();
2758
+		if ($this->has_primary_key_field()
2759
+			&& ($include_primary_key
2760
+				|| $this->get_primary_key_field()
2761
+				   instanceof
2762
+				   EE_Primary_Key_String_Field)
2763
+			&& isset($fields_n_values[$this->primary_key_name()])
2764
+		) {
2765
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2766
+		}
2767
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2768
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2769
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2770
+		}
2771
+		//if there is nothing to base this search on, then we shouldn't find anything
2772
+		if (empty($query_params)) {
2773
+			return array();
2774
+		} else {
2775
+			return $this->get_one($query_params);
2776
+		}
2777
+	}
2778
+
2779
+
2780
+
2781
+	/**
2782
+	 * Like count, but is optimized and returns a boolean instead of an int
2783
+	 *
2784
+	 * @param array $query_params
2785
+	 * @return boolean
2786
+	 * @throws \EE_Error
2787
+	 */
2788
+	public function exists($query_params)
2789
+	{
2790
+		$query_params['limit'] = 1;
2791
+		return $this->count($query_params) > 0;
2792
+	}
2793
+
2794
+
2795
+
2796
+	/**
2797
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2798
+	 *
2799
+	 * @param int|string $id
2800
+	 * @return boolean
2801
+	 * @throws \EE_Error
2802
+	 */
2803
+	public function exists_by_ID($id)
2804
+	{
2805
+		return $this->exists(
2806
+			array(
2807
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2808
+				array(
2809
+					$this->primary_key_name() => $id,
2810
+				),
2811
+			)
2812
+		);
2813
+	}
2814
+
2815
+
2816
+
2817
+	/**
2818
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2819
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2820
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2821
+	 * on the main table)
2822
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2823
+	 * cases where we want to call it directly rather than via insert().
2824
+	 *
2825
+	 * @access   protected
2826
+	 * @param EE_Table_Base $table
2827
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2828
+	 *                                       float
2829
+	 * @param int           $new_id          for now we assume only int keys
2830
+	 * @throws EE_Error
2831
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2832
+	 * @return int ID of new row inserted, or FALSE on failure
2833
+	 */
2834
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2835
+	{
2836
+		global $wpdb;
2837
+		$insertion_col_n_values = array();
2838
+		$format_for_insertion = array();
2839
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2840
+		foreach ($fields_on_table as $field_name => $field_obj) {
2841
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2842
+			if ($field_obj->is_auto_increment()) {
2843
+				continue;
2844
+			}
2845
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2846
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2847
+			if ($prepared_value !== null) {
2848
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2849
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2850
+			}
2851
+		}
2852
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2853
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2854
+			//so add the fk to the main table as a column
2855
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2856
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2857
+		}
2858
+		//insert the new entry
2859
+		$result = $this->_do_wpdb_query('insert',
2860
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2861
+		if ($result === false) {
2862
+			return false;
2863
+		}
2864
+		//ok, now what do we return for the ID of the newly-inserted thing?
2865
+		if ($this->has_primary_key_field()) {
2866
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2867
+				return $wpdb->insert_id;
2868
+			} else {
2869
+				//it's not an auto-increment primary key, so
2870
+				//it must have been supplied
2871
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2872
+			}
2873
+		} else {
2874
+			//we can't return a  primary key because there is none. instead return
2875
+			//a unique string indicating this model
2876
+			return $this->get_index_primary_key_string($fields_n_values);
2877
+		}
2878
+	}
2879
+
2880
+
2881
+
2882
+	/**
2883
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2884
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2885
+	 * and there is no default, we pass it along. WPDB will take care of it)
2886
+	 *
2887
+	 * @param EE_Model_Field_Base $field_obj
2888
+	 * @param array               $fields_n_values
2889
+	 * @return mixed string|int|float depending on what the table column will be expecting
2890
+	 * @throws \EE_Error
2891
+	 */
2892
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2893
+	{
2894
+		//if this field doesn't allow nullable, don't allow it
2895
+		if (! $field_obj->is_nullable()
2896
+			&& (
2897
+				! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2898
+		) {
2899
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2900
+		}
2901
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2902
+			: null;
2903
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2904
+	}
2905
+
2906
+
2907
+
2908
+	/**
2909
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2910
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2911
+	 * the field's prepare_for_set() method.
2912
+	 *
2913
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2914
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2915
+	 *                                   top of file)
2916
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2917
+	 *                                   $value is a custom selection
2918
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2919
+	 */
2920
+	private function _prepare_value_for_use_in_db($value, $field)
2921
+	{
2922
+		if ($field && $field instanceof EE_Model_Field_Base) {
2923
+			switch ($this->_values_already_prepared_by_model_object) {
2924
+				/** @noinspection PhpMissingBreakStatementInspection */
2925
+				case self::not_prepared_by_model_object:
2926
+					$value = $field->prepare_for_set($value);
2927
+				//purposefully left out "return"
2928
+				case self::prepared_by_model_object:
2929
+					$value = $field->prepare_for_use_in_db($value);
2930
+				case self::prepared_for_use_in_db:
2931
+					//leave the value alone
2932
+			}
2933
+			return $value;
2934
+		} else {
2935
+			return $value;
2936
+		}
2937
+	}
2938
+
2939
+
2940
+
2941
+	/**
2942
+	 * Returns the main table on this model
2943
+	 *
2944
+	 * @return EE_Primary_Table
2945
+	 * @throws EE_Error
2946
+	 */
2947
+	protected function _get_main_table()
2948
+	{
2949
+		foreach ($this->_tables as $table) {
2950
+			if ($table instanceof EE_Primary_Table) {
2951
+				return $table;
2952
+			}
2953
+		}
2954
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2955
+			'event_espresso'), get_class($this)));
2956
+	}
2957
+
2958
+
2959
+
2960
+	/**
2961
+	 * table
2962
+	 * returns EE_Primary_Table table name
2963
+	 *
2964
+	 * @return string
2965
+	 * @throws \EE_Error
2966
+	 */
2967
+	public function table()
2968
+	{
2969
+		return $this->_get_main_table()->get_table_name();
2970
+	}
2971
+
2972
+
2973
+
2974
+	/**
2975
+	 * table
2976
+	 * returns first EE_Secondary_Table table name
2977
+	 *
2978
+	 * @return string
2979
+	 */
2980
+	public function second_table()
2981
+	{
2982
+		// grab second table from tables array
2983
+		$second_table = end($this->_tables);
2984
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2985
+	}
2986
+
2987
+
2988
+
2989
+	/**
2990
+	 * get_table_obj_by_alias
2991
+	 * returns table name given it's alias
2992
+	 *
2993
+	 * @param string $table_alias
2994
+	 * @return EE_Primary_Table | EE_Secondary_Table
2995
+	 */
2996
+	public function get_table_obj_by_alias($table_alias = '')
2997
+	{
2998
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
2999
+	}
3000
+
3001
+
3002
+
3003
+	/**
3004
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3005
+	 *
3006
+	 * @return EE_Secondary_Table[]
3007
+	 */
3008
+	protected function _get_other_tables()
3009
+	{
3010
+		$other_tables = array();
3011
+		foreach ($this->_tables as $table_alias => $table) {
3012
+			if ($table instanceof EE_Secondary_Table) {
3013
+				$other_tables[$table_alias] = $table;
3014
+			}
3015
+		}
3016
+		return $other_tables;
3017
+	}
3018
+
3019
+
3020
+
3021
+	/**
3022
+	 * Finds all the fields that correspond to the given table
3023
+	 *
3024
+	 * @param string $table_alias , array key in EEM_Base::_tables
3025
+	 * @return EE_Model_Field_Base[]
3026
+	 */
3027
+	public function _get_fields_for_table($table_alias)
3028
+	{
3029
+		return $this->_fields[$table_alias];
3030
+	}
3031
+
3032
+
3033
+
3034
+	/**
3035
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3036
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3037
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3038
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3039
+	 * related Registration, Transaction, and Payment models.
3040
+	 *
3041
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3042
+	 * @return EE_Model_Query_Info_Carrier
3043
+	 * @throws \EE_Error
3044
+	 */
3045
+	public function _extract_related_models_from_query($query_params)
3046
+	{
3047
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3048
+		if (array_key_exists(0, $query_params)) {
3049
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3050
+		}
3051
+		if (array_key_exists('group_by', $query_params)) {
3052
+			if (is_array($query_params['group_by'])) {
3053
+				$this->_extract_related_models_from_sub_params_array_values(
3054
+					$query_params['group_by'],
3055
+					$query_info_carrier,
3056
+					'group_by'
3057
+				);
3058
+			} elseif (! empty ($query_params['group_by'])) {
3059
+				$this->_extract_related_model_info_from_query_param(
3060
+					$query_params['group_by'],
3061
+					$query_info_carrier,
3062
+					'group_by'
3063
+				);
3064
+			}
3065
+		}
3066
+		if (array_key_exists('having', $query_params)) {
3067
+			$this->_extract_related_models_from_sub_params_array_keys(
3068
+				$query_params[0],
3069
+				$query_info_carrier,
3070
+				'having'
3071
+			);
3072
+		}
3073
+		if (array_key_exists('order_by', $query_params)) {
3074
+			if (is_array($query_params['order_by'])) {
3075
+				$this->_extract_related_models_from_sub_params_array_keys(
3076
+					$query_params['order_by'],
3077
+					$query_info_carrier,
3078
+					'order_by'
3079
+				);
3080
+			} elseif (! empty($query_params['order_by'])) {
3081
+				$this->_extract_related_model_info_from_query_param(
3082
+					$query_params['order_by'],
3083
+					$query_info_carrier,
3084
+					'order_by'
3085
+				);
3086
+			}
3087
+		}
3088
+		if (array_key_exists('force_join', $query_params)) {
3089
+			$this->_extract_related_models_from_sub_params_array_values(
3090
+				$query_params['force_join'],
3091
+				$query_info_carrier,
3092
+				'force_join'
3093
+			);
3094
+		}
3095
+		return $query_info_carrier;
3096
+	}
3097
+
3098
+
3099
+
3100
+	/**
3101
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3102
+	 *
3103
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3104
+	 *                                                      $query_params['having']
3105
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3106
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3107
+	 * @throws EE_Error
3108
+	 * @return \EE_Model_Query_Info_Carrier
3109
+	 */
3110
+	private function _extract_related_models_from_sub_params_array_keys(
3111
+		$sub_query_params,
3112
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3113
+		$query_param_type
3114
+	) {
3115
+		if (! empty($sub_query_params)) {
3116
+			$sub_query_params = (array)$sub_query_params;
3117
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3118
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3119
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3120
+					$query_param_type);
3121
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3122
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3123
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3124
+				//of array('Registration.TXN_ID'=>23)
3125
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3126
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3127
+					if (! is_array($possibly_array_of_params)) {
3128
+						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'))",
3129
+							"event_espresso"),
3130
+							$param, $possibly_array_of_params));
3131
+					} else {
3132
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3133
+							$model_query_info_carrier, $query_param_type);
3134
+					}
3135
+				} elseif ($query_param_type === 0 //ie WHERE
3136
+						  && is_array($possibly_array_of_params)
3137
+						  && isset($possibly_array_of_params[2])
3138
+						  && $possibly_array_of_params[2] == true
3139
+				) {
3140
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3141
+					//indicating that $possible_array_of_params[1] is actually a field name,
3142
+					//from which we should extract query parameters!
3143
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3144
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3145
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3146
+					}
3147
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3148
+						$model_query_info_carrier, $query_param_type);
3149
+				}
3150
+			}
3151
+		}
3152
+		return $model_query_info_carrier;
3153
+	}
3154
+
3155
+
3156
+
3157
+	/**
3158
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3159
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3160
+	 *
3161
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3162
+	 *                                                      $query_params['having']
3163
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3164
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3165
+	 * @throws EE_Error
3166
+	 * @return \EE_Model_Query_Info_Carrier
3167
+	 */
3168
+	private function _extract_related_models_from_sub_params_array_values(
3169
+		$sub_query_params,
3170
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3171
+		$query_param_type
3172
+	) {
3173
+		if (! empty($sub_query_params)) {
3174
+			if (! is_array($sub_query_params)) {
3175
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3176
+					$sub_query_params));
3177
+			}
3178
+			foreach ($sub_query_params as $param) {
3179
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3180
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3181
+					$query_param_type);
3182
+			}
3183
+		}
3184
+		return $model_query_info_carrier;
3185
+	}
3186
+
3187
+
3188
+
3189
+	/**
3190
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3191
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3192
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3193
+	 * but use them in a different order. Eg, we need to know what models we are querying
3194
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3195
+	 * other models before we can finalize the where clause SQL.
3196
+	 *
3197
+	 * @param array $query_params
3198
+	 * @throws EE_Error
3199
+	 * @return EE_Model_Query_Info_Carrier
3200
+	 */
3201
+	public function _create_model_query_info_carrier($query_params)
3202
+	{
3203
+		if (! is_array($query_params)) {
3204
+			EE_Error::doing_it_wrong(
3205
+				'EEM_Base::_create_model_query_info_carrier',
3206
+				sprintf(
3207
+					__(
3208
+						'$query_params should be an array, you passed a variable of type %s',
3209
+						'event_espresso'
3210
+					),
3211
+					gettype($query_params)
3212
+				),
3213
+				'4.6.0'
3214
+			);
3215
+			$query_params = array();
3216
+		}
3217
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3218
+		//first check if we should alter the query to account for caps or not
3219
+		//because the caps might require us to do extra joins
3220
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3221
+			$query_params[0] = $where_query_params = array_replace_recursive(
3222
+				$where_query_params,
3223
+				$this->caps_where_conditions(
3224
+					$query_params['caps']
3225
+				)
3226
+			);
3227
+		}
3228
+		$query_object = $this->_extract_related_models_from_query($query_params);
3229
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3230
+		foreach ($where_query_params as $key => $value) {
3231
+			if (is_int($key)) {
3232
+				throw new EE_Error(
3233
+					sprintf(
3234
+						__(
3235
+							"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.",
3236
+							"event_espresso"
3237
+						),
3238
+						$key,
3239
+						var_export($value, true),
3240
+						var_export($query_params, true),
3241
+						get_class($this)
3242
+					)
3243
+				);
3244
+			}
3245
+		}
3246
+		if (
3247
+			array_key_exists('default_where_conditions', $query_params)
3248
+			&& ! empty($query_params['default_where_conditions'])
3249
+		) {
3250
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3251
+		} else {
3252
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3253
+		}
3254
+		$where_query_params = array_merge(
3255
+			$this->_get_default_where_conditions_for_models_in_query(
3256
+				$query_object,
3257
+				$use_default_where_conditions,
3258
+				$where_query_params
3259
+			),
3260
+			$where_query_params
3261
+		);
3262
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3263
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3264
+		// So we need to setup a subquery and use that for the main join.
3265
+		// Note for now this only works on the primary table for the model.
3266
+		// So for instance, you could set the limit array like this:
3267
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3268
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3269
+			$query_object->set_main_model_join_sql(
3270
+				$this->_construct_limit_join_select(
3271
+					$query_params['on_join_limit'][0],
3272
+					$query_params['on_join_limit'][1]
3273
+				)
3274
+			);
3275
+		}
3276
+		//set limit
3277
+		if (array_key_exists('limit', $query_params)) {
3278
+			if (is_array($query_params['limit'])) {
3279
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3280
+					$e = sprintf(
3281
+						__(
3282
+							"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)",
3283
+							"event_espresso"
3284
+						),
3285
+						http_build_query($query_params['limit'])
3286
+					);
3287
+					throw new EE_Error($e . "|" . $e);
3288
+				}
3289
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3290
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3291
+			} elseif (! empty ($query_params['limit'])) {
3292
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3293
+			}
3294
+		}
3295
+		//set order by
3296
+		if (array_key_exists('order_by', $query_params)) {
3297
+			if (is_array($query_params['order_by'])) {
3298
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3299
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3300
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3301
+				if (array_key_exists('order', $query_params)) {
3302
+					throw new EE_Error(
3303
+						sprintf(
3304
+							__(
3305
+								"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 ",
3306
+								"event_espresso"
3307
+							),
3308
+							get_class($this),
3309
+							implode(", ", array_keys($query_params['order_by'])),
3310
+							implode(", ", $query_params['order_by']),
3311
+							$query_params['order']
3312
+						)
3313
+					);
3314
+				}
3315
+				$this->_extract_related_models_from_sub_params_array_keys(
3316
+					$query_params['order_by'],
3317
+					$query_object,
3318
+					'order_by'
3319
+				);
3320
+				//assume it's an array of fields to order by
3321
+				$order_array = array();
3322
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3323
+					$order = $this->_extract_order($order);
3324
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3325
+				}
3326
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3327
+			} elseif (! empty ($query_params['order_by'])) {
3328
+				$this->_extract_related_model_info_from_query_param(
3329
+					$query_params['order_by'],
3330
+					$query_object,
3331
+					'order',
3332
+					$query_params['order_by']
3333
+				);
3334
+				$order = isset($query_params['order'])
3335
+					? $this->_extract_order($query_params['order'])
3336
+					: 'DESC';
3337
+				$query_object->set_order_by_sql(
3338
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3339
+				);
3340
+			}
3341
+		}
3342
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3343
+		if (! array_key_exists('order_by', $query_params)
3344
+			&& array_key_exists('order', $query_params)
3345
+			&& ! empty($query_params['order'])
3346
+		) {
3347
+			$pk_field = $this->get_primary_key_field();
3348
+			$order = $this->_extract_order($query_params['order']);
3349
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3350
+		}
3351
+		//set group by
3352
+		if (array_key_exists('group_by', $query_params)) {
3353
+			if (is_array($query_params['group_by'])) {
3354
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3355
+				$group_by_array = array();
3356
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3357
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3358
+				}
3359
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3360
+			} elseif (! empty ($query_params['group_by'])) {
3361
+				$query_object->set_group_by_sql(
3362
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3363
+				);
3364
+			}
3365
+		}
3366
+		//set having
3367
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3368
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3369
+		}
3370
+		//now, just verify they didn't pass anything wack
3371
+		foreach ($query_params as $query_key => $query_value) {
3372
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3373
+				throw new EE_Error(
3374
+					sprintf(
3375
+						__(
3376
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3377
+							'event_espresso'
3378
+						),
3379
+						$query_key,
3380
+						get_class($this),
3381
+						//						print_r( $this->_allowed_query_params, TRUE )
3382
+						implode(',', $this->_allowed_query_params)
3383
+					)
3384
+				);
3385
+			}
3386
+		}
3387
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3388
+		if (empty($main_model_join_sql)) {
3389
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3390
+		}
3391
+		return $query_object;
3392
+	}
3393
+
3394
+
3395
+
3396
+	/**
3397
+	 * Gets the where conditions that should be imposed on the query based on the
3398
+	 * context (eg reading frontend, backend, edit or delete).
3399
+	 *
3400
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3401
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3402
+	 * @throws \EE_Error
3403
+	 */
3404
+	public function caps_where_conditions($context = self::caps_read)
3405
+	{
3406
+		EEM_Base::verify_is_valid_cap_context($context);
3407
+		$cap_where_conditions = array();
3408
+		$cap_restrictions = $this->caps_missing($context);
3409
+		/**
3410
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3411
+		 */
3412
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3413
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3414
+				$restriction_if_no_cap->get_default_where_conditions());
3415
+		}
3416
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3417
+			$cap_restrictions);
3418
+	}
3419
+
3420
+
3421
+
3422
+	/**
3423
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3424
+	 * otherwise throws an exception
3425
+	 *
3426
+	 * @param string $should_be_order_string
3427
+	 * @return string either ASC, asc, DESC or desc
3428
+	 * @throws EE_Error
3429
+	 */
3430
+	private function _extract_order($should_be_order_string)
3431
+	{
3432
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3433
+			return $should_be_order_string;
3434
+		} else {
3435
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3436
+				"event_espresso"), get_class($this), $should_be_order_string));
3437
+		}
3438
+	}
3439
+
3440
+
3441
+
3442
+	/**
3443
+	 * Looks at all the models which are included in this query, and asks each
3444
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3445
+	 * so they can be merged
3446
+	 *
3447
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3448
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3449
+	 *                                                                  'none' means NO default where conditions will
3450
+	 *                                                                  be used AT ALL during this query.
3451
+	 *                                                                  'other_models_only' means default where
3452
+	 *                                                                  conditions from other models will be used, but
3453
+	 *                                                                  not for this primary model. 'all', the default,
3454
+	 *                                                                  means default where conditions will apply as
3455
+	 *                                                                  normal
3456
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3457
+	 * @throws EE_Error
3458
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3459
+	 */
3460
+	private function _get_default_where_conditions_for_models_in_query(
3461
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3462
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3463
+		$where_query_params = array()
3464
+	) {
3465
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3466
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3467
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3468
+				"event_espresso"), $use_default_where_conditions,
3469
+				implode(", ", $allowed_used_default_where_conditions_values)));
3470
+		}
3471
+		$universal_query_params = array();
3472
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3473
+			$universal_query_params = $this->_get_default_where_conditions();
3474
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3475
+			$universal_query_params = $this->_get_minimum_where_conditions();
3476
+		}
3477
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3478
+			$related_model = $this->get_related_model_obj($model_name);
3479
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3480
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3481
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3482
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3483
+			} else {
3484
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3485
+				continue;
3486
+			}
3487
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3488
+				$related_model_universal_where_params,
3489
+				$where_query_params,
3490
+				$related_model,
3491
+				$model_relation_path
3492
+			);
3493
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3494
+				$universal_query_params,
3495
+				$overrides
3496
+			);
3497
+		}
3498
+		return $universal_query_params;
3499
+	}
3500
+
3501
+
3502
+
3503
+	/**
3504
+	 * Determines whether or not we should use default where conditions for the model in question
3505
+	 * (this model, or other related models).
3506
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3507
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3508
+	 * We should use default where conditions on related models when they requested to use default where conditions
3509
+	 * on all models, or specifically just on other related models
3510
+	 * @param      $default_where_conditions_value
3511
+	 * @param bool $for_this_model false means this is for OTHER related models
3512
+	 * @return bool
3513
+	 */
3514
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3515
+	{
3516
+		return (
3517
+				   $for_this_model
3518
+				   && in_array(
3519
+					   $default_where_conditions_value,
3520
+					   array(
3521
+						   EEM_Base::default_where_conditions_all,
3522
+						   EEM_Base::default_where_conditions_this_only,
3523
+						   EEM_Base::default_where_conditions_minimum_others,
3524
+					   ),
3525
+					   true
3526
+				   )
3527
+			   )
3528
+			   || (
3529
+				   ! $for_this_model
3530
+				   && in_array(
3531
+					   $default_where_conditions_value,
3532
+					   array(
3533
+						   EEM_Base::default_where_conditions_all,
3534
+						   EEM_Base::default_where_conditions_others_only,
3535
+					   ),
3536
+					   true
3537
+				   )
3538
+			   );
3539
+	}
3540
+
3541
+	/**
3542
+	 * Determines whether or not we should use default minimum conditions for the model in question
3543
+	 * (this model, or other related models).
3544
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3545
+	 * where conditions.
3546
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3547
+	 * on this model or others
3548
+	 * @param      $default_where_conditions_value
3549
+	 * @param bool $for_this_model false means this is for OTHER related models
3550
+	 * @return bool
3551
+	 */
3552
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3553
+	{
3554
+		return (
3555
+				   $for_this_model
3556
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3557
+			   )
3558
+			   || (
3559
+				   ! $for_this_model
3560
+				   && in_array(
3561
+					   $default_where_conditions_value,
3562
+					   array(
3563
+						   EEM_Base::default_where_conditions_minimum_others,
3564
+						   EEM_Base::default_where_conditions_minimum_all,
3565
+					   ),
3566
+					   true
3567
+				   )
3568
+			   );
3569
+	}
3570
+
3571
+
3572
+	/**
3573
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3574
+	 * then we also add a special where condition which allows for that model's primary key
3575
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3576
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3577
+	 *
3578
+	 * @param array    $default_where_conditions
3579
+	 * @param array    $provided_where_conditions
3580
+	 * @param EEM_Base $model
3581
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3582
+	 * @return array like EEM_Base::get_all's $query_params[0]
3583
+	 * @throws \EE_Error
3584
+	 */
3585
+	private function _override_defaults_or_make_null_friendly(
3586
+		$default_where_conditions,
3587
+		$provided_where_conditions,
3588
+		$model,
3589
+		$model_relation_path
3590
+	) {
3591
+		$null_friendly_where_conditions = array();
3592
+		$none_overridden = true;
3593
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3594
+		foreach ($default_where_conditions as $key => $val) {
3595
+			if (isset($provided_where_conditions[$key])) {
3596
+				$none_overridden = false;
3597
+			} else {
3598
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3599
+			}
3600
+		}
3601
+		if ($none_overridden && $default_where_conditions) {
3602
+			if ($model->has_primary_key_field()) {
3603
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3604
+																				. "."
3605
+																				. $model->primary_key_name()] = array('IS NULL');
3606
+			}/*else{
3607 3607
 				//@todo NO PK, use other defaults
3608 3608
 			}*/
3609
-        }
3610
-        return $null_friendly_where_conditions;
3611
-    }
3612
-
3613
-
3614
-
3615
-    /**
3616
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3617
-     * default where conditions on all get_all, update, and delete queries done by this model.
3618
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3619
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3620
-     *
3621
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3622
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3623
-     */
3624
-    private function _get_default_where_conditions($model_relation_path = null)
3625
-    {
3626
-        if ($this->_ignore_where_strategy) {
3627
-            return array();
3628
-        }
3629
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3630
-    }
3631
-
3632
-
3633
-
3634
-    /**
3635
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3636
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3637
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3638
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3639
-     * Similar to _get_default_where_conditions
3640
-     *
3641
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3642
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3643
-     */
3644
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3645
-    {
3646
-        if ($this->_ignore_where_strategy) {
3647
-            return array();
3648
-        }
3649
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3650
-    }
3651
-
3652
-
3653
-
3654
-    /**
3655
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3656
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3657
-     *
3658
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3659
-     * @return string
3660
-     * @throws \EE_Error
3661
-     */
3662
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3663
-    {
3664
-        $selects = $this->_get_columns_to_select_for_this_model();
3665
-        foreach (
3666
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3667
-            $name_of_other_model_included
3668
-        ) {
3669
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3670
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3671
-            foreach ($other_model_selects as $key => $value) {
3672
-                $selects[] = $value;
3673
-            }
3674
-        }
3675
-        return implode(", ", $selects);
3676
-    }
3677
-
3678
-
3679
-
3680
-    /**
3681
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3682
-     * So that's going to be the columns for all the fields on the model
3683
-     *
3684
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3685
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3686
-     */
3687
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3688
-    {
3689
-        $fields = $this->field_settings();
3690
-        $selects = array();
3691
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3692
-            $this->get_this_model_name());
3693
-        foreach ($fields as $field_obj) {
3694
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3695
-                         . $field_obj->get_table_alias()
3696
-                         . "."
3697
-                         . $field_obj->get_table_column()
3698
-                         . " AS '"
3699
-                         . $table_alias_with_model_relation_chain_prefix
3700
-                         . $field_obj->get_table_alias()
3701
-                         . "."
3702
-                         . $field_obj->get_table_column()
3703
-                         . "'";
3704
-        }
3705
-        //make sure we are also getting the PKs of each table
3706
-        $tables = $this->get_tables();
3707
-        if (count($tables) > 1) {
3708
-            foreach ($tables as $table_obj) {
3709
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3710
-                                       . $table_obj->get_fully_qualified_pk_column();
3711
-                if (! in_array($qualified_pk_column, $selects)) {
3712
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3713
-                }
3714
-            }
3715
-        }
3716
-        return $selects;
3717
-    }
3718
-
3719
-
3720
-
3721
-    /**
3722
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3723
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3724
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3725
-     * SQL for joining, and the data types
3726
-     *
3727
-     * @param null|string                 $original_query_param
3728
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3729
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3730
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3731
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3732
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3733
-     *                                                          or 'Registration's
3734
-     * @param string                      $original_query_param what it originally was (eg
3735
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3736
-     *                                                          matches $query_param
3737
-     * @throws EE_Error
3738
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3739
-     */
3740
-    private function _extract_related_model_info_from_query_param(
3741
-        $query_param,
3742
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3743
-        $query_param_type,
3744
-        $original_query_param = null
3745
-    ) {
3746
-        if ($original_query_param === null) {
3747
-            $original_query_param = $query_param;
3748
-        }
3749
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3750
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3751
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3752
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3753
-        //check to see if we have a field on this model
3754
-        $this_model_fields = $this->field_settings(true);
3755
-        if (array_key_exists($query_param, $this_model_fields)) {
3756
-            if ($allow_fields) {
3757
-                return;
3758
-            } else {
3759
-                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",
3760
-                    "event_espresso"),
3761
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3762
-            }
3763
-        } //check if this is a special logic query param
3764
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3765
-            if ($allow_logic_query_params) {
3766
-                return;
3767
-            } else {
3768
-                throw new EE_Error(
3769
-                    sprintf(
3770
-                        __('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',
3771
-                            'event_espresso'),
3772
-                        implode('", "', $this->_logic_query_param_keys),
3773
-                        $query_param,
3774
-                        get_class($this),
3775
-                        '<br />',
3776
-                        "\t"
3777
-                        . ' $passed_in_query_info = <pre>'
3778
-                        . print_r($passed_in_query_info, true)
3779
-                        . '</pre>'
3780
-                        . "\n\t"
3781
-                        . ' $query_param_type = '
3782
-                        . $query_param_type
3783
-                        . "\n\t"
3784
-                        . ' $original_query_param = '
3785
-                        . $original_query_param
3786
-                    )
3787
-                );
3788
-            }
3789
-        } //check if it's a custom selection
3790
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3791
-            return;
3792
-        }
3793
-        //check if has a model name at the beginning
3794
-        //and
3795
-        //check if it's a field on a related model
3796
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3797
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3798
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3799
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3800
-                if ($query_param === '') {
3801
-                    //nothing left to $query_param
3802
-                    //we should actually end in a field name, not a model like this!
3803
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3804
-                        "event_espresso"),
3805
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3806
-                } else {
3807
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3808
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3809
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3810
-                    return;
3811
-                }
3812
-            } elseif ($query_param === $valid_related_model_name) {
3813
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3814
-                return;
3815
-            }
3816
-        }
3817
-        //ok so $query_param didn't start with a model name
3818
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3819
-        //it's wack, that's what it is
3820
-        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",
3821
-            "event_espresso"),
3822
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3823
-    }
3824
-
3825
-
3826
-
3827
-    /**
3828
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3829
-     * and store it on $passed_in_query_info
3830
-     *
3831
-     * @param string                      $model_name
3832
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3833
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3834
-     *                                                          model and $model_name. Eg, if we are querying Event,
3835
-     *                                                          and are adding a join to 'Payment' with the original
3836
-     *                                                          query param key
3837
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3838
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3839
-     *                                                          Payment wants to add default query params so that it
3840
-     *                                                          will know what models to prepend onto its default query
3841
-     *                                                          params or in case it wants to rename tables (in case
3842
-     *                                                          there are multiple joins to the same table)
3843
-     * @return void
3844
-     * @throws \EE_Error
3845
-     */
3846
-    private function _add_join_to_model(
3847
-        $model_name,
3848
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3849
-        $original_query_param
3850
-    ) {
3851
-        $relation_obj = $this->related_settings_for($model_name);
3852
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3853
-        //check if the relation is HABTM, because then we're essentially doing two joins
3854
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3855
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3856
-            $join_model_obj = $relation_obj->get_join_model();
3857
-            //replace the model specified with the join model for this relation chain, whi
3858
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3859
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3860
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3861
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3862
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3863
-            $passed_in_query_info->merge($new_query_info);
3864
-        }
3865
-        //now just join to the other table pointed to by the relation object, and add its data types
3866
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3867
-            array($model_relation_chain => $model_name),
3868
-            $relation_obj->get_join_statement($model_relation_chain));
3869
-        $passed_in_query_info->merge($new_query_info);
3870
-    }
3871
-
3872
-
3873
-
3874
-    /**
3875
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3876
-     *
3877
-     * @param array $where_params like EEM_Base::get_all
3878
-     * @return string of SQL
3879
-     * @throws \EE_Error
3880
-     */
3881
-    private function _construct_where_clause($where_params)
3882
-    {
3883
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3884
-        if ($SQL) {
3885
-            return " WHERE " . $SQL;
3886
-        } else {
3887
-            return '';
3888
-        }
3889
-    }
3890
-
3891
-
3892
-
3893
-    /**
3894
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3895
-     * and should be passed HAVING parameters, not WHERE parameters
3896
-     *
3897
-     * @param array $having_params
3898
-     * @return string
3899
-     * @throws \EE_Error
3900
-     */
3901
-    private function _construct_having_clause($having_params)
3902
-    {
3903
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3904
-        if ($SQL) {
3905
-            return " HAVING " . $SQL;
3906
-        } else {
3907
-            return '';
3908
-        }
3909
-    }
3910
-
3911
-
3912
-
3913
-    /**
3914
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3915
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3916
-     * EEM_Attendee.
3917
-     *
3918
-     * @param string $field_name
3919
-     * @param string $model_name
3920
-     * @return EE_Model_Field_Base
3921
-     * @throws EE_Error
3922
-     */
3923
-    protected function _get_field_on_model($field_name, $model_name)
3924
-    {
3925
-        $model_class = 'EEM_' . $model_name;
3926
-        $model_filepath = $model_class . ".model.php";
3927
-        if (is_readable($model_filepath)) {
3928
-            require_once($model_filepath);
3929
-            $model_instance = call_user_func($model_name . "::instance");
3930
-            /* @var $model_instance EEM_Base */
3931
-            return $model_instance->field_settings_for($field_name);
3932
-        } else {
3933
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3934
-                'event_espresso'), $model_name, $model_class, $model_filepath));
3935
-        }
3936
-    }
3937
-
3938
-
3939
-
3940
-    /**
3941
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3942
-     * Event_Meta.meta_value = 'foo'))"
3943
-     *
3944
-     * @param array  $where_params see EEM_Base::get_all for documentation
3945
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3946
-     * @throws EE_Error
3947
-     * @return string of SQL
3948
-     */
3949
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3950
-    {
3951
-        $where_clauses = array();
3952
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3953
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3954
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3955
-                switch ($query_param) {
3956
-                    case 'not':
3957
-                    case 'NOT':
3958
-                        $where_clauses[] = "! ("
3959
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3960
-                                $glue)
3961
-                                           . ")";
3962
-                        break;
3963
-                    case 'and':
3964
-                    case 'AND':
3965
-                        $where_clauses[] = " ("
3966
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3967
-                                ' AND ')
3968
-                                           . ")";
3969
-                        break;
3970
-                    case 'or':
3971
-                    case 'OR':
3972
-                        $where_clauses[] = " ("
3973
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3974
-                                ' OR ')
3975
-                                           . ")";
3976
-                        break;
3977
-                }
3978
-            } else {
3979
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3980
-                //if it's not a normal field, maybe it's a custom selection?
3981
-                if (! $field_obj) {
3982
-                    if (isset($this->_custom_selections[$query_param][1])) {
3983
-                        $field_obj = $this->_custom_selections[$query_param][1];
3984
-                    } else {
3985
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3986
-                            "event_espresso"), $query_param));
3987
-                    }
3988
-                }
3989
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3990
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3991
-            }
3992
-        }
3993
-        return $where_clauses ? implode($glue, $where_clauses) : '';
3994
-    }
3995
-
3996
-
3997
-
3998
-    /**
3999
-     * Takes the input parameter and extract the table name (alias) and column name
4000
-     *
4001
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4002
-     * @throws EE_Error
4003
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4004
-     */
4005
-    private function _deduce_column_name_from_query_param($query_param)
4006
-    {
4007
-        $field = $this->_deduce_field_from_query_param($query_param);
4008
-        if ($field) {
4009
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4010
-                $query_param);
4011
-            return $table_alias_prefix . $field->get_qualified_column();
4012
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4013
-            //maybe it's custom selection item?
4014
-            //if so, just use it as the "column name"
4015
-            return $query_param;
4016
-        } else {
4017
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4018
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4019
-        }
4020
-    }
4021
-
4022
-
4023
-
4024
-    /**
4025
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4026
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4027
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4028
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4029
-     *
4030
-     * @param string $condition_query_param_key
4031
-     * @return string
4032
-     */
4033
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4034
-    {
4035
-        $pos_of_star = strpos($condition_query_param_key, '*');
4036
-        if ($pos_of_star === false) {
4037
-            return $condition_query_param_key;
4038
-        } else {
4039
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4040
-            return $condition_query_param_sans_star;
4041
-        }
4042
-    }
4043
-
4044
-
4045
-
4046
-    /**
4047
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4048
-     *
4049
-     * @param                            mixed      array | string    $op_and_value
4050
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4051
-     * @throws EE_Error
4052
-     * @return string
4053
-     */
4054
-    private function _construct_op_and_value($op_and_value, $field_obj)
4055
-    {
4056
-        if (is_array($op_and_value)) {
4057
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4058
-            if (! $operator) {
4059
-                $php_array_like_string = array();
4060
-                foreach ($op_and_value as $key => $value) {
4061
-                    $php_array_like_string[] = "$key=>$value";
4062
-                }
4063
-                throw new EE_Error(
4064
-                    sprintf(
4065
-                        __(
4066
-                            "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))",
4067
-                            "event_espresso"
4068
-                        ),
4069
-                        implode(",", $php_array_like_string)
4070
-                    )
4071
-                );
4072
-            }
4073
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4074
-        } else {
4075
-            $operator = '=';
4076
-            $value = $op_and_value;
4077
-        }
4078
-        //check to see if the value is actually another field
4079
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4080
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4081
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4082
-            //in this case, the value should be an array, or at least a comma-separated list
4083
-            //it will need to handle a little differently
4084
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4085
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4086
-            return $operator . SP . $cleaned_value;
4087
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4088
-            //the value should be an array with count of two.
4089
-            if (count($value) !== 2) {
4090
-                throw new EE_Error(
4091
-                    sprintf(
4092
-                        __(
4093
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4094
-                            'event_espresso'
4095
-                        ),
4096
-                        "BETWEEN"
4097
-                    )
4098
-                );
4099
-            }
4100
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4101
-            return $operator . SP . $cleaned_value;
4102
-        } elseif (in_array($operator, $this->_null_style_operators)) {
4103
-            if ($value !== null) {
4104
-                throw new EE_Error(
4105
-                    sprintf(
4106
-                        __(
4107
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4108
-                            "event_espresso"
4109
-                        ),
4110
-                        $value,
4111
-                        $operator
4112
-                    )
4113
-                );
4114
-            }
4115
-            return $operator;
4116
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
4117
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4118
-            //remove other junk. So just treat it as a string.
4119
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4120
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4121
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4122
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4123
-            throw new EE_Error(
4124
-                sprintf(
4125
-                    __(
4126
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4127
-                        'event_espresso'
4128
-                    ),
4129
-                    $operator,
4130
-                    $operator
4131
-                )
4132
-            );
4133
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4134
-            throw new EE_Error(
4135
-                sprintf(
4136
-                    __(
4137
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4138
-                        'event_espresso'
4139
-                    ),
4140
-                    $operator,
4141
-                    $operator
4142
-                )
4143
-            );
4144
-        } else {
4145
-            throw new EE_Error(
4146
-                sprintf(
4147
-                    __(
4148
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4149
-                        "event_espresso"
4150
-                    ),
4151
-                    http_build_query($op_and_value)
4152
-                )
4153
-            );
4154
-        }
4155
-    }
4156
-
4157
-
4158
-
4159
-    /**
4160
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4161
-     *
4162
-     * @param array                      $values
4163
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4164
-     *                                              '%s'
4165
-     * @return string
4166
-     * @throws \EE_Error
4167
-     */
4168
-    public function _construct_between_value($values, $field_obj)
4169
-    {
4170
-        $cleaned_values = array();
4171
-        foreach ($values as $value) {
4172
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4173
-        }
4174
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4175
-    }
4176
-
4177
-
4178
-
4179
-    /**
4180
-     * Takes an array or a comma-separated list of $values and cleans them
4181
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4182
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4183
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4184
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4185
-     *
4186
-     * @param mixed                      $values    array or comma-separated string
4187
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4188
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4189
-     * @throws \EE_Error
4190
-     */
4191
-    public function _construct_in_value($values, $field_obj)
4192
-    {
4193
-        //check if the value is a CSV list
4194
-        if (is_string($values)) {
4195
-            //in which case, turn it into an array
4196
-            $values = explode(",", $values);
4197
-        }
4198
-        $cleaned_values = array();
4199
-        foreach ($values as $value) {
4200
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4201
-        }
4202
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4203
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4204
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4205
-        if (empty($cleaned_values)) {
4206
-            $all_fields = $this->field_settings();
4207
-            $a_field = array_shift($all_fields);
4208
-            $main_table = $this->_get_main_table();
4209
-            $cleaned_values[] = "SELECT "
4210
-                                . $a_field->get_table_column()
4211
-                                . " FROM "
4212
-                                . $main_table->get_table_name()
4213
-                                . " WHERE FALSE";
4214
-        }
4215
-        return "(" . implode(",", $cleaned_values) . ")";
4216
-    }
4217
-
4218
-
4219
-
4220
-    /**
4221
-     * @param mixed                      $value
4222
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4223
-     * @throws EE_Error
4224
-     * @return false|null|string
4225
-     */
4226
-    private function _wpdb_prepare_using_field($value, $field_obj)
4227
-    {
4228
-        /** @type WPDB $wpdb */
4229
-        global $wpdb;
4230
-        if ($field_obj instanceof EE_Model_Field_Base) {
4231
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4232
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4233
-        } else {//$field_obj should really just be a data type
4234
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4235
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4236
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4237
-            }
4238
-            return $wpdb->prepare($field_obj, $value);
4239
-        }
4240
-    }
4241
-
4242
-
4243
-
4244
-    /**
4245
-     * Takes the input parameter and finds the model field that it indicates.
4246
-     *
4247
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4248
-     * @throws EE_Error
4249
-     * @return EE_Model_Field_Base
4250
-     */
4251
-    protected function _deduce_field_from_query_param($query_param_name)
4252
-    {
4253
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4254
-        //which will help us find the database table and column
4255
-        $query_param_parts = explode(".", $query_param_name);
4256
-        if (empty($query_param_parts)) {
4257
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4258
-                'event_espresso'), $query_param_name));
4259
-        }
4260
-        $number_of_parts = count($query_param_parts);
4261
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4262
-        if ($number_of_parts === 1) {
4263
-            $field_name = $last_query_param_part;
4264
-            $model_obj = $this;
4265
-        } else {// $number_of_parts >= 2
4266
-            //the last part is the column name, and there are only 2parts. therefore...
4267
-            $field_name = $last_query_param_part;
4268
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4269
-        }
4270
-        try {
4271
-            return $model_obj->field_settings_for($field_name);
4272
-        } catch (EE_Error $e) {
4273
-            return null;
4274
-        }
4275
-    }
4276
-
4277
-
4278
-
4279
-    /**
4280
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4281
-     * alias and column which corresponds to it
4282
-     *
4283
-     * @param string $field_name
4284
-     * @throws EE_Error
4285
-     * @return string
4286
-     */
4287
-    public function _get_qualified_column_for_field($field_name)
4288
-    {
4289
-        $all_fields = $this->field_settings();
4290
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4291
-        if ($field) {
4292
-            return $field->get_qualified_column();
4293
-        } else {
4294
-            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.",
4295
-                'event_espresso'), $field_name, get_class($this)));
4296
-        }
4297
-    }
4298
-
4299
-
4300
-
4301
-    /**
4302
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4303
-     * Example usage:
4304
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4305
-     *      array(),
4306
-     *      ARRAY_A,
4307
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4308
-     *  );
4309
-     * is equivalent to
4310
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4311
-     * and
4312
-     *  EEM_Event::instance()->get_all_wpdb_results(
4313
-     *      array(
4314
-     *          array(
4315
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4316
-     *          ),
4317
-     *          ARRAY_A,
4318
-     *          implode(
4319
-     *              ', ',
4320
-     *              array_merge(
4321
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4322
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4323
-     *              )
4324
-     *          )
4325
-     *      )
4326
-     *  );
4327
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4328
-     *
4329
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4330
-     *                                            and the one whose fields you are selecting for example: when querying
4331
-     *                                            tickets model and selecting fields from the tickets model you would
4332
-     *                                            leave this parameter empty, because no models are needed to join
4333
-     *                                            between the queried model and the selected one. Likewise when
4334
-     *                                            querying the datetime model and selecting fields from the tickets
4335
-     *                                            model, it would also be left empty, because there is a direct
4336
-     *                                            relation from datetimes to tickets, so no model is needed to join
4337
-     *                                            them together. However, when querying from the event model and
4338
-     *                                            selecting fields from the ticket model, you should provide the string
4339
-     *                                            'Datetime', indicating that the event model must first join to the
4340
-     *                                            datetime model in order to find its relation to ticket model.
4341
-     *                                            Also, when querying from the venue model and selecting fields from
4342
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4343
-     *                                            indicating you need to join the venue model to the event model,
4344
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4345
-     *                                            This string is used to deduce the prefix that gets added onto the
4346
-     *                                            models' tables qualified columns
4347
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4348
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4349
-     *                                            qualified column names
4350
-     * @return array|string
4351
-     */
4352
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4353
-    {
4354
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4355
-        $qualified_columns = array();
4356
-        foreach ($this->field_settings() as $field_name => $field) {
4357
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4358
-        }
4359
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4360
-    }
4361
-
4362
-
4363
-
4364
-    /**
4365
-     * constructs the select use on special limit joins
4366
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4367
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4368
-     * (as that is typically where the limits would be set).
4369
-     *
4370
-     * @param  string       $table_alias The table the select is being built for
4371
-     * @param  mixed|string $limit       The limit for this select
4372
-     * @return string                The final select join element for the query.
4373
-     */
4374
-    public function _construct_limit_join_select($table_alias, $limit)
4375
-    {
4376
-        $SQL = '';
4377
-        foreach ($this->_tables as $table_obj) {
4378
-            if ($table_obj instanceof EE_Primary_Table) {
4379
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4380
-                    ? $table_obj->get_select_join_limit($limit)
4381
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4382
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4383
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4384
-                    ? $table_obj->get_select_join_limit_join($limit)
4385
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4386
-            }
4387
-        }
4388
-        return $SQL;
4389
-    }
4390
-
4391
-
4392
-
4393
-    /**
4394
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4395
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4396
-     *
4397
-     * @return string SQL
4398
-     * @throws \EE_Error
4399
-     */
4400
-    public function _construct_internal_join()
4401
-    {
4402
-        $SQL = $this->_get_main_table()->get_table_sql();
4403
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4404
-        return $SQL;
4405
-    }
4406
-
4407
-
4408
-
4409
-    /**
4410
-     * Constructs the SQL for joining all the tables on this model.
4411
-     * Normally $alias should be the primary table's alias, but in cases where
4412
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4413
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4414
-     * alias, this will construct SQL like:
4415
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4416
-     * With $alias being a secondary table's alias, this will construct SQL like:
4417
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4418
-     *
4419
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4420
-     * @return string
4421
-     */
4422
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4423
-    {
4424
-        $SQL = '';
4425
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4426
-        foreach ($this->_tables as $table_obj) {
4427
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4428
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4429
-                    //so we're joining to this table, meaning the table is already in
4430
-                    //the FROM statement, BUT the primary table isn't. So we want
4431
-                    //to add the inverse join sql
4432
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4433
-                } else {
4434
-                    //just add a regular JOIN to this table from the primary table
4435
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4436
-                }
4437
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4438
-        }
4439
-        return $SQL;
4440
-    }
4441
-
4442
-
4443
-
4444
-    /**
4445
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4446
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4447
-     * their data type (eg, '%s', '%d', etc)
4448
-     *
4449
-     * @return array
4450
-     */
4451
-    public function _get_data_types()
4452
-    {
4453
-        $data_types = array();
4454
-        foreach ($this->field_settings() as $field_obj) {
4455
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4456
-            /** @var $field_obj EE_Model_Field_Base */
4457
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4458
-        }
4459
-        return $data_types;
4460
-    }
4461
-
4462
-
4463
-
4464
-    /**
4465
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4466
-     *
4467
-     * @param string $model_name
4468
-     * @throws EE_Error
4469
-     * @return EEM_Base
4470
-     */
4471
-    public function get_related_model_obj($model_name)
4472
-    {
4473
-        $model_classname = "EEM_" . $model_name;
4474
-        if (! class_exists($model_classname)) {
4475
-            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",
4476
-                'event_espresso'), $model_name, $model_classname));
4477
-        }
4478
-        return call_user_func($model_classname . "::instance");
4479
-    }
4480
-
4481
-
4482
-
4483
-    /**
4484
-     * Returns the array of EE_ModelRelations for this model.
4485
-     *
4486
-     * @return EE_Model_Relation_Base[]
4487
-     */
4488
-    public function relation_settings()
4489
-    {
4490
-        return $this->_model_relations;
4491
-    }
4492
-
4493
-
4494
-
4495
-    /**
4496
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4497
-     * because without THOSE models, this model probably doesn't have much purpose.
4498
-     * (Eg, without an event, datetimes have little purpose.)
4499
-     *
4500
-     * @return EE_Belongs_To_Relation[]
4501
-     */
4502
-    public function belongs_to_relations()
4503
-    {
4504
-        $belongs_to_relations = array();
4505
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4506
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4507
-                $belongs_to_relations[$model_name] = $relation_obj;
4508
-            }
4509
-        }
4510
-        return $belongs_to_relations;
4511
-    }
4512
-
4513
-
4514
-
4515
-    /**
4516
-     * Returns the specified EE_Model_Relation, or throws an exception
4517
-     *
4518
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4519
-     * @throws EE_Error
4520
-     * @return EE_Model_Relation_Base
4521
-     */
4522
-    public function related_settings_for($relation_name)
4523
-    {
4524
-        $relatedModels = $this->relation_settings();
4525
-        if (! array_key_exists($relation_name, $relatedModels)) {
4526
-            throw new EE_Error(
4527
-                sprintf(
4528
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4529
-                        'event_espresso'),
4530
-                    $relation_name,
4531
-                    $this->_get_class_name(),
4532
-                    implode(', ', array_keys($relatedModels))
4533
-                )
4534
-            );
4535
-        }
4536
-        return $relatedModels[$relation_name];
4537
-    }
4538
-
4539
-
4540
-
4541
-    /**
4542
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4543
-     * fields
4544
-     *
4545
-     * @param string $fieldName
4546
-     * @throws EE_Error
4547
-     * @return EE_Model_Field_Base
4548
-     */
4549
-    public function field_settings_for($fieldName)
4550
-    {
4551
-        $fieldSettings = $this->field_settings(true);
4552
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4553
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4554
-                get_class($this)));
4555
-        }
4556
-        return $fieldSettings[$fieldName];
4557
-    }
4558
-
4559
-
4560
-
4561
-    /**
4562
-     * Checks if this field exists on this model
4563
-     *
4564
-     * @param string $fieldName a key in the model's _field_settings array
4565
-     * @return boolean
4566
-     */
4567
-    public function has_field($fieldName)
4568
-    {
4569
-        $fieldSettings = $this->field_settings(true);
4570
-        if (isset($fieldSettings[$fieldName])) {
4571
-            return true;
4572
-        } else {
4573
-            return false;
4574
-        }
4575
-    }
4576
-
4577
-
4578
-
4579
-    /**
4580
-     * Returns whether or not this model has a relation to the specified model
4581
-     *
4582
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4583
-     * @return boolean
4584
-     */
4585
-    public function has_relation($relation_name)
4586
-    {
4587
-        $relations = $this->relation_settings();
4588
-        if (isset($relations[$relation_name])) {
4589
-            return true;
4590
-        } else {
4591
-            return false;
4592
-        }
4593
-    }
4594
-
4595
-
4596
-
4597
-    /**
4598
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4599
-     * Eg, on EE_Answer that would be ANS_ID field object
4600
-     *
4601
-     * @param $field_obj
4602
-     * @return boolean
4603
-     */
4604
-    public function is_primary_key_field($field_obj)
4605
-    {
4606
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4607
-    }
4608
-
4609
-
4610
-
4611
-    /**
4612
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4613
-     * Eg, on EE_Answer that would be ANS_ID field object
4614
-     *
4615
-     * @return EE_Model_Field_Base
4616
-     * @throws EE_Error
4617
-     */
4618
-    public function get_primary_key_field()
4619
-    {
4620
-        if ($this->_primary_key_field === null) {
4621
-            foreach ($this->field_settings(true) as $field_obj) {
4622
-                if ($this->is_primary_key_field($field_obj)) {
4623
-                    $this->_primary_key_field = $field_obj;
4624
-                    break;
4625
-                }
4626
-            }
4627
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4628
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4629
-                    get_class($this)));
4630
-            }
4631
-        }
4632
-        return $this->_primary_key_field;
4633
-    }
4634
-
4635
-
4636
-
4637
-    /**
4638
-     * Returns whether or not not there is a primary key on this model.
4639
-     * Internally does some caching.
4640
-     *
4641
-     * @return boolean
4642
-     */
4643
-    public function has_primary_key_field()
4644
-    {
4645
-        if ($this->_has_primary_key_field === null) {
4646
-            try {
4647
-                $this->get_primary_key_field();
4648
-                $this->_has_primary_key_field = true;
4649
-            } catch (EE_Error $e) {
4650
-                $this->_has_primary_key_field = false;
4651
-            }
4652
-        }
4653
-        return $this->_has_primary_key_field;
4654
-    }
4655
-
4656
-
4657
-
4658
-    /**
4659
-     * Finds the first field of type $field_class_name.
4660
-     *
4661
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4662
-     *                                 EE_Foreign_Key_Field, etc
4663
-     * @return EE_Model_Field_Base or null if none is found
4664
-     */
4665
-    public function get_a_field_of_type($field_class_name)
4666
-    {
4667
-        foreach ($this->field_settings() as $field) {
4668
-            if ($field instanceof $field_class_name) {
4669
-                return $field;
4670
-            }
4671
-        }
4672
-        return null;
4673
-    }
4674
-
4675
-
4676
-
4677
-    /**
4678
-     * Gets a foreign key field pointing to model.
4679
-     *
4680
-     * @param string $model_name eg Event, Registration, not EEM_Event
4681
-     * @return EE_Foreign_Key_Field_Base
4682
-     * @throws EE_Error
4683
-     */
4684
-    public function get_foreign_key_to($model_name)
4685
-    {
4686
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4687
-            foreach ($this->field_settings() as $field) {
4688
-                if (
4689
-                    $field instanceof EE_Foreign_Key_Field_Base
4690
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4691
-                ) {
4692
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4693
-                    break;
4694
-                }
4695
-            }
4696
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4697
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4698
-                    'event_espresso'), $model_name, get_class($this)));
4699
-            }
4700
-        }
4701
-        return $this->_cache_foreign_key_to_fields[$model_name];
4702
-    }
4703
-
4704
-
4705
-
4706
-    /**
4707
-     * Gets the table name (including $wpdb->prefix) for the table alias
4708
-     *
4709
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4710
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4711
-     *                            Either one works
4712
-     * @return string
4713
-     */
4714
-    public function get_table_for_alias($table_alias)
4715
-    {
4716
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4717
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4718
-    }
4719
-
4720
-
4721
-
4722
-    /**
4723
-     * Returns a flat array of all field son this model, instead of organizing them
4724
-     * by table_alias as they are in the constructor.
4725
-     *
4726
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4727
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4728
-     */
4729
-    public function field_settings($include_db_only_fields = false)
4730
-    {
4731
-        if ($include_db_only_fields) {
4732
-            if ($this->_cached_fields === null) {
4733
-                $this->_cached_fields = array();
4734
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4735
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4736
-                        $this->_cached_fields[$field_name] = $field_obj;
4737
-                    }
4738
-                }
4739
-            }
4740
-            return $this->_cached_fields;
4741
-        } else {
4742
-            if ($this->_cached_fields_non_db_only === null) {
4743
-                $this->_cached_fields_non_db_only = array();
4744
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4745
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4746
-                        /** @var $field_obj EE_Model_Field_Base */
4747
-                        if (! $field_obj->is_db_only_field()) {
4748
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4749
-                        }
4750
-                    }
4751
-                }
4752
-            }
4753
-            return $this->_cached_fields_non_db_only;
4754
-        }
4755
-    }
4756
-
4757
-
4758
-
4759
-    /**
4760
-     *        cycle though array of attendees and create objects out of each item
4761
-     *
4762
-     * @access        private
4763
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4764
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4765
-     *                           numerically indexed)
4766
-     * @throws \EE_Error
4767
-     */
4768
-    protected function _create_objects($rows = array())
4769
-    {
4770
-        $array_of_objects = array();
4771
-        if (empty($rows)) {
4772
-            return array();
4773
-        }
4774
-        $count_if_model_has_no_primary_key = 0;
4775
-        $has_primary_key = $this->has_primary_key_field();
4776
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4777
-        foreach ((array)$rows as $row) {
4778
-            if (empty($row)) {
4779
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4780
-                return array();
4781
-            }
4782
-            //check if we've already set this object in the results array,
4783
-            //in which case there's no need to process it further (again)
4784
-            if ($has_primary_key) {
4785
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4786
-                    $row,
4787
-                    $primary_key_field->get_qualified_column(),
4788
-                    $primary_key_field->get_table_column()
4789
-                );
4790
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4791
-                    continue;
4792
-                }
4793
-            }
4794
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4795
-            if (! $classInstance) {
4796
-                throw new EE_Error(
4797
-                    sprintf(
4798
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4799
-                        $this->get_this_model_name(),
4800
-                        http_build_query($row)
4801
-                    )
4802
-                );
4803
-            }
4804
-            //set the timezone on the instantiated objects
4805
-            $classInstance->set_timezone($this->_timezone);
4806
-            //make sure if there is any timezone setting present that we set the timezone for the object
4807
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4808
-            $array_of_objects[$key] = $classInstance;
4809
-            //also, for all the relations of type BelongsTo, see if we can cache
4810
-            //those related models
4811
-            //(we could do this for other relations too, but if there are conditions
4812
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4813
-            //so it requires a little more thought than just caching them immediately...)
4814
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4815
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4816
-                    //check if this model's INFO is present. If so, cache it on the model
4817
-                    $other_model = $relation_obj->get_other_model();
4818
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4819
-                    //if we managed to make a model object from the results, cache it on the main model object
4820
-                    if ($other_model_obj_maybe) {
4821
-                        //set timezone on these other model objects if they are present
4822
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4823
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4824
-                    }
4825
-                }
4826
-            }
4827
-        }
4828
-        return $array_of_objects;
4829
-    }
4830
-
4831
-
4832
-
4833
-    /**
4834
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4835
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4836
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4837
-     * object (as set in the model_field!).
4838
-     *
4839
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4840
-     */
4841
-    public function create_default_object()
4842
-    {
4843
-        $this_model_fields_and_values = array();
4844
-        //setup the row using default values;
4845
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4846
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4847
-        }
4848
-        $className = $this->_get_class_name();
4849
-        $classInstance = EE_Registry::instance()
4850
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4851
-        return $classInstance;
4852
-    }
4853
-
4854
-
4855
-
4856
-    /**
4857
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4858
-     *                             or an stdClass where each property is the name of a column,
4859
-     * @return EE_Base_Class
4860
-     * @throws \EE_Error
4861
-     */
4862
-    public function instantiate_class_from_array_or_object($cols_n_values)
4863
-    {
4864
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4865
-            $cols_n_values = get_object_vars($cols_n_values);
4866
-        }
4867
-        $primary_key = null;
4868
-        //make sure the array only has keys that are fields/columns on this model
4869
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4870
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4871
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4872
-        }
4873
-        $className = $this->_get_class_name();
4874
-        //check we actually found results that we can use to build our model object
4875
-        //if not, return null
4876
-        if ($this->has_primary_key_field()) {
4877
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4878
-                return null;
4879
-            }
4880
-        } else if ($this->unique_indexes()) {
4881
-            $first_column = reset($this_model_fields_n_values);
4882
-            if (empty($first_column)) {
4883
-                return null;
4884
-            }
4885
-        }
4886
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4887
-        if ($primary_key) {
4888
-            $classInstance = $this->get_from_entity_map($primary_key);
4889
-            if (! $classInstance) {
4890
-                $classInstance = EE_Registry::instance()
4891
-                                            ->load_class($className,
4892
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4893
-                // add this new object to the entity map
4894
-                $classInstance = $this->add_to_entity_map($classInstance);
4895
-            }
4896
-        } else {
4897
-            $classInstance = EE_Registry::instance()
4898
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4899
-                                            true, false);
4900
-        }
4901
-        //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.
4902
-        $this->set_timezone($classInstance->get_timezone());
4903
-        return $classInstance;
4904
-    }
4905
-
4906
-
4907
-
4908
-    /**
4909
-     * Gets the model object from the  entity map if it exists
4910
-     *
4911
-     * @param int|string $id the ID of the model object
4912
-     * @return EE_Base_Class
4913
-     */
4914
-    public function get_from_entity_map($id)
4915
-    {
4916
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4917
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4918
-    }
4919
-
4920
-
4921
-
4922
-    /**
4923
-     * add_to_entity_map
4924
-     * Adds the object to the model's entity mappings
4925
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4926
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4927
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4928
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4929
-     *        then this method should be called immediately after the update query
4930
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4931
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4932
-     *
4933
-     * @param    EE_Base_Class $object
4934
-     * @throws EE_Error
4935
-     * @return \EE_Base_Class
4936
-     */
4937
-    public function add_to_entity_map(EE_Base_Class $object)
4938
-    {
4939
-        $className = $this->_get_class_name();
4940
-        if (! $object instanceof $className) {
4941
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4942
-                is_object($object) ? get_class($object) : $object, $className));
4943
-        }
4944
-        /** @var $object EE_Base_Class */
4945
-        if (! $object->ID()) {
4946
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4947
-                "event_espresso"), get_class($this)));
4948
-        }
4949
-        // double check it's not already there
4950
-        $classInstance = $this->get_from_entity_map($object->ID());
4951
-        if ($classInstance) {
4952
-            return $classInstance;
4953
-        } else {
4954
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4955
-            return $object;
4956
-        }
4957
-    }
4958
-
4959
-
4960
-
4961
-    /**
4962
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4963
-     * if no identifier is provided, then the entire entity map is emptied
4964
-     *
4965
-     * @param int|string $id the ID of the model object
4966
-     * @return boolean
4967
-     */
4968
-    public function clear_entity_map($id = null)
4969
-    {
4970
-        if (empty($id)) {
4971
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4972
-            return true;
4973
-        }
4974
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4975
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4976
-            return true;
4977
-        }
4978
-        return false;
4979
-    }
4980
-
4981
-
4982
-
4983
-    /**
4984
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4985
-     * Given an array where keys are column (or column alias) names and values,
4986
-     * returns an array of their corresponding field names and database values
4987
-     *
4988
-     * @param array $cols_n_values
4989
-     * @return array
4990
-     */
4991
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4992
-    {
4993
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4994
-    }
4995
-
4996
-
4997
-
4998
-    /**
4999
-     * _deduce_fields_n_values_from_cols_n_values
5000
-     * Given an array where keys are column (or column alias) names and values,
5001
-     * returns an array of their corresponding field names and database values
5002
-     *
5003
-     * @param string $cols_n_values
5004
-     * @return array
5005
-     */
5006
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5007
-    {
5008
-        $this_model_fields_n_values = array();
5009
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5010
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5011
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5012
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5013
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5014
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5015
-                    if (! $field_obj->is_db_only_field()) {
5016
-                        //prepare field as if its coming from db
5017
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5018
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5019
-                    }
5020
-                }
5021
-            } else {
5022
-                //the table's rows existed. Use their values
5023
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5024
-                    if (! $field_obj->is_db_only_field()) {
5025
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5026
-                            $cols_n_values, $field_obj->get_qualified_column(),
5027
-                            $field_obj->get_table_column()
5028
-                        );
5029
-                    }
5030
-                }
5031
-            }
5032
-        }
5033
-        return $this_model_fields_n_values;
5034
-    }
5035
-
5036
-
5037
-
5038
-    /**
5039
-     * @param $cols_n_values
5040
-     * @param $qualified_column
5041
-     * @param $regular_column
5042
-     * @return null
5043
-     */
5044
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5045
-    {
5046
-        $value = null;
5047
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5048
-        //does the field on the model relate to this column retrieved from the db?
5049
-        //or is it a db-only field? (not relating to the model)
5050
-        if (isset($cols_n_values[$qualified_column])) {
5051
-            $value = $cols_n_values[$qualified_column];
5052
-        } elseif (isset($cols_n_values[$regular_column])) {
5053
-            $value = $cols_n_values[$regular_column];
5054
-        }
5055
-        return $value;
5056
-    }
5057
-
5058
-
5059
-
5060
-    /**
5061
-     * refresh_entity_map_from_db
5062
-     * Makes sure the model object in the entity map at $id assumes the values
5063
-     * of the database (opposite of EE_base_Class::save())
5064
-     *
5065
-     * @param int|string $id
5066
-     * @return EE_Base_Class
5067
-     * @throws \EE_Error
5068
-     */
5069
-    public function refresh_entity_map_from_db($id)
5070
-    {
5071
-        $obj_in_map = $this->get_from_entity_map($id);
5072
-        if ($obj_in_map) {
5073
-            $wpdb_results = $this->_get_all_wpdb_results(
5074
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5075
-            );
5076
-            if ($wpdb_results && is_array($wpdb_results)) {
5077
-                $one_row = reset($wpdb_results);
5078
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5079
-                    $obj_in_map->set_from_db($field_name, $db_value);
5080
-                }
5081
-                //clear the cache of related model objects
5082
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5083
-                    $obj_in_map->clear_cache($relation_name, null, true);
5084
-                }
5085
-            }
5086
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5087
-            return $obj_in_map;
5088
-        } else {
5089
-            return $this->get_one_by_ID($id);
5090
-        }
5091
-    }
5092
-
5093
-
5094
-
5095
-    /**
5096
-     * refresh_entity_map_with
5097
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5098
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5099
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5100
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5101
-     *
5102
-     * @param int|string    $id
5103
-     * @param EE_Base_Class $replacing_model_obj
5104
-     * @return \EE_Base_Class
5105
-     * @throws \EE_Error
5106
-     */
5107
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5108
-    {
5109
-        $obj_in_map = $this->get_from_entity_map($id);
5110
-        if ($obj_in_map) {
5111
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5112
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5113
-                    $obj_in_map->set($field_name, $value);
5114
-                }
5115
-                //make the model object in the entity map's cache match the $replacing_model_obj
5116
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5117
-                    $obj_in_map->clear_cache($relation_name, null, true);
5118
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5119
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5120
-                    }
5121
-                }
5122
-            }
5123
-            return $obj_in_map;
5124
-        } else {
5125
-            $this->add_to_entity_map($replacing_model_obj);
5126
-            return $replacing_model_obj;
5127
-        }
5128
-    }
5129
-
5130
-
5131
-
5132
-    /**
5133
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5134
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5135
-     * require_once($this->_getClassName().".class.php");
5136
-     *
5137
-     * @return string
5138
-     */
5139
-    private function _get_class_name()
5140
-    {
5141
-        return "EE_" . $this->get_this_model_name();
5142
-    }
5143
-
5144
-
5145
-
5146
-    /**
5147
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5148
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5149
-     * it would be 'Events'.
5150
-     *
5151
-     * @param int $quantity
5152
-     * @return string
5153
-     */
5154
-    public function item_name($quantity = 1)
5155
-    {
5156
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5157
-    }
5158
-
5159
-
5160
-
5161
-    /**
5162
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5163
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5164
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5165
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5166
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5167
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5168
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5169
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5170
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5171
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5172
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5173
-     *        return $previousReturnValue.$returnString;
5174
-     * }
5175
-     * require('EEM_Answer.model.php');
5176
-     * $answer=EEM_Answer::instance();
5177
-     * echo $answer->my_callback('monkeys',100);
5178
-     * //will output "you called my_callback! and passed args:monkeys,100"
5179
-     *
5180
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5181
-     * @param array  $args       array of original arguments passed to the function
5182
-     * @throws EE_Error
5183
-     * @return mixed whatever the plugin which calls add_filter decides
5184
-     */
5185
-    public function __call($methodName, $args)
5186
-    {
5187
-        $className = get_class($this);
5188
-        $tagName = "FHEE__{$className}__{$methodName}";
5189
-        if (! has_filter($tagName)) {
5190
-            throw new EE_Error(
5191
-                sprintf(
5192
-                    __('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 );',
5193
-                        'event_espresso'),
5194
-                    $methodName,
5195
-                    $className,
5196
-                    $tagName,
5197
-                    '<br />'
5198
-                )
5199
-            );
5200
-        }
5201
-        return apply_filters($tagName, null, $this, $args);
5202
-    }
5203
-
5204
-
5205
-
5206
-    /**
5207
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5208
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5209
-     *
5210
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5211
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5212
-     *                                                       the object's class name
5213
-     *                                                       or object's ID
5214
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5215
-     *                                                       exists in the database. If it does not, we add it
5216
-     * @throws EE_Error
5217
-     * @return EE_Base_Class
5218
-     */
5219
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5220
-    {
5221
-        $className = $this->_get_class_name();
5222
-        if ($base_class_obj_or_id instanceof $className) {
5223
-            $model_object = $base_class_obj_or_id;
5224
-        } else {
5225
-            $primary_key_field = $this->get_primary_key_field();
5226
-            if (
5227
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5228
-                && (
5229
-                    is_int($base_class_obj_or_id)
5230
-                    || is_string($base_class_obj_or_id)
5231
-                )
5232
-            ) {
5233
-                // assume it's an ID.
5234
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5235
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5236
-            } else if (
5237
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5238
-                && is_string($base_class_obj_or_id)
5239
-            ) {
5240
-                // assume its a string representation of the object
5241
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5242
-            } else {
5243
-                throw new EE_Error(
5244
-                    sprintf(
5245
-                        __(
5246
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5247
-                            'event_espresso'
5248
-                        ),
5249
-                        $base_class_obj_or_id,
5250
-                        $this->_get_class_name(),
5251
-                        print_r($base_class_obj_or_id, true)
5252
-                    )
5253
-                );
5254
-            }
5255
-        }
5256
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5257
-            $model_object->save();
5258
-        }
5259
-        return $model_object;
5260
-    }
5261
-
5262
-
5263
-
5264
-    /**
5265
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5266
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5267
-     * returns it ID.
5268
-     *
5269
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5270
-     * @return int|string depending on the type of this model object's ID
5271
-     * @throws EE_Error
5272
-     */
5273
-    public function ensure_is_ID($base_class_obj_or_id)
5274
-    {
5275
-        $className = $this->_get_class_name();
5276
-        if ($base_class_obj_or_id instanceof $className) {
5277
-            /** @var $base_class_obj_or_id EE_Base_Class */
5278
-            $id = $base_class_obj_or_id->ID();
5279
-        } elseif (is_int($base_class_obj_or_id)) {
5280
-            //assume it's an ID
5281
-            $id = $base_class_obj_or_id;
5282
-        } elseif (is_string($base_class_obj_or_id)) {
5283
-            //assume its a string representation of the object
5284
-            $id = $base_class_obj_or_id;
5285
-        } else {
5286
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5287
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5288
-                print_r($base_class_obj_or_id, true)));
5289
-        }
5290
-        return $id;
5291
-    }
5292
-
5293
-
5294
-
5295
-    /**
5296
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5297
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5298
-     * been sanitized and converted into the appropriate domain.
5299
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5300
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5301
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5302
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5303
-     * $EVT = EEM_Event::instance(); $old_setting =
5304
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5305
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5306
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5307
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5308
-     *
5309
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5310
-     * @return void
5311
-     */
5312
-    public function assume_values_already_prepared_by_model_object(
5313
-        $values_already_prepared = self::not_prepared_by_model_object
5314
-    ) {
5315
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5316
-    }
5317
-
5318
-
5319
-
5320
-    /**
5321
-     * Read comments for assume_values_already_prepared_by_model_object()
5322
-     *
5323
-     * @return int
5324
-     */
5325
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5326
-    {
5327
-        return $this->_values_already_prepared_by_model_object;
5328
-    }
5329
-
5330
-
5331
-
5332
-    /**
5333
-     * Gets all the indexes on this model
5334
-     *
5335
-     * @return EE_Index[]
5336
-     */
5337
-    public function indexes()
5338
-    {
5339
-        return $this->_indexes;
5340
-    }
5341
-
5342
-
5343
-
5344
-    /**
5345
-     * Gets all the Unique Indexes on this model
5346
-     *
5347
-     * @return EE_Unique_Index[]
5348
-     */
5349
-    public function unique_indexes()
5350
-    {
5351
-        $unique_indexes = array();
5352
-        foreach ($this->_indexes as $name => $index) {
5353
-            if ($index instanceof EE_Unique_Index) {
5354
-                $unique_indexes [$name] = $index;
5355
-            }
5356
-        }
5357
-        return $unique_indexes;
5358
-    }
5359
-
5360
-
5361
-
5362
-    /**
5363
-     * Gets all the fields which, when combined, make the primary key.
5364
-     * This is usually just an array with 1 element (the primary key), but in cases
5365
-     * where there is no primary key, it's a combination of fields as defined
5366
-     * on a primary index
5367
-     *
5368
-     * @return EE_Model_Field_Base[] indexed by the field's name
5369
-     * @throws \EE_Error
5370
-     */
5371
-    public function get_combined_primary_key_fields()
5372
-    {
5373
-        foreach ($this->indexes() as $index) {
5374
-            if ($index instanceof EE_Primary_Key_Index) {
5375
-                return $index->fields();
5376
-            }
5377
-        }
5378
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5379
-    }
5380
-
5381
-
5382
-
5383
-    /**
5384
-     * Used to build a primary key string (when the model has no primary key),
5385
-     * which can be used a unique string to identify this model object.
5386
-     *
5387
-     * @param array $cols_n_values keys are field names, values are their values
5388
-     * @return string
5389
-     * @throws \EE_Error
5390
-     */
5391
-    public function get_index_primary_key_string($cols_n_values)
5392
-    {
5393
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5394
-            $this->get_combined_primary_key_fields());
5395
-        return http_build_query($cols_n_values_for_primary_key_index);
5396
-    }
5397
-
5398
-
5399
-
5400
-    /**
5401
-     * Gets the field values from the primary key string
5402
-     *
5403
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5404
-     * @param string $index_primary_key_string
5405
-     * @return null|array
5406
-     * @throws \EE_Error
5407
-     */
5408
-    public function parse_index_primary_key_string($index_primary_key_string)
5409
-    {
5410
-        $key_fields = $this->get_combined_primary_key_fields();
5411
-        //check all of them are in the $id
5412
-        $key_vals_in_combined_pk = array();
5413
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5414
-        foreach ($key_fields as $key_field_name => $field_obj) {
5415
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5416
-                return null;
5417
-            }
5418
-        }
5419
-        return $key_vals_in_combined_pk;
5420
-    }
5421
-
5422
-
5423
-
5424
-    /**
5425
-     * verifies that an array of key-value pairs for model fields has a key
5426
-     * for each field comprising the primary key index
5427
-     *
5428
-     * @param array $key_vals
5429
-     * @return boolean
5430
-     * @throws \EE_Error
5431
-     */
5432
-    public function has_all_combined_primary_key_fields($key_vals)
5433
-    {
5434
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5435
-        foreach ($keys_it_should_have as $key) {
5436
-            if (! isset($key_vals[$key])) {
5437
-                return false;
5438
-            }
5439
-        }
5440
-        return true;
5441
-    }
5442
-
5443
-
5444
-
5445
-    /**
5446
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5447
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5448
-     *
5449
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5450
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5451
-     * @throws EE_Error
5452
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5453
-     *                                                              indexed)
5454
-     */
5455
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5456
-    {
5457
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5458
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5459
-        } elseif (is_array($model_object_or_attributes_array)) {
5460
-            $attributes_array = $model_object_or_attributes_array;
5461
-        } else {
5462
-            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",
5463
-                "event_espresso"), $model_object_or_attributes_array));
5464
-        }
5465
-        //even copies obviously won't have the same ID, so remove the primary key
5466
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5467
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5468
-            unset($attributes_array[$this->primary_key_name()]);
5469
-        }
5470
-        if (isset($query_params[0])) {
5471
-            $query_params[0] = array_merge($attributes_array, $query_params);
5472
-        } else {
5473
-            $query_params[0] = $attributes_array;
5474
-        }
5475
-        return $this->get_all($query_params);
5476
-    }
5477
-
5478
-
5479
-
5480
-    /**
5481
-     * Gets the first copy we find. See get_all_copies for more details
5482
-     *
5483
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5484
-     * @param array $query_params
5485
-     * @return EE_Base_Class
5486
-     * @throws \EE_Error
5487
-     */
5488
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5489
-    {
5490
-        if (! is_array($query_params)) {
5491
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5492
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5493
-                    gettype($query_params)), '4.6.0');
5494
-            $query_params = array();
5495
-        }
5496
-        $query_params['limit'] = 1;
5497
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5498
-        if (is_array($copies)) {
5499
-            return array_shift($copies);
5500
-        } else {
5501
-            return null;
5502
-        }
5503
-    }
5504
-
5505
-
5506
-
5507
-    /**
5508
-     * Updates the item with the specified id. Ignores default query parameters because
5509
-     * we have specified the ID, and its assumed we KNOW what we're doing
5510
-     *
5511
-     * @param array      $fields_n_values keys are field names, values are their new values
5512
-     * @param int|string $id              the value of the primary key to update
5513
-     * @return int number of rows updated
5514
-     * @throws \EE_Error
5515
-     */
5516
-    public function update_by_ID($fields_n_values, $id)
5517
-    {
5518
-        $query_params = array(
5519
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5520
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5521
-        );
5522
-        return $this->update($fields_n_values, $query_params);
5523
-    }
5524
-
5525
-
5526
-
5527
-    /**
5528
-     * Changes an operator which was supplied to the models into one usable in SQL
5529
-     *
5530
-     * @param string $operator_supplied
5531
-     * @return string an operator which can be used in SQL
5532
-     * @throws EE_Error
5533
-     */
5534
-    private function _prepare_operator_for_sql($operator_supplied)
5535
-    {
5536
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5537
-            : null;
5538
-        if ($sql_operator) {
5539
-            return $sql_operator;
5540
-        } else {
5541
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5542
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5543
-        }
5544
-    }
5545
-
5546
-
5547
-
5548
-    /**
5549
-     * Gets an array where keys are the primary keys and values are their 'names'
5550
-     * (as determined by the model object's name() function, which is often overridden)
5551
-     *
5552
-     * @param array $query_params like get_all's
5553
-     * @return string[]
5554
-     * @throws \EE_Error
5555
-     */
5556
-    public function get_all_names($query_params = array())
5557
-    {
5558
-        $objs = $this->get_all($query_params);
5559
-        $names = array();
5560
-        foreach ($objs as $obj) {
5561
-            $names[$obj->ID()] = $obj->name();
5562
-        }
5563
-        return $names;
5564
-    }
5565
-
5566
-
5567
-
5568
-    /**
5569
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5570
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5571
-     * this is duplicated effort and reduces efficiency) you would be better to use
5572
-     * array_keys() on $model_objects.
5573
-     *
5574
-     * @param \EE_Base_Class[] $model_objects
5575
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5576
-     *                                               in the returned array
5577
-     * @return array
5578
-     * @throws \EE_Error
5579
-     */
5580
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5581
-    {
5582
-        if (! $this->has_primary_key_field()) {
5583
-            if (WP_DEBUG) {
5584
-                EE_Error::add_error(
5585
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5586
-                    __FILE__,
5587
-                    __FUNCTION__,
5588
-                    __LINE__
5589
-                );
5590
-            }
5591
-        }
5592
-        $IDs = array();
5593
-        foreach ($model_objects as $model_object) {
5594
-            $id = $model_object->ID();
5595
-            if (! $id) {
5596
-                if ($filter_out_empty_ids) {
5597
-                    continue;
5598
-                }
5599
-                if (WP_DEBUG) {
5600
-                    EE_Error::add_error(
5601
-                        __(
5602
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5603
-                            'event_espresso'
5604
-                        ),
5605
-                        __FILE__,
5606
-                        __FUNCTION__,
5607
-                        __LINE__
5608
-                    );
5609
-                }
5610
-            }
5611
-            $IDs[] = $id;
5612
-        }
5613
-        return $IDs;
5614
-    }
5615
-
5616
-
5617
-
5618
-    /**
5619
-     * Returns the string used in capabilities relating to this model. If there
5620
-     * are no capabilities that relate to this model returns false
5621
-     *
5622
-     * @return string|false
5623
-     */
5624
-    public function cap_slug()
5625
-    {
5626
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5627
-    }
5628
-
5629
-
5630
-
5631
-    /**
5632
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5633
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5634
-     * only returns the cap restrictions array in that context (ie, the array
5635
-     * at that key)
5636
-     *
5637
-     * @param string $context
5638
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5639
-     * @throws \EE_Error
5640
-     */
5641
-    public function cap_restrictions($context = EEM_Base::caps_read)
5642
-    {
5643
-        EEM_Base::verify_is_valid_cap_context($context);
5644
-        //check if we ought to run the restriction generator first
5645
-        if (
5646
-            isset($this->_cap_restriction_generators[$context])
5647
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5648
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5649
-        ) {
5650
-            $this->_cap_restrictions[$context] = array_merge(
5651
-                $this->_cap_restrictions[$context],
5652
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5653
-            );
5654
-        }
5655
-        //and make sure we've finalized the construction of each restriction
5656
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5657
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5658
-                $where_conditions_obj->_finalize_construct($this);
5659
-            }
5660
-        }
5661
-        return $this->_cap_restrictions[$context];
5662
-    }
5663
-
5664
-
5665
-
5666
-    /**
5667
-     * Indicating whether or not this model thinks its a wp core model
5668
-     *
5669
-     * @return boolean
5670
-     */
5671
-    public function is_wp_core_model()
5672
-    {
5673
-        return $this->_wp_core_model;
5674
-    }
5675
-
5676
-
5677
-
5678
-    /**
5679
-     * Gets all the caps that are missing which impose a restriction on
5680
-     * queries made in this context
5681
-     *
5682
-     * @param string $context one of EEM_Base::caps_ constants
5683
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5684
-     * @throws \EE_Error
5685
-     */
5686
-    public function caps_missing($context = EEM_Base::caps_read)
5687
-    {
5688
-        $missing_caps = array();
5689
-        $cap_restrictions = $this->cap_restrictions($context);
5690
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5691
-            if (! EE_Capabilities::instance()
5692
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5693
-            ) {
5694
-                $missing_caps[$cap] = $restriction_if_no_cap;
5695
-            }
5696
-        }
5697
-        return $missing_caps;
5698
-    }
5699
-
5700
-
5701
-
5702
-    /**
5703
-     * Gets the mapping from capability contexts to action strings used in capability names
5704
-     *
5705
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5706
-     * one of 'read', 'edit', or 'delete'
5707
-     */
5708
-    public function cap_contexts_to_cap_action_map()
5709
-    {
5710
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5711
-            $this);
5712
-    }
5713
-
5714
-
5715
-
5716
-    /**
5717
-     * Gets the action string for the specified capability context
5718
-     *
5719
-     * @param string $context
5720
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5721
-     * @throws \EE_Error
5722
-     */
5723
-    public function cap_action_for_context($context)
5724
-    {
5725
-        $mapping = $this->cap_contexts_to_cap_action_map();
5726
-        if (isset($mapping[$context])) {
5727
-            return $mapping[$context];
5728
-        }
5729
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5730
-            return $action;
5731
-        }
5732
-        throw new EE_Error(
5733
-            sprintf(
5734
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5735
-                $context,
5736
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5737
-            )
5738
-        );
5739
-    }
5740
-
5741
-
5742
-
5743
-    /**
5744
-     * Returns all the capability contexts which are valid when querying models
5745
-     *
5746
-     * @return array
5747
-     */
5748
-    public static function valid_cap_contexts()
5749
-    {
5750
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5751
-            self::caps_read,
5752
-            self::caps_read_admin,
5753
-            self::caps_edit,
5754
-            self::caps_delete,
5755
-        ));
5756
-    }
5757
-
5758
-
5759
-
5760
-    /**
5761
-     * Returns all valid options for 'default_where_conditions'
5762
-     *
5763
-     * @return array
5764
-     */
5765
-    public static function valid_default_where_conditions()
5766
-    {
5767
-        return array(
5768
-            EEM_Base::default_where_conditions_all,
5769
-            EEM_Base::default_where_conditions_this_only,
5770
-            EEM_Base::default_where_conditions_others_only,
5771
-            EEM_Base::default_where_conditions_minimum_all,
5772
-            EEM_Base::default_where_conditions_minimum_others,
5773
-            EEM_Base::default_where_conditions_none
5774
-        );
5775
-    }
5776
-
5777
-    // public static function default_where_conditions_full
5778
-    /**
5779
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5780
-     *
5781
-     * @param string $context
5782
-     * @return bool
5783
-     * @throws \EE_Error
5784
-     */
5785
-    static public function verify_is_valid_cap_context($context)
5786
-    {
5787
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5788
-        if (in_array($context, $valid_cap_contexts)) {
5789
-            return true;
5790
-        } else {
5791
-            throw new EE_Error(
5792
-                sprintf(
5793
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5794
-                        'event_espresso'),
5795
-                    $context,
5796
-                    'EEM_Base',
5797
-                    implode(',', $valid_cap_contexts)
5798
-                )
5799
-            );
5800
-        }
5801
-    }
5802
-
5803
-
5804
-
5805
-    /**
5806
-     * Clears all the models field caches. This is only useful when a sub-class
5807
-     * might have added a field or something and these caches might be invalidated
5808
-     */
5809
-    protected function _invalidate_field_caches()
5810
-    {
5811
-        $this->_cache_foreign_key_to_fields = array();
5812
-        $this->_cached_fields = null;
5813
-        $this->_cached_fields_non_db_only = null;
5814
-    }
5815
-
5816
-
5817
-
5818
-    /**
5819
-     * Gets the list of all the where query param keys that relate to logic instead of field names
5820
-     * (eg "and", "or", "not").
5821
-     *
5822
-     * @return array
5823
-     */
5824
-    public function logic_query_param_keys()
5825
-    {
5826
-        return $this->_logic_query_param_keys;
5827
-    }
5828
-
5829
-
5830
-
5831
-    /**
5832
-     * Determines whether or not the where query param array key is for a logic query param.
5833
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5834
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5835
-     *
5836
-     * @param $query_param_key
5837
-     * @return bool
5838
-     */
5839
-    public function is_logic_query_param_key($query_param_key)
5840
-    {
5841
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5842
-            if ($query_param_key === $logic_query_param_key
5843
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5844
-            ) {
5845
-                return true;
5846
-            }
5847
-        }
5848
-        return false;
5849
-    }
3609
+		}
3610
+		return $null_friendly_where_conditions;
3611
+	}
3612
+
3613
+
3614
+
3615
+	/**
3616
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3617
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3618
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3619
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3620
+	 *
3621
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3622
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3623
+	 */
3624
+	private function _get_default_where_conditions($model_relation_path = null)
3625
+	{
3626
+		if ($this->_ignore_where_strategy) {
3627
+			return array();
3628
+		}
3629
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3630
+	}
3631
+
3632
+
3633
+
3634
+	/**
3635
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3636
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3637
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3638
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3639
+	 * Similar to _get_default_where_conditions
3640
+	 *
3641
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3642
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3643
+	 */
3644
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3645
+	{
3646
+		if ($this->_ignore_where_strategy) {
3647
+			return array();
3648
+		}
3649
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3650
+	}
3651
+
3652
+
3653
+
3654
+	/**
3655
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3656
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3657
+	 *
3658
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3659
+	 * @return string
3660
+	 * @throws \EE_Error
3661
+	 */
3662
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3663
+	{
3664
+		$selects = $this->_get_columns_to_select_for_this_model();
3665
+		foreach (
3666
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3667
+			$name_of_other_model_included
3668
+		) {
3669
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3670
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3671
+			foreach ($other_model_selects as $key => $value) {
3672
+				$selects[] = $value;
3673
+			}
3674
+		}
3675
+		return implode(", ", $selects);
3676
+	}
3677
+
3678
+
3679
+
3680
+	/**
3681
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3682
+	 * So that's going to be the columns for all the fields on the model
3683
+	 *
3684
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3685
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3686
+	 */
3687
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3688
+	{
3689
+		$fields = $this->field_settings();
3690
+		$selects = array();
3691
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3692
+			$this->get_this_model_name());
3693
+		foreach ($fields as $field_obj) {
3694
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3695
+						 . $field_obj->get_table_alias()
3696
+						 . "."
3697
+						 . $field_obj->get_table_column()
3698
+						 . " AS '"
3699
+						 . $table_alias_with_model_relation_chain_prefix
3700
+						 . $field_obj->get_table_alias()
3701
+						 . "."
3702
+						 . $field_obj->get_table_column()
3703
+						 . "'";
3704
+		}
3705
+		//make sure we are also getting the PKs of each table
3706
+		$tables = $this->get_tables();
3707
+		if (count($tables) > 1) {
3708
+			foreach ($tables as $table_obj) {
3709
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3710
+									   . $table_obj->get_fully_qualified_pk_column();
3711
+				if (! in_array($qualified_pk_column, $selects)) {
3712
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3713
+				}
3714
+			}
3715
+		}
3716
+		return $selects;
3717
+	}
3718
+
3719
+
3720
+
3721
+	/**
3722
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3723
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3724
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3725
+	 * SQL for joining, and the data types
3726
+	 *
3727
+	 * @param null|string                 $original_query_param
3728
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3729
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3730
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3731
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3732
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3733
+	 *                                                          or 'Registration's
3734
+	 * @param string                      $original_query_param what it originally was (eg
3735
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3736
+	 *                                                          matches $query_param
3737
+	 * @throws EE_Error
3738
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3739
+	 */
3740
+	private function _extract_related_model_info_from_query_param(
3741
+		$query_param,
3742
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3743
+		$query_param_type,
3744
+		$original_query_param = null
3745
+	) {
3746
+		if ($original_query_param === null) {
3747
+			$original_query_param = $query_param;
3748
+		}
3749
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3750
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3751
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3752
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3753
+		//check to see if we have a field on this model
3754
+		$this_model_fields = $this->field_settings(true);
3755
+		if (array_key_exists($query_param, $this_model_fields)) {
3756
+			if ($allow_fields) {
3757
+				return;
3758
+			} else {
3759
+				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",
3760
+					"event_espresso"),
3761
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3762
+			}
3763
+		} //check if this is a special logic query param
3764
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3765
+			if ($allow_logic_query_params) {
3766
+				return;
3767
+			} else {
3768
+				throw new EE_Error(
3769
+					sprintf(
3770
+						__('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',
3771
+							'event_espresso'),
3772
+						implode('", "', $this->_logic_query_param_keys),
3773
+						$query_param,
3774
+						get_class($this),
3775
+						'<br />',
3776
+						"\t"
3777
+						. ' $passed_in_query_info = <pre>'
3778
+						. print_r($passed_in_query_info, true)
3779
+						. '</pre>'
3780
+						. "\n\t"
3781
+						. ' $query_param_type = '
3782
+						. $query_param_type
3783
+						. "\n\t"
3784
+						. ' $original_query_param = '
3785
+						. $original_query_param
3786
+					)
3787
+				);
3788
+			}
3789
+		} //check if it's a custom selection
3790
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3791
+			return;
3792
+		}
3793
+		//check if has a model name at the beginning
3794
+		//and
3795
+		//check if it's a field on a related model
3796
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3797
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3798
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3799
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3800
+				if ($query_param === '') {
3801
+					//nothing left to $query_param
3802
+					//we should actually end in a field name, not a model like this!
3803
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3804
+						"event_espresso"),
3805
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3806
+				} else {
3807
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3808
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3809
+						$passed_in_query_info, $query_param_type, $original_query_param);
3810
+					return;
3811
+				}
3812
+			} elseif ($query_param === $valid_related_model_name) {
3813
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3814
+				return;
3815
+			}
3816
+		}
3817
+		//ok so $query_param didn't start with a model name
3818
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3819
+		//it's wack, that's what it is
3820
+		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",
3821
+			"event_espresso"),
3822
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3823
+	}
3824
+
3825
+
3826
+
3827
+	/**
3828
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3829
+	 * and store it on $passed_in_query_info
3830
+	 *
3831
+	 * @param string                      $model_name
3832
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3833
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3834
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3835
+	 *                                                          and are adding a join to 'Payment' with the original
3836
+	 *                                                          query param key
3837
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3838
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3839
+	 *                                                          Payment wants to add default query params so that it
3840
+	 *                                                          will know what models to prepend onto its default query
3841
+	 *                                                          params or in case it wants to rename tables (in case
3842
+	 *                                                          there are multiple joins to the same table)
3843
+	 * @return void
3844
+	 * @throws \EE_Error
3845
+	 */
3846
+	private function _add_join_to_model(
3847
+		$model_name,
3848
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3849
+		$original_query_param
3850
+	) {
3851
+		$relation_obj = $this->related_settings_for($model_name);
3852
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3853
+		//check if the relation is HABTM, because then we're essentially doing two joins
3854
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3855
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3856
+			$join_model_obj = $relation_obj->get_join_model();
3857
+			//replace the model specified with the join model for this relation chain, whi
3858
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3859
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3860
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3861
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3862
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3863
+			$passed_in_query_info->merge($new_query_info);
3864
+		}
3865
+		//now just join to the other table pointed to by the relation object, and add its data types
3866
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3867
+			array($model_relation_chain => $model_name),
3868
+			$relation_obj->get_join_statement($model_relation_chain));
3869
+		$passed_in_query_info->merge($new_query_info);
3870
+	}
3871
+
3872
+
3873
+
3874
+	/**
3875
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3876
+	 *
3877
+	 * @param array $where_params like EEM_Base::get_all
3878
+	 * @return string of SQL
3879
+	 * @throws \EE_Error
3880
+	 */
3881
+	private function _construct_where_clause($where_params)
3882
+	{
3883
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3884
+		if ($SQL) {
3885
+			return " WHERE " . $SQL;
3886
+		} else {
3887
+			return '';
3888
+		}
3889
+	}
3890
+
3891
+
3892
+
3893
+	/**
3894
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3895
+	 * and should be passed HAVING parameters, not WHERE parameters
3896
+	 *
3897
+	 * @param array $having_params
3898
+	 * @return string
3899
+	 * @throws \EE_Error
3900
+	 */
3901
+	private function _construct_having_clause($having_params)
3902
+	{
3903
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3904
+		if ($SQL) {
3905
+			return " HAVING " . $SQL;
3906
+		} else {
3907
+			return '';
3908
+		}
3909
+	}
3910
+
3911
+
3912
+
3913
+	/**
3914
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3915
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3916
+	 * EEM_Attendee.
3917
+	 *
3918
+	 * @param string $field_name
3919
+	 * @param string $model_name
3920
+	 * @return EE_Model_Field_Base
3921
+	 * @throws EE_Error
3922
+	 */
3923
+	protected function _get_field_on_model($field_name, $model_name)
3924
+	{
3925
+		$model_class = 'EEM_' . $model_name;
3926
+		$model_filepath = $model_class . ".model.php";
3927
+		if (is_readable($model_filepath)) {
3928
+			require_once($model_filepath);
3929
+			$model_instance = call_user_func($model_name . "::instance");
3930
+			/* @var $model_instance EEM_Base */
3931
+			return $model_instance->field_settings_for($field_name);
3932
+		} else {
3933
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3934
+				'event_espresso'), $model_name, $model_class, $model_filepath));
3935
+		}
3936
+	}
3937
+
3938
+
3939
+
3940
+	/**
3941
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3942
+	 * Event_Meta.meta_value = 'foo'))"
3943
+	 *
3944
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3945
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3946
+	 * @throws EE_Error
3947
+	 * @return string of SQL
3948
+	 */
3949
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3950
+	{
3951
+		$where_clauses = array();
3952
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3953
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3954
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3955
+				switch ($query_param) {
3956
+					case 'not':
3957
+					case 'NOT':
3958
+						$where_clauses[] = "! ("
3959
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3960
+								$glue)
3961
+										   . ")";
3962
+						break;
3963
+					case 'and':
3964
+					case 'AND':
3965
+						$where_clauses[] = " ("
3966
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3967
+								' AND ')
3968
+										   . ")";
3969
+						break;
3970
+					case 'or':
3971
+					case 'OR':
3972
+						$where_clauses[] = " ("
3973
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3974
+								' OR ')
3975
+										   . ")";
3976
+						break;
3977
+				}
3978
+			} else {
3979
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3980
+				//if it's not a normal field, maybe it's a custom selection?
3981
+				if (! $field_obj) {
3982
+					if (isset($this->_custom_selections[$query_param][1])) {
3983
+						$field_obj = $this->_custom_selections[$query_param][1];
3984
+					} else {
3985
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3986
+							"event_espresso"), $query_param));
3987
+					}
3988
+				}
3989
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3990
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3991
+			}
3992
+		}
3993
+		return $where_clauses ? implode($glue, $where_clauses) : '';
3994
+	}
3995
+
3996
+
3997
+
3998
+	/**
3999
+	 * Takes the input parameter and extract the table name (alias) and column name
4000
+	 *
4001
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4002
+	 * @throws EE_Error
4003
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4004
+	 */
4005
+	private function _deduce_column_name_from_query_param($query_param)
4006
+	{
4007
+		$field = $this->_deduce_field_from_query_param($query_param);
4008
+		if ($field) {
4009
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4010
+				$query_param);
4011
+			return $table_alias_prefix . $field->get_qualified_column();
4012
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
4013
+			//maybe it's custom selection item?
4014
+			//if so, just use it as the "column name"
4015
+			return $query_param;
4016
+		} else {
4017
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4018
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4019
+		}
4020
+	}
4021
+
4022
+
4023
+
4024
+	/**
4025
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4026
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4027
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4028
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4029
+	 *
4030
+	 * @param string $condition_query_param_key
4031
+	 * @return string
4032
+	 */
4033
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4034
+	{
4035
+		$pos_of_star = strpos($condition_query_param_key, '*');
4036
+		if ($pos_of_star === false) {
4037
+			return $condition_query_param_key;
4038
+		} else {
4039
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4040
+			return $condition_query_param_sans_star;
4041
+		}
4042
+	}
4043
+
4044
+
4045
+
4046
+	/**
4047
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4048
+	 *
4049
+	 * @param                            mixed      array | string    $op_and_value
4050
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4051
+	 * @throws EE_Error
4052
+	 * @return string
4053
+	 */
4054
+	private function _construct_op_and_value($op_and_value, $field_obj)
4055
+	{
4056
+		if (is_array($op_and_value)) {
4057
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4058
+			if (! $operator) {
4059
+				$php_array_like_string = array();
4060
+				foreach ($op_and_value as $key => $value) {
4061
+					$php_array_like_string[] = "$key=>$value";
4062
+				}
4063
+				throw new EE_Error(
4064
+					sprintf(
4065
+						__(
4066
+							"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))",
4067
+							"event_espresso"
4068
+						),
4069
+						implode(",", $php_array_like_string)
4070
+					)
4071
+				);
4072
+			}
4073
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4074
+		} else {
4075
+			$operator = '=';
4076
+			$value = $op_and_value;
4077
+		}
4078
+		//check to see if the value is actually another field
4079
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4080
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4081
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4082
+			//in this case, the value should be an array, or at least a comma-separated list
4083
+			//it will need to handle a little differently
4084
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4085
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4086
+			return $operator . SP . $cleaned_value;
4087
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4088
+			//the value should be an array with count of two.
4089
+			if (count($value) !== 2) {
4090
+				throw new EE_Error(
4091
+					sprintf(
4092
+						__(
4093
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4094
+							'event_espresso'
4095
+						),
4096
+						"BETWEEN"
4097
+					)
4098
+				);
4099
+			}
4100
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4101
+			return $operator . SP . $cleaned_value;
4102
+		} elseif (in_array($operator, $this->_null_style_operators)) {
4103
+			if ($value !== null) {
4104
+				throw new EE_Error(
4105
+					sprintf(
4106
+						__(
4107
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4108
+							"event_espresso"
4109
+						),
4110
+						$value,
4111
+						$operator
4112
+					)
4113
+				);
4114
+			}
4115
+			return $operator;
4116
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
4117
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4118
+			//remove other junk. So just treat it as a string.
4119
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4120
+		} elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4121
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4122
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4123
+			throw new EE_Error(
4124
+				sprintf(
4125
+					__(
4126
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4127
+						'event_espresso'
4128
+					),
4129
+					$operator,
4130
+					$operator
4131
+				)
4132
+			);
4133
+		} elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4134
+			throw new EE_Error(
4135
+				sprintf(
4136
+					__(
4137
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4138
+						'event_espresso'
4139
+					),
4140
+					$operator,
4141
+					$operator
4142
+				)
4143
+			);
4144
+		} else {
4145
+			throw new EE_Error(
4146
+				sprintf(
4147
+					__(
4148
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4149
+						"event_espresso"
4150
+					),
4151
+					http_build_query($op_and_value)
4152
+				)
4153
+			);
4154
+		}
4155
+	}
4156
+
4157
+
4158
+
4159
+	/**
4160
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4161
+	 *
4162
+	 * @param array                      $values
4163
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4164
+	 *                                              '%s'
4165
+	 * @return string
4166
+	 * @throws \EE_Error
4167
+	 */
4168
+	public function _construct_between_value($values, $field_obj)
4169
+	{
4170
+		$cleaned_values = array();
4171
+		foreach ($values as $value) {
4172
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4173
+		}
4174
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4175
+	}
4176
+
4177
+
4178
+
4179
+	/**
4180
+	 * Takes an array or a comma-separated list of $values and cleans them
4181
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4182
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4183
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4184
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4185
+	 *
4186
+	 * @param mixed                      $values    array or comma-separated string
4187
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4188
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4189
+	 * @throws \EE_Error
4190
+	 */
4191
+	public function _construct_in_value($values, $field_obj)
4192
+	{
4193
+		//check if the value is a CSV list
4194
+		if (is_string($values)) {
4195
+			//in which case, turn it into an array
4196
+			$values = explode(",", $values);
4197
+		}
4198
+		$cleaned_values = array();
4199
+		foreach ($values as $value) {
4200
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4201
+		}
4202
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4203
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4204
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4205
+		if (empty($cleaned_values)) {
4206
+			$all_fields = $this->field_settings();
4207
+			$a_field = array_shift($all_fields);
4208
+			$main_table = $this->_get_main_table();
4209
+			$cleaned_values[] = "SELECT "
4210
+								. $a_field->get_table_column()
4211
+								. " FROM "
4212
+								. $main_table->get_table_name()
4213
+								. " WHERE FALSE";
4214
+		}
4215
+		return "(" . implode(",", $cleaned_values) . ")";
4216
+	}
4217
+
4218
+
4219
+
4220
+	/**
4221
+	 * @param mixed                      $value
4222
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4223
+	 * @throws EE_Error
4224
+	 * @return false|null|string
4225
+	 */
4226
+	private function _wpdb_prepare_using_field($value, $field_obj)
4227
+	{
4228
+		/** @type WPDB $wpdb */
4229
+		global $wpdb;
4230
+		if ($field_obj instanceof EE_Model_Field_Base) {
4231
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4232
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4233
+		} else {//$field_obj should really just be a data type
4234
+			if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4235
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4236
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4237
+			}
4238
+			return $wpdb->prepare($field_obj, $value);
4239
+		}
4240
+	}
4241
+
4242
+
4243
+
4244
+	/**
4245
+	 * Takes the input parameter and finds the model field that it indicates.
4246
+	 *
4247
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4248
+	 * @throws EE_Error
4249
+	 * @return EE_Model_Field_Base
4250
+	 */
4251
+	protected function _deduce_field_from_query_param($query_param_name)
4252
+	{
4253
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4254
+		//which will help us find the database table and column
4255
+		$query_param_parts = explode(".", $query_param_name);
4256
+		if (empty($query_param_parts)) {
4257
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4258
+				'event_espresso'), $query_param_name));
4259
+		}
4260
+		$number_of_parts = count($query_param_parts);
4261
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4262
+		if ($number_of_parts === 1) {
4263
+			$field_name = $last_query_param_part;
4264
+			$model_obj = $this;
4265
+		} else {// $number_of_parts >= 2
4266
+			//the last part is the column name, and there are only 2parts. therefore...
4267
+			$field_name = $last_query_param_part;
4268
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4269
+		}
4270
+		try {
4271
+			return $model_obj->field_settings_for($field_name);
4272
+		} catch (EE_Error $e) {
4273
+			return null;
4274
+		}
4275
+	}
4276
+
4277
+
4278
+
4279
+	/**
4280
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4281
+	 * alias and column which corresponds to it
4282
+	 *
4283
+	 * @param string $field_name
4284
+	 * @throws EE_Error
4285
+	 * @return string
4286
+	 */
4287
+	public function _get_qualified_column_for_field($field_name)
4288
+	{
4289
+		$all_fields = $this->field_settings();
4290
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4291
+		if ($field) {
4292
+			return $field->get_qualified_column();
4293
+		} else {
4294
+			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.",
4295
+				'event_espresso'), $field_name, get_class($this)));
4296
+		}
4297
+	}
4298
+
4299
+
4300
+
4301
+	/**
4302
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4303
+	 * Example usage:
4304
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4305
+	 *      array(),
4306
+	 *      ARRAY_A,
4307
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4308
+	 *  );
4309
+	 * is equivalent to
4310
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4311
+	 * and
4312
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4313
+	 *      array(
4314
+	 *          array(
4315
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4316
+	 *          ),
4317
+	 *          ARRAY_A,
4318
+	 *          implode(
4319
+	 *              ', ',
4320
+	 *              array_merge(
4321
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4322
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4323
+	 *              )
4324
+	 *          )
4325
+	 *      )
4326
+	 *  );
4327
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4328
+	 *
4329
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4330
+	 *                                            and the one whose fields you are selecting for example: when querying
4331
+	 *                                            tickets model and selecting fields from the tickets model you would
4332
+	 *                                            leave this parameter empty, because no models are needed to join
4333
+	 *                                            between the queried model and the selected one. Likewise when
4334
+	 *                                            querying the datetime model and selecting fields from the tickets
4335
+	 *                                            model, it would also be left empty, because there is a direct
4336
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4337
+	 *                                            them together. However, when querying from the event model and
4338
+	 *                                            selecting fields from the ticket model, you should provide the string
4339
+	 *                                            'Datetime', indicating that the event model must first join to the
4340
+	 *                                            datetime model in order to find its relation to ticket model.
4341
+	 *                                            Also, when querying from the venue model and selecting fields from
4342
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4343
+	 *                                            indicating you need to join the venue model to the event model,
4344
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4345
+	 *                                            This string is used to deduce the prefix that gets added onto the
4346
+	 *                                            models' tables qualified columns
4347
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4348
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4349
+	 *                                            qualified column names
4350
+	 * @return array|string
4351
+	 */
4352
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4353
+	{
4354
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4355
+		$qualified_columns = array();
4356
+		foreach ($this->field_settings() as $field_name => $field) {
4357
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4358
+		}
4359
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4360
+	}
4361
+
4362
+
4363
+
4364
+	/**
4365
+	 * constructs the select use on special limit joins
4366
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4367
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4368
+	 * (as that is typically where the limits would be set).
4369
+	 *
4370
+	 * @param  string       $table_alias The table the select is being built for
4371
+	 * @param  mixed|string $limit       The limit for this select
4372
+	 * @return string                The final select join element for the query.
4373
+	 */
4374
+	public function _construct_limit_join_select($table_alias, $limit)
4375
+	{
4376
+		$SQL = '';
4377
+		foreach ($this->_tables as $table_obj) {
4378
+			if ($table_obj instanceof EE_Primary_Table) {
4379
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4380
+					? $table_obj->get_select_join_limit($limit)
4381
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4382
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4383
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4384
+					? $table_obj->get_select_join_limit_join($limit)
4385
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4386
+			}
4387
+		}
4388
+		return $SQL;
4389
+	}
4390
+
4391
+
4392
+
4393
+	/**
4394
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4395
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4396
+	 *
4397
+	 * @return string SQL
4398
+	 * @throws \EE_Error
4399
+	 */
4400
+	public function _construct_internal_join()
4401
+	{
4402
+		$SQL = $this->_get_main_table()->get_table_sql();
4403
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4404
+		return $SQL;
4405
+	}
4406
+
4407
+
4408
+
4409
+	/**
4410
+	 * Constructs the SQL for joining all the tables on this model.
4411
+	 * Normally $alias should be the primary table's alias, but in cases where
4412
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4413
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4414
+	 * alias, this will construct SQL like:
4415
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4416
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4417
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4418
+	 *
4419
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4420
+	 * @return string
4421
+	 */
4422
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4423
+	{
4424
+		$SQL = '';
4425
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4426
+		foreach ($this->_tables as $table_obj) {
4427
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4428
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4429
+					//so we're joining to this table, meaning the table is already in
4430
+					//the FROM statement, BUT the primary table isn't. So we want
4431
+					//to add the inverse join sql
4432
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4433
+				} else {
4434
+					//just add a regular JOIN to this table from the primary table
4435
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4436
+				}
4437
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4438
+		}
4439
+		return $SQL;
4440
+	}
4441
+
4442
+
4443
+
4444
+	/**
4445
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4446
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4447
+	 * their data type (eg, '%s', '%d', etc)
4448
+	 *
4449
+	 * @return array
4450
+	 */
4451
+	public function _get_data_types()
4452
+	{
4453
+		$data_types = array();
4454
+		foreach ($this->field_settings() as $field_obj) {
4455
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4456
+			/** @var $field_obj EE_Model_Field_Base */
4457
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4458
+		}
4459
+		return $data_types;
4460
+	}
4461
+
4462
+
4463
+
4464
+	/**
4465
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4466
+	 *
4467
+	 * @param string $model_name
4468
+	 * @throws EE_Error
4469
+	 * @return EEM_Base
4470
+	 */
4471
+	public function get_related_model_obj($model_name)
4472
+	{
4473
+		$model_classname = "EEM_" . $model_name;
4474
+		if (! class_exists($model_classname)) {
4475
+			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",
4476
+				'event_espresso'), $model_name, $model_classname));
4477
+		}
4478
+		return call_user_func($model_classname . "::instance");
4479
+	}
4480
+
4481
+
4482
+
4483
+	/**
4484
+	 * Returns the array of EE_ModelRelations for this model.
4485
+	 *
4486
+	 * @return EE_Model_Relation_Base[]
4487
+	 */
4488
+	public function relation_settings()
4489
+	{
4490
+		return $this->_model_relations;
4491
+	}
4492
+
4493
+
4494
+
4495
+	/**
4496
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4497
+	 * because without THOSE models, this model probably doesn't have much purpose.
4498
+	 * (Eg, without an event, datetimes have little purpose.)
4499
+	 *
4500
+	 * @return EE_Belongs_To_Relation[]
4501
+	 */
4502
+	public function belongs_to_relations()
4503
+	{
4504
+		$belongs_to_relations = array();
4505
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4506
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4507
+				$belongs_to_relations[$model_name] = $relation_obj;
4508
+			}
4509
+		}
4510
+		return $belongs_to_relations;
4511
+	}
4512
+
4513
+
4514
+
4515
+	/**
4516
+	 * Returns the specified EE_Model_Relation, or throws an exception
4517
+	 *
4518
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4519
+	 * @throws EE_Error
4520
+	 * @return EE_Model_Relation_Base
4521
+	 */
4522
+	public function related_settings_for($relation_name)
4523
+	{
4524
+		$relatedModels = $this->relation_settings();
4525
+		if (! array_key_exists($relation_name, $relatedModels)) {
4526
+			throw new EE_Error(
4527
+				sprintf(
4528
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4529
+						'event_espresso'),
4530
+					$relation_name,
4531
+					$this->_get_class_name(),
4532
+					implode(', ', array_keys($relatedModels))
4533
+				)
4534
+			);
4535
+		}
4536
+		return $relatedModels[$relation_name];
4537
+	}
4538
+
4539
+
4540
+
4541
+	/**
4542
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4543
+	 * fields
4544
+	 *
4545
+	 * @param string $fieldName
4546
+	 * @throws EE_Error
4547
+	 * @return EE_Model_Field_Base
4548
+	 */
4549
+	public function field_settings_for($fieldName)
4550
+	{
4551
+		$fieldSettings = $this->field_settings(true);
4552
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4553
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4554
+				get_class($this)));
4555
+		}
4556
+		return $fieldSettings[$fieldName];
4557
+	}
4558
+
4559
+
4560
+
4561
+	/**
4562
+	 * Checks if this field exists on this model
4563
+	 *
4564
+	 * @param string $fieldName a key in the model's _field_settings array
4565
+	 * @return boolean
4566
+	 */
4567
+	public function has_field($fieldName)
4568
+	{
4569
+		$fieldSettings = $this->field_settings(true);
4570
+		if (isset($fieldSettings[$fieldName])) {
4571
+			return true;
4572
+		} else {
4573
+			return false;
4574
+		}
4575
+	}
4576
+
4577
+
4578
+
4579
+	/**
4580
+	 * Returns whether or not this model has a relation to the specified model
4581
+	 *
4582
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4583
+	 * @return boolean
4584
+	 */
4585
+	public function has_relation($relation_name)
4586
+	{
4587
+		$relations = $this->relation_settings();
4588
+		if (isset($relations[$relation_name])) {
4589
+			return true;
4590
+		} else {
4591
+			return false;
4592
+		}
4593
+	}
4594
+
4595
+
4596
+
4597
+	/**
4598
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4599
+	 * Eg, on EE_Answer that would be ANS_ID field object
4600
+	 *
4601
+	 * @param $field_obj
4602
+	 * @return boolean
4603
+	 */
4604
+	public function is_primary_key_field($field_obj)
4605
+	{
4606
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4607
+	}
4608
+
4609
+
4610
+
4611
+	/**
4612
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4613
+	 * Eg, on EE_Answer that would be ANS_ID field object
4614
+	 *
4615
+	 * @return EE_Model_Field_Base
4616
+	 * @throws EE_Error
4617
+	 */
4618
+	public function get_primary_key_field()
4619
+	{
4620
+		if ($this->_primary_key_field === null) {
4621
+			foreach ($this->field_settings(true) as $field_obj) {
4622
+				if ($this->is_primary_key_field($field_obj)) {
4623
+					$this->_primary_key_field = $field_obj;
4624
+					break;
4625
+				}
4626
+			}
4627
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4628
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4629
+					get_class($this)));
4630
+			}
4631
+		}
4632
+		return $this->_primary_key_field;
4633
+	}
4634
+
4635
+
4636
+
4637
+	/**
4638
+	 * Returns whether or not not there is a primary key on this model.
4639
+	 * Internally does some caching.
4640
+	 *
4641
+	 * @return boolean
4642
+	 */
4643
+	public function has_primary_key_field()
4644
+	{
4645
+		if ($this->_has_primary_key_field === null) {
4646
+			try {
4647
+				$this->get_primary_key_field();
4648
+				$this->_has_primary_key_field = true;
4649
+			} catch (EE_Error $e) {
4650
+				$this->_has_primary_key_field = false;
4651
+			}
4652
+		}
4653
+		return $this->_has_primary_key_field;
4654
+	}
4655
+
4656
+
4657
+
4658
+	/**
4659
+	 * Finds the first field of type $field_class_name.
4660
+	 *
4661
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4662
+	 *                                 EE_Foreign_Key_Field, etc
4663
+	 * @return EE_Model_Field_Base or null if none is found
4664
+	 */
4665
+	public function get_a_field_of_type($field_class_name)
4666
+	{
4667
+		foreach ($this->field_settings() as $field) {
4668
+			if ($field instanceof $field_class_name) {
4669
+				return $field;
4670
+			}
4671
+		}
4672
+		return null;
4673
+	}
4674
+
4675
+
4676
+
4677
+	/**
4678
+	 * Gets a foreign key field pointing to model.
4679
+	 *
4680
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4681
+	 * @return EE_Foreign_Key_Field_Base
4682
+	 * @throws EE_Error
4683
+	 */
4684
+	public function get_foreign_key_to($model_name)
4685
+	{
4686
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4687
+			foreach ($this->field_settings() as $field) {
4688
+				if (
4689
+					$field instanceof EE_Foreign_Key_Field_Base
4690
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4691
+				) {
4692
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4693
+					break;
4694
+				}
4695
+			}
4696
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4697
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4698
+					'event_espresso'), $model_name, get_class($this)));
4699
+			}
4700
+		}
4701
+		return $this->_cache_foreign_key_to_fields[$model_name];
4702
+	}
4703
+
4704
+
4705
+
4706
+	/**
4707
+	 * Gets the table name (including $wpdb->prefix) for the table alias
4708
+	 *
4709
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4710
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4711
+	 *                            Either one works
4712
+	 * @return string
4713
+	 */
4714
+	public function get_table_for_alias($table_alias)
4715
+	{
4716
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4717
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4718
+	}
4719
+
4720
+
4721
+
4722
+	/**
4723
+	 * Returns a flat array of all field son this model, instead of organizing them
4724
+	 * by table_alias as they are in the constructor.
4725
+	 *
4726
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4727
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4728
+	 */
4729
+	public function field_settings($include_db_only_fields = false)
4730
+	{
4731
+		if ($include_db_only_fields) {
4732
+			if ($this->_cached_fields === null) {
4733
+				$this->_cached_fields = array();
4734
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4735
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4736
+						$this->_cached_fields[$field_name] = $field_obj;
4737
+					}
4738
+				}
4739
+			}
4740
+			return $this->_cached_fields;
4741
+		} else {
4742
+			if ($this->_cached_fields_non_db_only === null) {
4743
+				$this->_cached_fields_non_db_only = array();
4744
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4745
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4746
+						/** @var $field_obj EE_Model_Field_Base */
4747
+						if (! $field_obj->is_db_only_field()) {
4748
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4749
+						}
4750
+					}
4751
+				}
4752
+			}
4753
+			return $this->_cached_fields_non_db_only;
4754
+		}
4755
+	}
4756
+
4757
+
4758
+
4759
+	/**
4760
+	 *        cycle though array of attendees and create objects out of each item
4761
+	 *
4762
+	 * @access        private
4763
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4764
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4765
+	 *                           numerically indexed)
4766
+	 * @throws \EE_Error
4767
+	 */
4768
+	protected function _create_objects($rows = array())
4769
+	{
4770
+		$array_of_objects = array();
4771
+		if (empty($rows)) {
4772
+			return array();
4773
+		}
4774
+		$count_if_model_has_no_primary_key = 0;
4775
+		$has_primary_key = $this->has_primary_key_field();
4776
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4777
+		foreach ((array)$rows as $row) {
4778
+			if (empty($row)) {
4779
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4780
+				return array();
4781
+			}
4782
+			//check if we've already set this object in the results array,
4783
+			//in which case there's no need to process it further (again)
4784
+			if ($has_primary_key) {
4785
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4786
+					$row,
4787
+					$primary_key_field->get_qualified_column(),
4788
+					$primary_key_field->get_table_column()
4789
+				);
4790
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4791
+					continue;
4792
+				}
4793
+			}
4794
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4795
+			if (! $classInstance) {
4796
+				throw new EE_Error(
4797
+					sprintf(
4798
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4799
+						$this->get_this_model_name(),
4800
+						http_build_query($row)
4801
+					)
4802
+				);
4803
+			}
4804
+			//set the timezone on the instantiated objects
4805
+			$classInstance->set_timezone($this->_timezone);
4806
+			//make sure if there is any timezone setting present that we set the timezone for the object
4807
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4808
+			$array_of_objects[$key] = $classInstance;
4809
+			//also, for all the relations of type BelongsTo, see if we can cache
4810
+			//those related models
4811
+			//(we could do this for other relations too, but if there are conditions
4812
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4813
+			//so it requires a little more thought than just caching them immediately...)
4814
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4815
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4816
+					//check if this model's INFO is present. If so, cache it on the model
4817
+					$other_model = $relation_obj->get_other_model();
4818
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4819
+					//if we managed to make a model object from the results, cache it on the main model object
4820
+					if ($other_model_obj_maybe) {
4821
+						//set timezone on these other model objects if they are present
4822
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4823
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4824
+					}
4825
+				}
4826
+			}
4827
+		}
4828
+		return $array_of_objects;
4829
+	}
4830
+
4831
+
4832
+
4833
+	/**
4834
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4835
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4836
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4837
+	 * object (as set in the model_field!).
4838
+	 *
4839
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4840
+	 */
4841
+	public function create_default_object()
4842
+	{
4843
+		$this_model_fields_and_values = array();
4844
+		//setup the row using default values;
4845
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4846
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4847
+		}
4848
+		$className = $this->_get_class_name();
4849
+		$classInstance = EE_Registry::instance()
4850
+									->load_class($className, array($this_model_fields_and_values), false, false);
4851
+		return $classInstance;
4852
+	}
4853
+
4854
+
4855
+
4856
+	/**
4857
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4858
+	 *                             or an stdClass where each property is the name of a column,
4859
+	 * @return EE_Base_Class
4860
+	 * @throws \EE_Error
4861
+	 */
4862
+	public function instantiate_class_from_array_or_object($cols_n_values)
4863
+	{
4864
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4865
+			$cols_n_values = get_object_vars($cols_n_values);
4866
+		}
4867
+		$primary_key = null;
4868
+		//make sure the array only has keys that are fields/columns on this model
4869
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4870
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4871
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4872
+		}
4873
+		$className = $this->_get_class_name();
4874
+		//check we actually found results that we can use to build our model object
4875
+		//if not, return null
4876
+		if ($this->has_primary_key_field()) {
4877
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4878
+				return null;
4879
+			}
4880
+		} else if ($this->unique_indexes()) {
4881
+			$first_column = reset($this_model_fields_n_values);
4882
+			if (empty($first_column)) {
4883
+				return null;
4884
+			}
4885
+		}
4886
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4887
+		if ($primary_key) {
4888
+			$classInstance = $this->get_from_entity_map($primary_key);
4889
+			if (! $classInstance) {
4890
+				$classInstance = EE_Registry::instance()
4891
+											->load_class($className,
4892
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4893
+				// add this new object to the entity map
4894
+				$classInstance = $this->add_to_entity_map($classInstance);
4895
+			}
4896
+		} else {
4897
+			$classInstance = EE_Registry::instance()
4898
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4899
+											true, false);
4900
+		}
4901
+		//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.
4902
+		$this->set_timezone($classInstance->get_timezone());
4903
+		return $classInstance;
4904
+	}
4905
+
4906
+
4907
+
4908
+	/**
4909
+	 * Gets the model object from the  entity map if it exists
4910
+	 *
4911
+	 * @param int|string $id the ID of the model object
4912
+	 * @return EE_Base_Class
4913
+	 */
4914
+	public function get_from_entity_map($id)
4915
+	{
4916
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4917
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4918
+	}
4919
+
4920
+
4921
+
4922
+	/**
4923
+	 * add_to_entity_map
4924
+	 * Adds the object to the model's entity mappings
4925
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4926
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4927
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4928
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4929
+	 *        then this method should be called immediately after the update query
4930
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4931
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4932
+	 *
4933
+	 * @param    EE_Base_Class $object
4934
+	 * @throws EE_Error
4935
+	 * @return \EE_Base_Class
4936
+	 */
4937
+	public function add_to_entity_map(EE_Base_Class $object)
4938
+	{
4939
+		$className = $this->_get_class_name();
4940
+		if (! $object instanceof $className) {
4941
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4942
+				is_object($object) ? get_class($object) : $object, $className));
4943
+		}
4944
+		/** @var $object EE_Base_Class */
4945
+		if (! $object->ID()) {
4946
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4947
+				"event_espresso"), get_class($this)));
4948
+		}
4949
+		// double check it's not already there
4950
+		$classInstance = $this->get_from_entity_map($object->ID());
4951
+		if ($classInstance) {
4952
+			return $classInstance;
4953
+		} else {
4954
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4955
+			return $object;
4956
+		}
4957
+	}
4958
+
4959
+
4960
+
4961
+	/**
4962
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4963
+	 * if no identifier is provided, then the entire entity map is emptied
4964
+	 *
4965
+	 * @param int|string $id the ID of the model object
4966
+	 * @return boolean
4967
+	 */
4968
+	public function clear_entity_map($id = null)
4969
+	{
4970
+		if (empty($id)) {
4971
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4972
+			return true;
4973
+		}
4974
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4975
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4976
+			return true;
4977
+		}
4978
+		return false;
4979
+	}
4980
+
4981
+
4982
+
4983
+	/**
4984
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4985
+	 * Given an array where keys are column (or column alias) names and values,
4986
+	 * returns an array of their corresponding field names and database values
4987
+	 *
4988
+	 * @param array $cols_n_values
4989
+	 * @return array
4990
+	 */
4991
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4992
+	{
4993
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4994
+	}
4995
+
4996
+
4997
+
4998
+	/**
4999
+	 * _deduce_fields_n_values_from_cols_n_values
5000
+	 * Given an array where keys are column (or column alias) names and values,
5001
+	 * returns an array of their corresponding field names and database values
5002
+	 *
5003
+	 * @param string $cols_n_values
5004
+	 * @return array
5005
+	 */
5006
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5007
+	{
5008
+		$this_model_fields_n_values = array();
5009
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5010
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5011
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5012
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5013
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5014
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5015
+					if (! $field_obj->is_db_only_field()) {
5016
+						//prepare field as if its coming from db
5017
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5018
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5019
+					}
5020
+				}
5021
+			} else {
5022
+				//the table's rows existed. Use their values
5023
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5024
+					if (! $field_obj->is_db_only_field()) {
5025
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5026
+							$cols_n_values, $field_obj->get_qualified_column(),
5027
+							$field_obj->get_table_column()
5028
+						);
5029
+					}
5030
+				}
5031
+			}
5032
+		}
5033
+		return $this_model_fields_n_values;
5034
+	}
5035
+
5036
+
5037
+
5038
+	/**
5039
+	 * @param $cols_n_values
5040
+	 * @param $qualified_column
5041
+	 * @param $regular_column
5042
+	 * @return null
5043
+	 */
5044
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5045
+	{
5046
+		$value = null;
5047
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5048
+		//does the field on the model relate to this column retrieved from the db?
5049
+		//or is it a db-only field? (not relating to the model)
5050
+		if (isset($cols_n_values[$qualified_column])) {
5051
+			$value = $cols_n_values[$qualified_column];
5052
+		} elseif (isset($cols_n_values[$regular_column])) {
5053
+			$value = $cols_n_values[$regular_column];
5054
+		}
5055
+		return $value;
5056
+	}
5057
+
5058
+
5059
+
5060
+	/**
5061
+	 * refresh_entity_map_from_db
5062
+	 * Makes sure the model object in the entity map at $id assumes the values
5063
+	 * of the database (opposite of EE_base_Class::save())
5064
+	 *
5065
+	 * @param int|string $id
5066
+	 * @return EE_Base_Class
5067
+	 * @throws \EE_Error
5068
+	 */
5069
+	public function refresh_entity_map_from_db($id)
5070
+	{
5071
+		$obj_in_map = $this->get_from_entity_map($id);
5072
+		if ($obj_in_map) {
5073
+			$wpdb_results = $this->_get_all_wpdb_results(
5074
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5075
+			);
5076
+			if ($wpdb_results && is_array($wpdb_results)) {
5077
+				$one_row = reset($wpdb_results);
5078
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5079
+					$obj_in_map->set_from_db($field_name, $db_value);
5080
+				}
5081
+				//clear the cache of related model objects
5082
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5083
+					$obj_in_map->clear_cache($relation_name, null, true);
5084
+				}
5085
+			}
5086
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5087
+			return $obj_in_map;
5088
+		} else {
5089
+			return $this->get_one_by_ID($id);
5090
+		}
5091
+	}
5092
+
5093
+
5094
+
5095
+	/**
5096
+	 * refresh_entity_map_with
5097
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5098
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5099
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5100
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5101
+	 *
5102
+	 * @param int|string    $id
5103
+	 * @param EE_Base_Class $replacing_model_obj
5104
+	 * @return \EE_Base_Class
5105
+	 * @throws \EE_Error
5106
+	 */
5107
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5108
+	{
5109
+		$obj_in_map = $this->get_from_entity_map($id);
5110
+		if ($obj_in_map) {
5111
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5112
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5113
+					$obj_in_map->set($field_name, $value);
5114
+				}
5115
+				//make the model object in the entity map's cache match the $replacing_model_obj
5116
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5117
+					$obj_in_map->clear_cache($relation_name, null, true);
5118
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5119
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5120
+					}
5121
+				}
5122
+			}
5123
+			return $obj_in_map;
5124
+		} else {
5125
+			$this->add_to_entity_map($replacing_model_obj);
5126
+			return $replacing_model_obj;
5127
+		}
5128
+	}
5129
+
5130
+
5131
+
5132
+	/**
5133
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5134
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5135
+	 * require_once($this->_getClassName().".class.php");
5136
+	 *
5137
+	 * @return string
5138
+	 */
5139
+	private function _get_class_name()
5140
+	{
5141
+		return "EE_" . $this->get_this_model_name();
5142
+	}
5143
+
5144
+
5145
+
5146
+	/**
5147
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5148
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5149
+	 * it would be 'Events'.
5150
+	 *
5151
+	 * @param int $quantity
5152
+	 * @return string
5153
+	 */
5154
+	public function item_name($quantity = 1)
5155
+	{
5156
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5157
+	}
5158
+
5159
+
5160
+
5161
+	/**
5162
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5163
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5164
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5165
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5166
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5167
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5168
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5169
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5170
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5171
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5172
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5173
+	 *        return $previousReturnValue.$returnString;
5174
+	 * }
5175
+	 * require('EEM_Answer.model.php');
5176
+	 * $answer=EEM_Answer::instance();
5177
+	 * echo $answer->my_callback('monkeys',100);
5178
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5179
+	 *
5180
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5181
+	 * @param array  $args       array of original arguments passed to the function
5182
+	 * @throws EE_Error
5183
+	 * @return mixed whatever the plugin which calls add_filter decides
5184
+	 */
5185
+	public function __call($methodName, $args)
5186
+	{
5187
+		$className = get_class($this);
5188
+		$tagName = "FHEE__{$className}__{$methodName}";
5189
+		if (! has_filter($tagName)) {
5190
+			throw new EE_Error(
5191
+				sprintf(
5192
+					__('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 );',
5193
+						'event_espresso'),
5194
+					$methodName,
5195
+					$className,
5196
+					$tagName,
5197
+					'<br />'
5198
+				)
5199
+			);
5200
+		}
5201
+		return apply_filters($tagName, null, $this, $args);
5202
+	}
5203
+
5204
+
5205
+
5206
+	/**
5207
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5208
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5209
+	 *
5210
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5211
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5212
+	 *                                                       the object's class name
5213
+	 *                                                       or object's ID
5214
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5215
+	 *                                                       exists in the database. If it does not, we add it
5216
+	 * @throws EE_Error
5217
+	 * @return EE_Base_Class
5218
+	 */
5219
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5220
+	{
5221
+		$className = $this->_get_class_name();
5222
+		if ($base_class_obj_or_id instanceof $className) {
5223
+			$model_object = $base_class_obj_or_id;
5224
+		} else {
5225
+			$primary_key_field = $this->get_primary_key_field();
5226
+			if (
5227
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5228
+				&& (
5229
+					is_int($base_class_obj_or_id)
5230
+					|| is_string($base_class_obj_or_id)
5231
+				)
5232
+			) {
5233
+				// assume it's an ID.
5234
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5235
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5236
+			} else if (
5237
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5238
+				&& is_string($base_class_obj_or_id)
5239
+			) {
5240
+				// assume its a string representation of the object
5241
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5242
+			} else {
5243
+				throw new EE_Error(
5244
+					sprintf(
5245
+						__(
5246
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5247
+							'event_espresso'
5248
+						),
5249
+						$base_class_obj_or_id,
5250
+						$this->_get_class_name(),
5251
+						print_r($base_class_obj_or_id, true)
5252
+					)
5253
+				);
5254
+			}
5255
+		}
5256
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5257
+			$model_object->save();
5258
+		}
5259
+		return $model_object;
5260
+	}
5261
+
5262
+
5263
+
5264
+	/**
5265
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5266
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5267
+	 * returns it ID.
5268
+	 *
5269
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5270
+	 * @return int|string depending on the type of this model object's ID
5271
+	 * @throws EE_Error
5272
+	 */
5273
+	public function ensure_is_ID($base_class_obj_or_id)
5274
+	{
5275
+		$className = $this->_get_class_name();
5276
+		if ($base_class_obj_or_id instanceof $className) {
5277
+			/** @var $base_class_obj_or_id EE_Base_Class */
5278
+			$id = $base_class_obj_or_id->ID();
5279
+		} elseif (is_int($base_class_obj_or_id)) {
5280
+			//assume it's an ID
5281
+			$id = $base_class_obj_or_id;
5282
+		} elseif (is_string($base_class_obj_or_id)) {
5283
+			//assume its a string representation of the object
5284
+			$id = $base_class_obj_or_id;
5285
+		} else {
5286
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5287
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5288
+				print_r($base_class_obj_or_id, true)));
5289
+		}
5290
+		return $id;
5291
+	}
5292
+
5293
+
5294
+
5295
+	/**
5296
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5297
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5298
+	 * been sanitized and converted into the appropriate domain.
5299
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5300
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5301
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5302
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5303
+	 * $EVT = EEM_Event::instance(); $old_setting =
5304
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5305
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5306
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5307
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5308
+	 *
5309
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5310
+	 * @return void
5311
+	 */
5312
+	public function assume_values_already_prepared_by_model_object(
5313
+		$values_already_prepared = self::not_prepared_by_model_object
5314
+	) {
5315
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5316
+	}
5317
+
5318
+
5319
+
5320
+	/**
5321
+	 * Read comments for assume_values_already_prepared_by_model_object()
5322
+	 *
5323
+	 * @return int
5324
+	 */
5325
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5326
+	{
5327
+		return $this->_values_already_prepared_by_model_object;
5328
+	}
5329
+
5330
+
5331
+
5332
+	/**
5333
+	 * Gets all the indexes on this model
5334
+	 *
5335
+	 * @return EE_Index[]
5336
+	 */
5337
+	public function indexes()
5338
+	{
5339
+		return $this->_indexes;
5340
+	}
5341
+
5342
+
5343
+
5344
+	/**
5345
+	 * Gets all the Unique Indexes on this model
5346
+	 *
5347
+	 * @return EE_Unique_Index[]
5348
+	 */
5349
+	public function unique_indexes()
5350
+	{
5351
+		$unique_indexes = array();
5352
+		foreach ($this->_indexes as $name => $index) {
5353
+			if ($index instanceof EE_Unique_Index) {
5354
+				$unique_indexes [$name] = $index;
5355
+			}
5356
+		}
5357
+		return $unique_indexes;
5358
+	}
5359
+
5360
+
5361
+
5362
+	/**
5363
+	 * Gets all the fields which, when combined, make the primary key.
5364
+	 * This is usually just an array with 1 element (the primary key), but in cases
5365
+	 * where there is no primary key, it's a combination of fields as defined
5366
+	 * on a primary index
5367
+	 *
5368
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5369
+	 * @throws \EE_Error
5370
+	 */
5371
+	public function get_combined_primary_key_fields()
5372
+	{
5373
+		foreach ($this->indexes() as $index) {
5374
+			if ($index instanceof EE_Primary_Key_Index) {
5375
+				return $index->fields();
5376
+			}
5377
+		}
5378
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5379
+	}
5380
+
5381
+
5382
+
5383
+	/**
5384
+	 * Used to build a primary key string (when the model has no primary key),
5385
+	 * which can be used a unique string to identify this model object.
5386
+	 *
5387
+	 * @param array $cols_n_values keys are field names, values are their values
5388
+	 * @return string
5389
+	 * @throws \EE_Error
5390
+	 */
5391
+	public function get_index_primary_key_string($cols_n_values)
5392
+	{
5393
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5394
+			$this->get_combined_primary_key_fields());
5395
+		return http_build_query($cols_n_values_for_primary_key_index);
5396
+	}
5397
+
5398
+
5399
+
5400
+	/**
5401
+	 * Gets the field values from the primary key string
5402
+	 *
5403
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5404
+	 * @param string $index_primary_key_string
5405
+	 * @return null|array
5406
+	 * @throws \EE_Error
5407
+	 */
5408
+	public function parse_index_primary_key_string($index_primary_key_string)
5409
+	{
5410
+		$key_fields = $this->get_combined_primary_key_fields();
5411
+		//check all of them are in the $id
5412
+		$key_vals_in_combined_pk = array();
5413
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5414
+		foreach ($key_fields as $key_field_name => $field_obj) {
5415
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5416
+				return null;
5417
+			}
5418
+		}
5419
+		return $key_vals_in_combined_pk;
5420
+	}
5421
+
5422
+
5423
+
5424
+	/**
5425
+	 * verifies that an array of key-value pairs for model fields has a key
5426
+	 * for each field comprising the primary key index
5427
+	 *
5428
+	 * @param array $key_vals
5429
+	 * @return boolean
5430
+	 * @throws \EE_Error
5431
+	 */
5432
+	public function has_all_combined_primary_key_fields($key_vals)
5433
+	{
5434
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5435
+		foreach ($keys_it_should_have as $key) {
5436
+			if (! isset($key_vals[$key])) {
5437
+				return false;
5438
+			}
5439
+		}
5440
+		return true;
5441
+	}
5442
+
5443
+
5444
+
5445
+	/**
5446
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5447
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5448
+	 *
5449
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5450
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5451
+	 * @throws EE_Error
5452
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5453
+	 *                                                              indexed)
5454
+	 */
5455
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5456
+	{
5457
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5458
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5459
+		} elseif (is_array($model_object_or_attributes_array)) {
5460
+			$attributes_array = $model_object_or_attributes_array;
5461
+		} else {
5462
+			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",
5463
+				"event_espresso"), $model_object_or_attributes_array));
5464
+		}
5465
+		//even copies obviously won't have the same ID, so remove the primary key
5466
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5467
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5468
+			unset($attributes_array[$this->primary_key_name()]);
5469
+		}
5470
+		if (isset($query_params[0])) {
5471
+			$query_params[0] = array_merge($attributes_array, $query_params);
5472
+		} else {
5473
+			$query_params[0] = $attributes_array;
5474
+		}
5475
+		return $this->get_all($query_params);
5476
+	}
5477
+
5478
+
5479
+
5480
+	/**
5481
+	 * Gets the first copy we find. See get_all_copies for more details
5482
+	 *
5483
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5484
+	 * @param array $query_params
5485
+	 * @return EE_Base_Class
5486
+	 * @throws \EE_Error
5487
+	 */
5488
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5489
+	{
5490
+		if (! is_array($query_params)) {
5491
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5492
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5493
+					gettype($query_params)), '4.6.0');
5494
+			$query_params = array();
5495
+		}
5496
+		$query_params['limit'] = 1;
5497
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5498
+		if (is_array($copies)) {
5499
+			return array_shift($copies);
5500
+		} else {
5501
+			return null;
5502
+		}
5503
+	}
5504
+
5505
+
5506
+
5507
+	/**
5508
+	 * Updates the item with the specified id. Ignores default query parameters because
5509
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5510
+	 *
5511
+	 * @param array      $fields_n_values keys are field names, values are their new values
5512
+	 * @param int|string $id              the value of the primary key to update
5513
+	 * @return int number of rows updated
5514
+	 * @throws \EE_Error
5515
+	 */
5516
+	public function update_by_ID($fields_n_values, $id)
5517
+	{
5518
+		$query_params = array(
5519
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5520
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5521
+		);
5522
+		return $this->update($fields_n_values, $query_params);
5523
+	}
5524
+
5525
+
5526
+
5527
+	/**
5528
+	 * Changes an operator which was supplied to the models into one usable in SQL
5529
+	 *
5530
+	 * @param string $operator_supplied
5531
+	 * @return string an operator which can be used in SQL
5532
+	 * @throws EE_Error
5533
+	 */
5534
+	private function _prepare_operator_for_sql($operator_supplied)
5535
+	{
5536
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5537
+			: null;
5538
+		if ($sql_operator) {
5539
+			return $sql_operator;
5540
+		} else {
5541
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5542
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5543
+		}
5544
+	}
5545
+
5546
+
5547
+
5548
+	/**
5549
+	 * Gets an array where keys are the primary keys and values are their 'names'
5550
+	 * (as determined by the model object's name() function, which is often overridden)
5551
+	 *
5552
+	 * @param array $query_params like get_all's
5553
+	 * @return string[]
5554
+	 * @throws \EE_Error
5555
+	 */
5556
+	public function get_all_names($query_params = array())
5557
+	{
5558
+		$objs = $this->get_all($query_params);
5559
+		$names = array();
5560
+		foreach ($objs as $obj) {
5561
+			$names[$obj->ID()] = $obj->name();
5562
+		}
5563
+		return $names;
5564
+	}
5565
+
5566
+
5567
+
5568
+	/**
5569
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5570
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5571
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5572
+	 * array_keys() on $model_objects.
5573
+	 *
5574
+	 * @param \EE_Base_Class[] $model_objects
5575
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5576
+	 *                                               in the returned array
5577
+	 * @return array
5578
+	 * @throws \EE_Error
5579
+	 */
5580
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5581
+	{
5582
+		if (! $this->has_primary_key_field()) {
5583
+			if (WP_DEBUG) {
5584
+				EE_Error::add_error(
5585
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5586
+					__FILE__,
5587
+					__FUNCTION__,
5588
+					__LINE__
5589
+				);
5590
+			}
5591
+		}
5592
+		$IDs = array();
5593
+		foreach ($model_objects as $model_object) {
5594
+			$id = $model_object->ID();
5595
+			if (! $id) {
5596
+				if ($filter_out_empty_ids) {
5597
+					continue;
5598
+				}
5599
+				if (WP_DEBUG) {
5600
+					EE_Error::add_error(
5601
+						__(
5602
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5603
+							'event_espresso'
5604
+						),
5605
+						__FILE__,
5606
+						__FUNCTION__,
5607
+						__LINE__
5608
+					);
5609
+				}
5610
+			}
5611
+			$IDs[] = $id;
5612
+		}
5613
+		return $IDs;
5614
+	}
5615
+
5616
+
5617
+
5618
+	/**
5619
+	 * Returns the string used in capabilities relating to this model. If there
5620
+	 * are no capabilities that relate to this model returns false
5621
+	 *
5622
+	 * @return string|false
5623
+	 */
5624
+	public function cap_slug()
5625
+	{
5626
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5627
+	}
5628
+
5629
+
5630
+
5631
+	/**
5632
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5633
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5634
+	 * only returns the cap restrictions array in that context (ie, the array
5635
+	 * at that key)
5636
+	 *
5637
+	 * @param string $context
5638
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5639
+	 * @throws \EE_Error
5640
+	 */
5641
+	public function cap_restrictions($context = EEM_Base::caps_read)
5642
+	{
5643
+		EEM_Base::verify_is_valid_cap_context($context);
5644
+		//check if we ought to run the restriction generator first
5645
+		if (
5646
+			isset($this->_cap_restriction_generators[$context])
5647
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5648
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5649
+		) {
5650
+			$this->_cap_restrictions[$context] = array_merge(
5651
+				$this->_cap_restrictions[$context],
5652
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5653
+			);
5654
+		}
5655
+		//and make sure we've finalized the construction of each restriction
5656
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5657
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5658
+				$where_conditions_obj->_finalize_construct($this);
5659
+			}
5660
+		}
5661
+		return $this->_cap_restrictions[$context];
5662
+	}
5663
+
5664
+
5665
+
5666
+	/**
5667
+	 * Indicating whether or not this model thinks its a wp core model
5668
+	 *
5669
+	 * @return boolean
5670
+	 */
5671
+	public function is_wp_core_model()
5672
+	{
5673
+		return $this->_wp_core_model;
5674
+	}
5675
+
5676
+
5677
+
5678
+	/**
5679
+	 * Gets all the caps that are missing which impose a restriction on
5680
+	 * queries made in this context
5681
+	 *
5682
+	 * @param string $context one of EEM_Base::caps_ constants
5683
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5684
+	 * @throws \EE_Error
5685
+	 */
5686
+	public function caps_missing($context = EEM_Base::caps_read)
5687
+	{
5688
+		$missing_caps = array();
5689
+		$cap_restrictions = $this->cap_restrictions($context);
5690
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5691
+			if (! EE_Capabilities::instance()
5692
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5693
+			) {
5694
+				$missing_caps[$cap] = $restriction_if_no_cap;
5695
+			}
5696
+		}
5697
+		return $missing_caps;
5698
+	}
5699
+
5700
+
5701
+
5702
+	/**
5703
+	 * Gets the mapping from capability contexts to action strings used in capability names
5704
+	 *
5705
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5706
+	 * one of 'read', 'edit', or 'delete'
5707
+	 */
5708
+	public function cap_contexts_to_cap_action_map()
5709
+	{
5710
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5711
+			$this);
5712
+	}
5713
+
5714
+
5715
+
5716
+	/**
5717
+	 * Gets the action string for the specified capability context
5718
+	 *
5719
+	 * @param string $context
5720
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5721
+	 * @throws \EE_Error
5722
+	 */
5723
+	public function cap_action_for_context($context)
5724
+	{
5725
+		$mapping = $this->cap_contexts_to_cap_action_map();
5726
+		if (isset($mapping[$context])) {
5727
+			return $mapping[$context];
5728
+		}
5729
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5730
+			return $action;
5731
+		}
5732
+		throw new EE_Error(
5733
+			sprintf(
5734
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5735
+				$context,
5736
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5737
+			)
5738
+		);
5739
+	}
5740
+
5741
+
5742
+
5743
+	/**
5744
+	 * Returns all the capability contexts which are valid when querying models
5745
+	 *
5746
+	 * @return array
5747
+	 */
5748
+	public static function valid_cap_contexts()
5749
+	{
5750
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5751
+			self::caps_read,
5752
+			self::caps_read_admin,
5753
+			self::caps_edit,
5754
+			self::caps_delete,
5755
+		));
5756
+	}
5757
+
5758
+
5759
+
5760
+	/**
5761
+	 * Returns all valid options for 'default_where_conditions'
5762
+	 *
5763
+	 * @return array
5764
+	 */
5765
+	public static function valid_default_where_conditions()
5766
+	{
5767
+		return array(
5768
+			EEM_Base::default_where_conditions_all,
5769
+			EEM_Base::default_where_conditions_this_only,
5770
+			EEM_Base::default_where_conditions_others_only,
5771
+			EEM_Base::default_where_conditions_minimum_all,
5772
+			EEM_Base::default_where_conditions_minimum_others,
5773
+			EEM_Base::default_where_conditions_none
5774
+		);
5775
+	}
5776
+
5777
+	// public static function default_where_conditions_full
5778
+	/**
5779
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5780
+	 *
5781
+	 * @param string $context
5782
+	 * @return bool
5783
+	 * @throws \EE_Error
5784
+	 */
5785
+	static public function verify_is_valid_cap_context($context)
5786
+	{
5787
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5788
+		if (in_array($context, $valid_cap_contexts)) {
5789
+			return true;
5790
+		} else {
5791
+			throw new EE_Error(
5792
+				sprintf(
5793
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5794
+						'event_espresso'),
5795
+					$context,
5796
+					'EEM_Base',
5797
+					implode(',', $valid_cap_contexts)
5798
+				)
5799
+			);
5800
+		}
5801
+	}
5802
+
5803
+
5804
+
5805
+	/**
5806
+	 * Clears all the models field caches. This is only useful when a sub-class
5807
+	 * might have added a field or something and these caches might be invalidated
5808
+	 */
5809
+	protected function _invalidate_field_caches()
5810
+	{
5811
+		$this->_cache_foreign_key_to_fields = array();
5812
+		$this->_cached_fields = null;
5813
+		$this->_cached_fields_non_db_only = null;
5814
+	}
5815
+
5816
+
5817
+
5818
+	/**
5819
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
5820
+	 * (eg "and", "or", "not").
5821
+	 *
5822
+	 * @return array
5823
+	 */
5824
+	public function logic_query_param_keys()
5825
+	{
5826
+		return $this->_logic_query_param_keys;
5827
+	}
5828
+
5829
+
5830
+
5831
+	/**
5832
+	 * Determines whether or not the where query param array key is for a logic query param.
5833
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5834
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5835
+	 *
5836
+	 * @param $query_param_key
5837
+	 * @return bool
5838
+	 */
5839
+	public function is_logic_query_param_key($query_param_key)
5840
+	{
5841
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5842
+			if ($query_param_key === $logic_query_param_key
5843
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
5844
+			) {
5845
+				return true;
5846
+			}
5847
+		}
5848
+		return false;
5849
+	}
5850 5850
 
5851 5851
 
5852 5852
 
Please login to merge, or discard this patch.
core/db_models/fields/EE_Post_Content_Field.php 2 patches
Indentation   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -8,133 +8,133 @@
 block discarded – undo
8 8
 class EE_Post_Content_Field extends EE_Text_Field_Base
9 9
 {
10 10
 
11
-    /**
12
-     * @param string $table_column
13
-     * @param string $nicename
14
-     * @param bool   $nullable
15
-     * @param null   $default_value
16
-     */
17
-    public function __construct($table_column, $nicename, $nullable, $default_value = null)
18
-    {
19
-        parent::__construct($table_column, $nicename, $nullable, $default_value);
20
-        $this->setSchemaType('object');
21
-    }
11
+	/**
12
+	 * @param string $table_column
13
+	 * @param string $nicename
14
+	 * @param bool   $nullable
15
+	 * @param null   $default_value
16
+	 */
17
+	public function __construct($table_column, $nicename, $nullable, $default_value = null)
18
+	{
19
+		parent::__construct($table_column, $nicename, $nullable, $default_value);
20
+		$this->setSchemaType('object');
21
+	}
22 22
 
23 23
 
24
-    /**
25
-     * removes all tags which a WP Post wouldn't allow in its content normally
26
-     *
27
-     * @param string $value
28
-     * @return string
29
-     */
30
-    function prepare_for_set($value)
31
-    {
32
-        if (! current_user_can('unfiltered_html')) {
33
-            $value = wp_kses("$value", wp_kses_allowed_html('post'));
34
-        }
35
-        return parent::prepare_for_set($value);
36
-    }
24
+	/**
25
+	 * removes all tags which a WP Post wouldn't allow in its content normally
26
+	 *
27
+	 * @param string $value
28
+	 * @return string
29
+	 */
30
+	function prepare_for_set($value)
31
+	{
32
+		if (! current_user_can('unfiltered_html')) {
33
+			$value = wp_kses("$value", wp_kses_allowed_html('post'));
34
+		}
35
+		return parent::prepare_for_set($value);
36
+	}
37 37
 
38
-    function prepare_for_set_from_db($value_found_in_db_for_model_object)
39
-    {
40
-        return $value_found_in_db_for_model_object;
41
-    }
38
+	function prepare_for_set_from_db($value_found_in_db_for_model_object)
39
+	{
40
+		return $value_found_in_db_for_model_object;
41
+	}
42 42
 
43 43
 
44 44
 
45
-    /**
46
-     * Runs the content through `the_content`, or if prepares the content for placing in a form input
47
-     * @param string $value_on_field_to_be_outputted
48
-     * @param string   $schema possible values: 'form_input' or null (if null, will run through 'the_content')
49
-     * @return string
50
-     * @throws EE_Error when WP_DEBUG is on and recursive calling is detected
51
-     */
52
-    public function prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema = null)
53
-    {
54
-        switch($schema){
55
-            case 'form_input':
56
-                return parent::prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema);
57
-            case 'the_content':
45
+	/**
46
+	 * Runs the content through `the_content`, or if prepares the content for placing in a form input
47
+	 * @param string $value_on_field_to_be_outputted
48
+	 * @param string   $schema possible values: 'form_input' or null (if null, will run through 'the_content')
49
+	 * @return string
50
+	 * @throws EE_Error when WP_DEBUG is on and recursive calling is detected
51
+	 */
52
+	public function prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema = null)
53
+	{
54
+		switch($schema){
55
+			case 'form_input':
56
+				return parent::prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema);
57
+			case 'the_content':
58 58
 
59
-                if(doing_filter( 'the_content')){
60
-                    if( defined('WP_DEBUG') && WP_DEBUG){
61
-                        throw new EE_Error(
62
-                            sprintf(
63
-                                esc_html__('You have recursively called "%1$s" with %2$s set to %3$s which uses "%2$s" filter. You should use it with %2$s "%3$s" instead here.', 'event_espresso'),
64
-                                'EE_Post_Content_Field::prepare_for_pretty_echoing',
65
-                                '$schema',
66
-                                'the_content',
67
-                                'the_content_wp_core_only'
68
-                            )
69
-                        );
70
-                    } else {
71
-                        return $this->prepare_for_pretty_echoing($value_on_field_to_be_outputted, 'the_content_wp_core_only');
72
-                    }
73
-                }
74
-                return apply_filters(
75
-                    'the_content',
76
-                    parent::prepare_for_pretty_echoing(
77
-                        $value_on_field_to_be_outputted,
78
-                        $schema
79
-                    )
80
-                );
81
-            case 'the_content_wp_core_only':
82
-            default:
83
-                self::_setup_the_content_wp_core_only_filters();
84
-                $return_value = apply_filters(
85
-                    'the_content_wp_core_only',
86
-                    parent::prepare_for_pretty_echoing(
87
-                        $value_on_field_to_be_outputted,
88
-                        $schema
89
-                    )
90
-                );
91
-                //ya know what? adding these filters is super fast. Let's just
92
-                //avoid needing to maintain global state and set this up as-needed
93
-                remove_all_filters('the_content_wp_core_only');
94
-                do_action( 'AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
95
-                return $return_value;
96
-        }
97
-    }
59
+				if(doing_filter( 'the_content')){
60
+					if( defined('WP_DEBUG') && WP_DEBUG){
61
+						throw new EE_Error(
62
+							sprintf(
63
+								esc_html__('You have recursively called "%1$s" with %2$s set to %3$s which uses "%2$s" filter. You should use it with %2$s "%3$s" instead here.', 'event_espresso'),
64
+								'EE_Post_Content_Field::prepare_for_pretty_echoing',
65
+								'$schema',
66
+								'the_content',
67
+								'the_content_wp_core_only'
68
+							)
69
+						);
70
+					} else {
71
+						return $this->prepare_for_pretty_echoing($value_on_field_to_be_outputted, 'the_content_wp_core_only');
72
+					}
73
+				}
74
+				return apply_filters(
75
+					'the_content',
76
+					parent::prepare_for_pretty_echoing(
77
+						$value_on_field_to_be_outputted,
78
+						$schema
79
+					)
80
+				);
81
+			case 'the_content_wp_core_only':
82
+			default:
83
+				self::_setup_the_content_wp_core_only_filters();
84
+				$return_value = apply_filters(
85
+					'the_content_wp_core_only',
86
+					parent::prepare_for_pretty_echoing(
87
+						$value_on_field_to_be_outputted,
88
+						$schema
89
+					)
90
+				);
91
+				//ya know what? adding these filters is super fast. Let's just
92
+				//avoid needing to maintain global state and set this up as-needed
93
+				remove_all_filters('the_content_wp_core_only');
94
+				do_action( 'AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
95
+				return $return_value;
96
+		}
97
+	}
98 98
 
99 99
 
100 100
 
101
-    /**
102
-     * Verifies we've setup the standard WP core filters on  'the_content_wp_core_only' filter
103
-     */
104
-    protected static function _setup_the_content_wp_core_only_filters()
105
-    {
106
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'run_shortcode'), 8);
107
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'autoembed'), 8);
108
-        add_filter('the_content_wp_core_only', 'wptexturize', 10);
109
-        add_filter('the_content_wp_core_only', 'wpautop', 10);
110
-        add_filter('the_content_wp_core_only', 'shortcode_unautop', 10);
111
-        add_filter('the_content_wp_core_only', 'prepend_attachment', 10);
112
-        if(function_exists('wp_make_content_images_responsive')) {
113
-            add_filter('the_content_wp_core_only', 'wp_make_content_images_responsive', 10);
114
-        }
115
-        add_filter('the_content_wp_core_only', 'do_shortcode', 11);
116
-        add_filter('the_content_wp_core_only', 'convert_smilies', 20);
117
-    }
101
+	/**
102
+	 * Verifies we've setup the standard WP core filters on  'the_content_wp_core_only' filter
103
+	 */
104
+	protected static function _setup_the_content_wp_core_only_filters()
105
+	{
106
+		add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'run_shortcode'), 8);
107
+		add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'autoembed'), 8);
108
+		add_filter('the_content_wp_core_only', 'wptexturize', 10);
109
+		add_filter('the_content_wp_core_only', 'wpautop', 10);
110
+		add_filter('the_content_wp_core_only', 'shortcode_unautop', 10);
111
+		add_filter('the_content_wp_core_only', 'prepend_attachment', 10);
112
+		if(function_exists('wp_make_content_images_responsive')) {
113
+			add_filter('the_content_wp_core_only', 'wp_make_content_images_responsive', 10);
114
+		}
115
+		add_filter('the_content_wp_core_only', 'do_shortcode', 11);
116
+		add_filter('the_content_wp_core_only', 'convert_smilies', 20);
117
+	}
118 118
 
119 119
 
120 120
 
121
-    public function getSchemaProperties()
122
-    {
123
-        return array(
124
-            'raw' => array(
125
-                'description' =>  sprintf(
126
-                    __('%s - the content as it exists in the database.', 'event_espresso'),
127
-                    $this->get_nicename()
128
-                ),
129
-                'type' => 'string'
130
-            ),
131
-            'rendered' => array(
132
-                'description' =>  sprintf(
133
-                    __('%s - the content rendered for display.', 'event_espresso'),
134
-                    $this->get_nicename()
135
-                ),
136
-                'type' => 'string'
137
-            )
138
-        );
139
-    }
121
+	public function getSchemaProperties()
122
+	{
123
+		return array(
124
+			'raw' => array(
125
+				'description' =>  sprintf(
126
+					__('%s - the content as it exists in the database.', 'event_espresso'),
127
+					$this->get_nicename()
128
+				),
129
+				'type' => 'string'
130
+			),
131
+			'rendered' => array(
132
+				'description' =>  sprintf(
133
+					__('%s - the content rendered for display.', 'event_espresso'),
134
+					$this->get_nicename()
135
+				),
136
+				'type' => 'string'
137
+			)
138
+		);
139
+	}
140 140
 }
141 141
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
      */
30 30
     function prepare_for_set($value)
31 31
     {
32
-        if (! current_user_can('unfiltered_html')) {
32
+        if ( ! current_user_can('unfiltered_html')) {
33 33
             $value = wp_kses("$value", wp_kses_allowed_html('post'));
34 34
         }
35 35
         return parent::prepare_for_set($value);
@@ -51,13 +51,13 @@  discard block
 block discarded – undo
51 51
      */
52 52
     public function prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema = null)
53 53
     {
54
-        switch($schema){
54
+        switch ($schema) {
55 55
             case 'form_input':
56 56
                 return parent::prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema);
57 57
             case 'the_content':
58 58
 
59
-                if(doing_filter( 'the_content')){
60
-                    if( defined('WP_DEBUG') && WP_DEBUG){
59
+                if (doing_filter('the_content')) {
60
+                    if (defined('WP_DEBUG') && WP_DEBUG) {
61 61
                         throw new EE_Error(
62 62
                             sprintf(
63 63
                                 esc_html__('You have recursively called "%1$s" with %2$s set to %3$s which uses "%2$s" filter. You should use it with %2$s "%3$s" instead here.', 'event_espresso'),
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
                 //ya know what? adding these filters is super fast. Let's just
92 92
                 //avoid needing to maintain global state and set this up as-needed
93 93
                 remove_all_filters('the_content_wp_core_only');
94
-                do_action( 'AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
94
+                do_action('AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
95 95
                 return $return_value;
96 96
         }
97 97
     }
@@ -103,13 +103,13 @@  discard block
 block discarded – undo
103 103
      */
104 104
     protected static function _setup_the_content_wp_core_only_filters()
105 105
     {
106
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'run_shortcode'), 8);
107
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'autoembed'), 8);
106
+        add_filter('the_content_wp_core_only', array($GLOBALS['wp_embed'], 'run_shortcode'), 8);
107
+        add_filter('the_content_wp_core_only', array($GLOBALS['wp_embed'], 'autoembed'), 8);
108 108
         add_filter('the_content_wp_core_only', 'wptexturize', 10);
109 109
         add_filter('the_content_wp_core_only', 'wpautop', 10);
110 110
         add_filter('the_content_wp_core_only', 'shortcode_unautop', 10);
111 111
         add_filter('the_content_wp_core_only', 'prepend_attachment', 10);
112
-        if(function_exists('wp_make_content_images_responsive')) {
112
+        if (function_exists('wp_make_content_images_responsive')) {
113 113
             add_filter('the_content_wp_core_only', 'wp_make_content_images_responsive', 10);
114 114
         }
115 115
         add_filter('the_content_wp_core_only', 'do_shortcode', 11);
Please login to merge, or discard this patch.
core/db_classes/EE_CPT_Base.class.php 2 patches
Indentation   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -36,9 +36,9 @@  discard block
 block discarded – undo
36 36
 	 */
37 37
 	protected $_feature_image = array();
38 38
 
39
-    /**
40
-     * @var WP_Post the WP_Post that corresponds with this CPT model object
41
-     */
39
+	/**
40
+	 * @var WP_Post the WP_Post that corresponds with this CPT model object
41
+	 */
42 42
 	protected $_wp_post;
43 43
 
44 44
 
@@ -46,75 +46,75 @@  discard block
 block discarded – undo
46 46
 
47 47
 
48 48
 
49
-    /**
50
-     * Returns the WP post associated with this CPT model object. If this CPT is saved, fetches it
51
-     * from the DB. Otherwise, create an unsaved WP_POst object. Caches the post internally.
52
-     * @return WP_Post
53
-     */
54
-    public function wp_post(){
55
-        global $wpdb;
56
-        if (! $this->_wp_post instanceof WP_Post) {
57
-            if ($this->ID()) {
58
-                $this->_wp_post = get_post($this->ID());
59
-            } else {
60
-                $simulated_db_result = new stdClass();
61
-                foreach($this->get_model()->field_settings(true) as $field_name => $field_obj){
62
-                    if ($this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name() === $wpdb->posts){
63
-                        $column = $field_obj->get_table_column();
64
-
65
-                        if($field_obj instanceof EE_Datetime_Field){
66
-                            $value_on_model_obj = $this->get_DateTime_object($field_name);
67
-                        } elseif( $field_obj->is_db_only_field()){
68
-                            $value_on_model_obj = $field_obj->get_default_value();
69
-                        } else {
70
-                            $value_on_model_obj = $this->get_raw($field_name);
71
-                        }
72
-                        $simulated_db_result->{$column} = $field_obj->prepare_for_use_in_db($value_on_model_obj);
73
-                    }
74
-                }
75
-                $this->_wp_post = new WP_Post($simulated_db_result);
76
-            }
77
-            //and let's make retrieving the EE CPT object easy too
78
-            $classname = get_class($this);
79
-            if (! isset($this->_wp_post->{$classname})) {
80
-                $this->_wp_post->{$classname} = $this;
81
-            }
82
-        }
83
-        return $this->_wp_post;
84
-    }
85
-
86
-    /**
87
-     * When fetching a new value for a post field that uses the global $post for rendering,
88
-     * set the global $post temporarily to be this model object; and afterwards restore it
89
-     * @param string $fieldname
90
-     * @param bool $pretty
91
-     * @param string $extra_cache_ref
92
-     * @return mixed
93
-     */
94
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
95
-    {
96
-        global $post;
97
-
98
-        if ( $pretty
99
-            && (
100
-                ! (
101
-                       $post instanceof WP_Post
102
-                       && $post->ID
103
-                   )
104
-                || (int)$post->ID !== $this->ID()
105
-             )
106
-            && $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field ) {
107
-            $old_post = $post;
108
-            $post = $this->wp_post();
109
-            $return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
110
-            $post = $old_post;
111
-        } else {
112
-            $return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
113
-        }
114
-        return $return_value;
115
-    }
116
-
117
-    /**
49
+	/**
50
+	 * Returns the WP post associated with this CPT model object. If this CPT is saved, fetches it
51
+	 * from the DB. Otherwise, create an unsaved WP_POst object. Caches the post internally.
52
+	 * @return WP_Post
53
+	 */
54
+	public function wp_post(){
55
+		global $wpdb;
56
+		if (! $this->_wp_post instanceof WP_Post) {
57
+			if ($this->ID()) {
58
+				$this->_wp_post = get_post($this->ID());
59
+			} else {
60
+				$simulated_db_result = new stdClass();
61
+				foreach($this->get_model()->field_settings(true) as $field_name => $field_obj){
62
+					if ($this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name() === $wpdb->posts){
63
+						$column = $field_obj->get_table_column();
64
+
65
+						if($field_obj instanceof EE_Datetime_Field){
66
+							$value_on_model_obj = $this->get_DateTime_object($field_name);
67
+						} elseif( $field_obj->is_db_only_field()){
68
+							$value_on_model_obj = $field_obj->get_default_value();
69
+						} else {
70
+							$value_on_model_obj = $this->get_raw($field_name);
71
+						}
72
+						$simulated_db_result->{$column} = $field_obj->prepare_for_use_in_db($value_on_model_obj);
73
+					}
74
+				}
75
+				$this->_wp_post = new WP_Post($simulated_db_result);
76
+			}
77
+			//and let's make retrieving the EE CPT object easy too
78
+			$classname = get_class($this);
79
+			if (! isset($this->_wp_post->{$classname})) {
80
+				$this->_wp_post->{$classname} = $this;
81
+			}
82
+		}
83
+		return $this->_wp_post;
84
+	}
85
+
86
+	/**
87
+	 * When fetching a new value for a post field that uses the global $post for rendering,
88
+	 * set the global $post temporarily to be this model object; and afterwards restore it
89
+	 * @param string $fieldname
90
+	 * @param bool $pretty
91
+	 * @param string $extra_cache_ref
92
+	 * @return mixed
93
+	 */
94
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
95
+	{
96
+		global $post;
97
+
98
+		if ( $pretty
99
+			&& (
100
+				! (
101
+					   $post instanceof WP_Post
102
+					   && $post->ID
103
+				   )
104
+				|| (int)$post->ID !== $this->ID()
105
+			 )
106
+			&& $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field ) {
107
+			$old_post = $post;
108
+			$post = $this->wp_post();
109
+			$return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
110
+			$post = $old_post;
111
+		} else {
112
+			$return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
113
+		}
114
+		return $return_value;
115
+	}
116
+
117
+	/**
118 118
 	 * Adds to the specified event category. If it category doesn't exist, creates it.
119 119
 	 * @param string $category_name
120 120
 	 * @param string $category_description    optional
@@ -399,14 +399,14 @@  discard block
 block discarded – undo
399 399
 
400 400
 
401 401
 
402
-    /**
403
-     * Don't serialize the WP Post. That's just duplicate data and we want to avoid recursion
404
-     * @return array
405
-     */
406
-    public function __sleep()
407
-    {
408
-        $properties_to_serialize = parent::__sleep();
409
-        $properties_to_serialize = array_diff( $properties_to_serialize, array('_wp_post'));
410
-        return $properties_to_serialize;
411
-    }
402
+	/**
403
+	 * Don't serialize the WP Post. That's just duplicate data and we want to avoid recursion
404
+	 * @return array
405
+	 */
406
+	public function __sleep()
407
+	{
408
+		$properties_to_serialize = parent::__sleep();
409
+		$properties_to_serialize = array_diff( $properties_to_serialize, array('_wp_post'));
410
+		return $properties_to_serialize;
411
+	}
412 412
 }
Please login to merge, or discard this patch.
Spacing   +67 added lines, -67 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1
-<?php if ( !defined( 'EVENT_ESPRESSO_VERSION' ) ) {
2
-	exit( 'No direct script access allowed' );
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -51,20 +51,20 @@  discard block
 block discarded – undo
51 51
      * from the DB. Otherwise, create an unsaved WP_POst object. Caches the post internally.
52 52
      * @return WP_Post
53 53
      */
54
-    public function wp_post(){
54
+    public function wp_post() {
55 55
         global $wpdb;
56
-        if (! $this->_wp_post instanceof WP_Post) {
56
+        if ( ! $this->_wp_post instanceof WP_Post) {
57 57
             if ($this->ID()) {
58 58
                 $this->_wp_post = get_post($this->ID());
59 59
             } else {
60 60
                 $simulated_db_result = new stdClass();
61
-                foreach($this->get_model()->field_settings(true) as $field_name => $field_obj){
62
-                    if ($this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name() === $wpdb->posts){
61
+                foreach ($this->get_model()->field_settings(true) as $field_name => $field_obj) {
62
+                    if ($this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name() === $wpdb->posts) {
63 63
                         $column = $field_obj->get_table_column();
64 64
 
65
-                        if($field_obj instanceof EE_Datetime_Field){
65
+                        if ($field_obj instanceof EE_Datetime_Field) {
66 66
                             $value_on_model_obj = $this->get_DateTime_object($field_name);
67
-                        } elseif( $field_obj->is_db_only_field()){
67
+                        } elseif ($field_obj->is_db_only_field()) {
68 68
                             $value_on_model_obj = $field_obj->get_default_value();
69 69
                         } else {
70 70
                             $value_on_model_obj = $this->get_raw($field_name);
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
             }
77 77
             //and let's make retrieving the EE CPT object easy too
78 78
             $classname = get_class($this);
79
-            if (! isset($this->_wp_post->{$classname})) {
79
+            if ( ! isset($this->_wp_post->{$classname})) {
80 80
                 $this->_wp_post->{$classname} = $this;
81 81
             }
82 82
         }
@@ -95,15 +95,15 @@  discard block
 block discarded – undo
95 95
     {
96 96
         global $post;
97 97
 
98
-        if ( $pretty
98
+        if ($pretty
99 99
             && (
100 100
                 ! (
101 101
                        $post instanceof WP_Post
102 102
                        && $post->ID
103 103
                    )
104
-                || (int)$post->ID !== $this->ID()
104
+                || (int) $post->ID !== $this->ID()
105 105
              )
106
-            && $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field ) {
106
+            && $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field) {
107 107
             $old_post = $post;
108 108
             $post = $this->wp_post();
109 109
             $return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
@@ -121,8 +121,8 @@  discard block
 block discarded – undo
121 121
 	 * @param int    $parent_term_taxonomy_id optional
122 122
 	 * @return EE_Term_Taxonomy
123 123
 	 */
124
-	function add_event_category( $category_name, $category_description = NULL, $parent_term_taxonomy_id = NULL ) {
125
-		return $this->get_model()->add_event_category( $this, $category_name, $category_description, $parent_term_taxonomy_id );
124
+	function add_event_category($category_name, $category_description = NULL, $parent_term_taxonomy_id = NULL) {
125
+		return $this->get_model()->add_event_category($this, $category_name, $category_description, $parent_term_taxonomy_id);
126 126
 	}
127 127
 
128 128
 
@@ -132,8 +132,8 @@  discard block
 block discarded – undo
132 132
 	 * @param string $category_name
133 133
 	 * @return bool
134 134
 	 */
135
-	function remove_event_category( $category_name ) {
136
-		return $this->get_model()->remove_event_category( $this, $category_name );
135
+	function remove_event_category($category_name) {
136
+		return $this->get_model()->remove_event_category($this, $category_name);
137 137
 	}
138 138
 
139 139
 
@@ -144,14 +144,14 @@  discard block
 block discarded – undo
144 144
 	 * @param EE_Term_Taxonomy $term_taxonomy
145 145
 	 * @return EE_Base_Class the relation was removed from
146 146
 	 */
147
-	function remove_relation_to_term_taxonomy( $term_taxonomy ) {
148
-		if ( !$term_taxonomy ) {
149
-			EE_Error::add_error( sprintf( __( "No Term_Taxonomy provided which to remove from model object of type %s and id %d", "event_espresso" ), get_class( $this ), $this->ID() ), __FILE__, __FUNCTION__, __LINE__ );
147
+	function remove_relation_to_term_taxonomy($term_taxonomy) {
148
+		if ( ! $term_taxonomy) {
149
+			EE_Error::add_error(sprintf(__("No Term_Taxonomy provided which to remove from model object of type %s and id %d", "event_espresso"), get_class($this), $this->ID()), __FILE__, __FUNCTION__, __LINE__);
150 150
 			return NULL;
151 151
 		}
152
-		$term_taxonomy->set_count( $term_taxonomy->count() - 1 );
152
+		$term_taxonomy->set_count($term_taxonomy->count() - 1);
153 153
 		$term_taxonomy->save();
154
-		return $this->_remove_relation_to( $term_taxonomy, 'Term_Taxonomy' );
154
+		return $this->_remove_relation_to($term_taxonomy, 'Term_Taxonomy');
155 155
 	}
156 156
 
157 157
 
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 	 * @return int
176 176
 	 */
177 177
 	public function parent() {
178
-		return $this->get( 'parent' );
178
+		return $this->get('parent');
179 179
 	}
180 180
 
181 181
 
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
 	 * @return string
186 186
 	 */
187 187
 	public function status() {
188
-		return $this->get( 'status' );
188
+		return $this->get('status');
189 189
 	}
190 190
 
191 191
 
@@ -193,8 +193,8 @@  discard block
 block discarded – undo
193 193
 	/**
194 194
 	 * @param string $status
195 195
 	 */
196
-	public function set_status( $status ) {
197
-		$this->set( 'status', $status );
196
+	public function set_status($status) {
197
+		$this->set('status', $status);
198 198
 	}
199 199
 
200 200
 
@@ -208,12 +208,12 @@  discard block
 block discarded – undo
208 208
 	 * @param string|array $attr Optional. Query string or array of attributes.
209 209
 	 * @return string HTML image element
210 210
 	 */
211
-	protected function _get_feature_image( $size, $attr ) {
211
+	protected function _get_feature_image($size, $attr) {
212 212
 		//first let's see if we already have the _feature_image property set AND if it has a cached element on it FOR the given size
213
-		$attr_key = is_array( $attr ) ? implode( '_', $attr ) : $attr;
214
-		$cache_key = is_array( $size ) ? implode( '_', $size ) . $attr_key : $size . $attr_key;
215
-		$this->_feature_image[ $cache_key ] = isset( $this->_feature_image[ $cache_key ] ) ? $this->_feature_image[ $cache_key ] : $this->get_model()->get_feature_image( $this->ID(), $size, $attr );
216
-		return $this->_feature_image[ $cache_key ];
213
+		$attr_key = is_array($attr) ? implode('_', $attr) : $attr;
214
+		$cache_key = is_array($size) ? implode('_', $size).$attr_key : $size.$attr_key;
215
+		$this->_feature_image[$cache_key] = isset($this->_feature_image[$cache_key]) ? $this->_feature_image[$cache_key] : $this->get_model()->get_feature_image($this->ID(), $size, $attr);
216
+		return $this->_feature_image[$cache_key];
217 217
 	}
218 218
 
219 219
 
@@ -224,8 +224,8 @@  discard block
 block discarded – undo
224 224
 	 * @param string|array $attr
225 225
 	 * @return string of html
226 226
 	 */
227
-	public function feature_image( $size = 'thumbnail', $attr = '' ) {
228
-		return $this->_get_feature_image( $size, $attr );
227
+	public function feature_image($size = 'thumbnail', $attr = '') {
228
+		return $this->_get_feature_image($size, $attr);
229 229
 	}
230 230
 
231 231
 
@@ -235,9 +235,9 @@  discard block
 block discarded – undo
235 235
 	 * @param  string|array $size can either be a string: 'thumbnail', 'medium', 'large', 'full' OR 2-item array representing width and height in pixels eg. array(32,32).
236 236
 	 * @return string|boolean          the url of the image or false if not found
237 237
 	 */
238
-	public function feature_image_url( $size = 'thumbnail' ) {
239
-		$attachment = wp_get_attachment_image_src( get_post_thumbnail_id( $this->ID() ), $size );
240
-		return !empty( $attachment ) ? $attachment[ 0 ] : FALSE;
238
+	public function feature_image_url($size = 'thumbnail') {
239
+		$attachment = wp_get_attachment_image_src(get_post_thumbnail_id($this->ID()), $size);
240
+		return ! empty($attachment) ? $attachment[0] : FALSE;
241 241
 	}
242 242
 
243 243
 
@@ -259,36 +259,36 @@  discard block
 block discarded – undo
259 259
 	 *                                 This array is INDEXED by RELATED OBJ NAME (so it corresponds with the obj_names sent);
260 260
 	 * @return void
261 261
 	 */
262
-	public function restore_revision( $revision_id, $related_obj_names = array(), $where_query = array() ) {
262
+	public function restore_revision($revision_id, $related_obj_names = array(), $where_query = array()) {
263 263
 		//get revision object
264
-		$revision_obj = $this->get_model()->get_one_by_ID( $revision_id );
265
-		if ( $revision_obj instanceof EE_CPT_Base ) {
264
+		$revision_obj = $this->get_model()->get_one_by_ID($revision_id);
265
+		if ($revision_obj instanceof EE_CPT_Base) {
266 266
 			//no related_obj_name so we assume we're saving a revision on this object.
267
-			if ( empty( $related_obj_names ) ) {
267
+			if (empty($related_obj_names)) {
268 268
 				$fields = $this->get_model()->get_meta_table_fields();
269
-				foreach ( $fields as $field ) {
270
-					$this->set( $field, $revision_obj->get( $field ) );
269
+				foreach ($fields as $field) {
270
+					$this->set($field, $revision_obj->get($field));
271 271
 				}
272 272
 				$this->save();
273 273
 			}
274
-			$related_obj_names = (array)$related_obj_names;
275
-			foreach ( $related_obj_names as $related_name ) {
274
+			$related_obj_names = (array) $related_obj_names;
275
+			foreach ($related_obj_names as $related_name) {
276 276
 				//related_obj_name so we're saving a revision on an object related to this object
277 277
 				//do we have $where_query params for this related object?  If we do then we include that.
278
-				$cols_n_values = isset( $where_query[ $related_name ] ) ? $where_query[ $related_name ] : array();
279
-				$where_params = !empty( $cols_n_values ) ? array( $cols_n_values ) : array();
280
-				$related_objs = $this->get_many_related( $related_name, $where_params );
281
-				$revision_related_objs = $revision_obj->get_many_related( $related_name, $where_params );
278
+				$cols_n_values = isset($where_query[$related_name]) ? $where_query[$related_name] : array();
279
+				$where_params = ! empty($cols_n_values) ? array($cols_n_values) : array();
280
+				$related_objs = $this->get_many_related($related_name, $where_params);
281
+				$revision_related_objs = $revision_obj->get_many_related($related_name, $where_params);
282 282
 				//load helper
283 283
 				//remove related objs from this object that are not in revision
284 284
 				//array_diff *should* work cause I think objects are indexed by ID?
285
-				$related_to_remove = EEH_Array::object_array_diff( $related_objs, $revision_related_objs );
286
-				foreach ( $related_to_remove as $rr ) {
287
-					$this->_remove_relation_to( $rr, $related_name, $cols_n_values );
285
+				$related_to_remove = EEH_Array::object_array_diff($related_objs, $revision_related_objs);
286
+				foreach ($related_to_remove as $rr) {
287
+					$this->_remove_relation_to($rr, $related_name, $cols_n_values);
288 288
 				}
289 289
 				//add all related objs attached to revision to this object
290
-				foreach ( $revision_related_objs as $r_obj ) {
291
-					$this->_add_relation_to( $r_obj, $related_name, $cols_n_values );
290
+				foreach ($revision_related_objs as $r_obj) {
291
+					$this->_add_relation_to($r_obj, $related_name, $cols_n_values);
292 292
 				}
293 293
 			}
294 294
 		}
@@ -304,8 +304,8 @@  discard block
 block discarded – undo
304 304
 	 * <li>If $single is set to false, or left blank, the function returns an array containing all values of the specified key.</li>
305 305
 	 * <li>If $single is set to true, the function returns the first value of the specified key (not in an array</li></ul>
306 306
 	 */
307
-	public function get_post_meta( $meta_key = NULL, $single = FALSE ) {
308
-		return get_post_meta( $this->ID(), $meta_key, $single );
307
+	public function get_post_meta($meta_key = NULL, $single = FALSE) {
308
+		return get_post_meta($this->ID(), $meta_key, $single);
309 309
 	}
310 310
 
311 311
 
@@ -317,11 +317,11 @@  discard block
 block discarded – undo
317 317
 	 * @param mixed  $prev_value
318 318
 	 * @return mixed Returns meta_id if the meta doesn't exist, otherwise returns true on success and false on failure. NOTE: If the meta_value passed to this function is the same as the value that is already in the database, this function returns false.
319 319
 	 */
320
-	public function update_post_meta( $meta_key, $meta_value, $prev_value = NULL ) {
321
-		if ( ! $this->ID() ) {
320
+	public function update_post_meta($meta_key, $meta_value, $prev_value = NULL) {
321
+		if ( ! $this->ID()) {
322 322
 			$this->save();
323 323
 		}
324
-		return update_post_meta( $this->ID(), $meta_key, $meta_value, $prev_value );
324
+		return update_post_meta($this->ID(), $meta_key, $meta_value, $prev_value);
325 325
 	}
326 326
 
327 327
 
@@ -333,11 +333,11 @@  discard block
 block discarded – undo
333 333
 	 * @param bool  $unique . If postmeta for this $meta_key already exists, whether to add an additional item or not
334 334
 	 * @return boolean Boolean true, except if the $unique argument was set to true and a custom field with the given key already exists, in which case false is returned.
335 335
 	 */
336
-	public function add_post_meta( $meta_key, $meta_value, $unique = FALSE ) {
337
-		if ( $this->ID() ) {
336
+	public function add_post_meta($meta_key, $meta_value, $unique = FALSE) {
337
+		if ($this->ID()) {
338 338
 			$this->save();
339 339
 		}
340
-		return add_post_meta( $this->ID(), $meta_key, $meta_value, $unique );
340
+		return add_post_meta($this->ID(), $meta_key, $meta_value, $unique);
341 341
 	}
342 342
 
343 343
 
@@ -349,13 +349,13 @@  discard block
 block discarded – undo
349 349
 	 * @param mixed $meta_value
350 350
 	 * @return boolean False for failure. True for success.
351 351
 	 */
352
-	public function delete_post_meta( $meta_key, $meta_value = '' ) {
353
-		if ( ! $this->ID() ) {
352
+	public function delete_post_meta($meta_key, $meta_value = '') {
353
+		if ( ! $this->ID()) {
354 354
 			//there are obviously no postmetas for this if it's not saved
355 355
 			//so let's just report this as a success
356 356
 			return true;
357 357
 		}
358
-		return delete_post_meta( $this->ID(), $meta_key, $meta_value );
358
+		return delete_post_meta($this->ID(), $meta_key, $meta_value);
359 359
 	}
360 360
 
361 361
 
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
 	 * @return string
366 366
 	 */
367 367
 	public function get_permalink() {
368
-		return get_permalink( $this->ID() );
368
+		return get_permalink($this->ID());
369 369
 	}
370 370
 
371 371
 
@@ -375,8 +375,8 @@  discard block
 block discarded – undo
375 375
 	 * @param array $query_params
376 376
 	 * @return EE_Term_Taxonomy
377 377
 	 */
378
-	public function term_taxonomies( $query_params = array() ) {
379
-		return $this->get_many_related( 'Term_Taxonomy', $query_params );
378
+	public function term_taxonomies($query_params = array()) {
379
+		return $this->get_many_related('Term_Taxonomy', $query_params);
380 380
 	}
381 381
 
382 382
 
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
     public function __sleep()
407 407
     {
408 408
         $properties_to_serialize = parent::__sleep();
409
-        $properties_to_serialize = array_diff( $properties_to_serialize, array('_wp_post'));
409
+        $properties_to_serialize = array_diff($properties_to_serialize, array('_wp_post'));
410 410
         return $properties_to_serialize;
411 411
     }
412 412
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 1 patch
Indentation   +2662 added lines, -2662 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
 do_action('AHEE_log', __FILE__, ' FILE LOADED', '');
5 5
 
@@ -25,2667 +25,2667 @@  discard block
 block discarded – undo
25 25
 abstract class EE_Base_Class
26 26
 {
27 27
 
28
-    /**
29
-     * This is an array of the original properties and values provided during construction
30
-     * of this model object. (keys are model field names, values are their values).
31
-     * This list is important to remember so that when we are merging data from the db, we know
32
-     * which values to override and which to not override.
33
-     *
34
-     * @var array
35
-     */
36
-    protected $_props_n_values_provided_in_constructor;
37
-
38
-    /**
39
-     * Timezone
40
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
41
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
42
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
43
-     * access to it.
44
-     *
45
-     * @var string
46
-     */
47
-    protected $_timezone;
48
-
49
-
50
-
51
-    /**
52
-     * date format
53
-     * pattern or format for displaying dates
54
-     *
55
-     * @var string $_dt_frmt
56
-     */
57
-    protected $_dt_frmt;
58
-
59
-
60
-
61
-    /**
62
-     * time format
63
-     * pattern or format for displaying time
64
-     *
65
-     * @var string $_tm_frmt
66
-     */
67
-    protected $_tm_frmt;
68
-
69
-
70
-
71
-    /**
72
-     * This property is for holding a cached array of object properties indexed by property name as the key.
73
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
74
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
75
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
76
-     *
77
-     * @var array
78
-     */
79
-    protected $_cached_properties = array();
80
-
81
-    /**
82
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
83
-     * single
84
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
85
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
86
-     * all others have an array)
87
-     *
88
-     * @var array
89
-     */
90
-    protected $_model_relations = array();
91
-
92
-    /**
93
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
94
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
95
-     *
96
-     * @var array
97
-     */
98
-    protected $_fields = array();
99
-
100
-    /**
101
-     * @var boolean indicating whether or not this model object is intended to ever be saved
102
-     * For example, we might create model objects intended to only be used for the duration
103
-     * of this request and to be thrown away, and if they were accidentally saved
104
-     * it would be a bug.
105
-     */
106
-    protected $_allow_persist = true;
107
-
108
-
109
-
110
-    /**
111
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
112
-     * play nice
113
-     *
114
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
115
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
116
-     *                                                         TXN_amount, QST_name, etc) and values are their values
117
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
118
-     *                                                         corresponding db model or not.
119
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
120
-     *                                                         be in when instantiating a EE_Base_Class object.
121
-     * @param array   $date_formats                            An array of date formats to set on construct where first
122
-     *                                                         value is the date_format and second value is the time
123
-     *                                                         format.
124
-     * @throws EE_Error
125
-     */
126
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
127
-    {
128
-        $className = get_class($this);
129
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
130
-        $model = $this->get_model();
131
-        $model_fields = $model->field_settings(false);
132
-        // ensure $fieldValues is an array
133
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
134
-        // EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
135
-        // verify client code has not passed any invalid field names
136
-        foreach ($fieldValues as $field_name => $field_value) {
137
-            if ( ! isset($model_fields[$field_name])) {
138
-                throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
139
-                    "event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
140
-            }
141
-        }
142
-        // EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
143
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
144
-        if ( ! empty($date_formats) && is_array($date_formats)) {
145
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
146
-        } else {
147
-            //set default formats for date and time
148
-            $this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
149
-            $this->_tm_frmt = (string)get_option('time_format', 'g:i a');
150
-        }
151
-        //if db model is instantiating
152
-        if ($bydb) {
153
-            //client code has indicated these field values are from the database
154
-            foreach ($model_fields as $fieldName => $field) {
155
-                $this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
156
-            }
157
-        } else {
158
-            //we're constructing a brand
159
-            //new instance of the model object. Generally, this means we'll need to do more field validation
160
-            foreach ($model_fields as $fieldName => $field) {
161
-                $this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
162
-            }
163
-        }
164
-        //remember what values were passed to this constructor
165
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
166
-        //remember in entity mapper
167
-        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
168
-            $model->add_to_entity_map($this);
169
-        }
170
-        //setup all the relations
171
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
172
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
173
-                $this->_model_relations[$relation_name] = null;
174
-            } else {
175
-                $this->_model_relations[$relation_name] = array();
176
-            }
177
-        }
178
-        /**
179
-         * Action done at the end of each model object construction
180
-         *
181
-         * @param EE_Base_Class $this the model object just created
182
-         */
183
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
184
-    }
185
-
186
-
187
-
188
-    /**
189
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
190
-     *
191
-     * @return boolean
192
-     */
193
-    public function allow_persist()
194
-    {
195
-        return $this->_allow_persist;
196
-    }
197
-
198
-
199
-
200
-    /**
201
-     * Sets whether or not this model object should be allowed to be saved to the DB.
202
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
203
-     * you got new information that somehow made you change your mind.
204
-     *
205
-     * @param boolean $allow_persist
206
-     * @return boolean
207
-     */
208
-    public function set_allow_persist($allow_persist)
209
-    {
210
-        return $this->_allow_persist = $allow_persist;
211
-    }
212
-
213
-
214
-
215
-    /**
216
-     * Gets the field's original value when this object was constructed during this request.
217
-     * This can be helpful when determining if a model object has changed or not
218
-     *
219
-     * @param string $field_name
220
-     * @return mixed|null
221
-     * @throws \EE_Error
222
-     */
223
-    public function get_original($field_name)
224
-    {
225
-        if (isset($this->_props_n_values_provided_in_constructor[$field_name])
226
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
227
-        ) {
228
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
229
-        } else {
230
-            return null;
231
-        }
232
-    }
233
-
234
-
235
-
236
-    /**
237
-     * @param EE_Base_Class $obj
238
-     * @return string
239
-     */
240
-    public function get_class($obj)
241
-    {
242
-        return get_class($obj);
243
-    }
244
-
245
-
246
-
247
-    /**
248
-     * Overrides parent because parent expects old models.
249
-     * This also doesn't do any validation, and won't work for serialized arrays
250
-     *
251
-     * @param    string $field_name
252
-     * @param    mixed  $field_value
253
-     * @param bool      $use_default
254
-     * @throws \EE_Error
255
-     */
256
-    public function set($field_name, $field_value, $use_default = false)
257
-    {
258
-        $field_obj = $this->get_model()->field_settings_for($field_name);
259
-        if ($field_obj instanceof EE_Model_Field_Base) {
260
-            //			if ( method_exists( $field_obj, 'set_timezone' )) {
261
-            if ($field_obj instanceof EE_Datetime_Field) {
262
-                $field_obj->set_timezone($this->_timezone);
263
-                $field_obj->set_date_format($this->_dt_frmt);
264
-                $field_obj->set_time_format($this->_tm_frmt);
265
-            }
266
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
267
-            //should the value be null?
268
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
269
-                $this->_fields[$field_name] = $field_obj->get_default_value();
270
-                /**
271
-                 * To save having to refactor all the models, if a default value is used for a
272
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
273
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
274
-                 * object.
275
-                 *
276
-                 * @since 4.6.10+
277
-                 */
278
-                if (
279
-                    $field_obj instanceof EE_Datetime_Field
280
-                    && $this->_fields[$field_name] !== null
281
-                    && ! $this->_fields[$field_name] instanceof DateTime
282
-                ) {
283
-                    empty($this->_fields[$field_name])
284
-                        ? $this->set($field_name, time())
285
-                        : $this->set($field_name, $this->_fields[$field_name]);
286
-                }
287
-            } else {
288
-                $this->_fields[$field_name] = $holder_of_value;
289
-            }
290
-            //if we're not in the constructor...
291
-            //now check if what we set was a primary key
292
-            if (
293
-                //note: props_n_values_provided_in_constructor is only set at the END of the constructor
294
-                $this->_props_n_values_provided_in_constructor
295
-                && $field_value
296
-                && $field_name === self::_get_primary_key_name(get_class($this))
297
-            ) {
298
-                //if so, we want all this object's fields to be filled either with
299
-                //what we've explicitly set on this model
300
-                //or what we have in the db
301
-                // echo "setting primary key!";
302
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
303
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
304
-                foreach ($fields_on_model as $field_obj) {
305
-                    if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
306
-                         && $field_obj->get_name() !== $field_name
307
-                    ) {
308
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
309
-                    }
310
-                }
311
-                //oh this model object has an ID? well make sure its in the entity mapper
312
-                $this->get_model()->add_to_entity_map($this);
313
-            }
314
-            //let's unset any cache for this field_name from the $_cached_properties property.
315
-            $this->_clear_cached_property($field_name);
316
-        } else {
317
-            throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
318
-                "event_espresso"), $field_name));
319
-        }
320
-    }
321
-
322
-
323
-
324
-    /**
325
-     * This sets the field value on the db column if it exists for the given $column_name or
326
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
327
-     *
328
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
329
-     * @param string $field_name  Must be the exact column name.
330
-     * @param mixed  $field_value The value to set.
331
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
332
-     * @throws \EE_Error
333
-     */
334
-    public function set_field_or_extra_meta($field_name, $field_value)
335
-    {
336
-        if ($this->get_model()->has_field($field_name)) {
337
-            $this->set($field_name, $field_value);
338
-            return true;
339
-        } else {
340
-            //ensure this object is saved first so that extra meta can be properly related.
341
-            $this->save();
342
-            return $this->update_extra_meta($field_name, $field_value);
343
-        }
344
-    }
345
-
346
-
347
-
348
-    /**
349
-     * This retrieves the value of the db column set on this class or if that's not present
350
-     * it will attempt to retrieve from extra_meta if found.
351
-     * Example Usage:
352
-     * Via EE_Message child class:
353
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
354
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
355
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
356
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
357
-     * value for those extra fields dynamically via the EE_message object.
358
-     *
359
-     * @param  string $field_name expecting the fully qualified field name.
360
-     * @return mixed|null  value for the field if found.  null if not found.
361
-     * @throws \EE_Error
362
-     */
363
-    public function get_field_or_extra_meta($field_name)
364
-    {
365
-        if ($this->get_model()->has_field($field_name)) {
366
-            $column_value = $this->get($field_name);
367
-        } else {
368
-            //This isn't a column in the main table, let's see if it is in the extra meta.
369
-            $column_value = $this->get_extra_meta($field_name, true, null);
370
-        }
371
-        return $column_value;
372
-    }
373
-
374
-
375
-
376
-    /**
377
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
378
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
379
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
380
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
381
-     *
382
-     * @access public
383
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
384
-     * @return void
385
-     * @throws \EE_Error
386
-     */
387
-    public function set_timezone($timezone = '')
388
-    {
389
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
390
-        //make sure we clear all cached properties because they won't be relevant now
391
-        $this->_clear_cached_properties();
392
-        //make sure we update field settings and the date for all EE_Datetime_Fields
393
-        $model_fields = $this->get_model()->field_settings(false);
394
-        foreach ($model_fields as $field_name => $field_obj) {
395
-            if ($field_obj instanceof EE_Datetime_Field) {
396
-                $field_obj->set_timezone($this->_timezone);
397
-                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
398
-                    $this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
399
-                }
400
-            }
401
-        }
402
-    }
403
-
404
-
405
-
406
-    /**
407
-     * This just returns whatever is set for the current timezone.
408
-     *
409
-     * @access public
410
-     * @return string timezone string
411
-     */
412
-    public function get_timezone()
413
-    {
414
-        return $this->_timezone;
415
-    }
416
-
417
-
418
-
419
-    /**
420
-     * This sets the internal date format to what is sent in to be used as the new default for the class
421
-     * internally instead of wp set date format options
422
-     *
423
-     * @since 4.6
424
-     * @param string $format should be a format recognizable by PHP date() functions.
425
-     */
426
-    public function set_date_format($format)
427
-    {
428
-        $this->_dt_frmt = $format;
429
-        //clear cached_properties because they won't be relevant now.
430
-        $this->_clear_cached_properties();
431
-    }
432
-
433
-
434
-
435
-    /**
436
-     * This sets the internal time format string to what is sent in to be used as the new default for the
437
-     * class internally instead of wp set time format options.
438
-     *
439
-     * @since 4.6
440
-     * @param string $format should be a format recognizable by PHP date() functions.
441
-     */
442
-    public function set_time_format($format)
443
-    {
444
-        $this->_tm_frmt = $format;
445
-        //clear cached_properties because they won't be relevant now.
446
-        $this->_clear_cached_properties();
447
-    }
448
-
449
-
450
-
451
-    /**
452
-     * This returns the current internal set format for the date and time formats.
453
-     *
454
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
455
-     *                             where the first value is the date format and the second value is the time format.
456
-     * @return mixed string|array
457
-     */
458
-    public function get_format($full = true)
459
-    {
460
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
461
-    }
462
-
463
-
464
-
465
-    /**
466
-     * cache
467
-     * stores the passed model object on the current model object.
468
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
469
-     *
470
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
471
-     *                                       'Registration' associated with this model object
472
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
473
-     *                                       that could be a payment or a registration)
474
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
475
-     *                                       items which will be stored in an array on this object
476
-     * @throws EE_Error
477
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
478
-     *                  related thing, no array)
479
-     */
480
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
481
-    {
482
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
483
-        if ( ! $object_to_cache instanceof EE_Base_Class) {
484
-            return false;
485
-        }
486
-        // also get "how" the object is related, or throw an error
487
-        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
488
-            throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
489
-                $relationName, get_class($this)));
490
-        }
491
-        // how many things are related ?
492
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
493
-            // if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
494
-            // so for these model objects just set it to be cached
495
-            $this->_model_relations[$relationName] = $object_to_cache;
496
-            $return = true;
497
-        } else {
498
-            // otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
499
-            // eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
500
-            if ( ! is_array($this->_model_relations[$relationName])) {
501
-                // if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
502
-                $this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
503
-                    ? array($this->_model_relations[$relationName]) : array();
504
-            }
505
-            // first check for a cache_id which is normally empty
506
-            if ( ! empty($cache_id)) {
507
-                // if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
508
-                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
509
-                $return = $cache_id;
510
-            } elseif ($object_to_cache->ID()) {
511
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
512
-                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
513
-                $return = $object_to_cache->ID();
514
-            } else {
515
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
516
-                $this->_model_relations[$relationName][] = $object_to_cache;
517
-                // move the internal pointer to the end of the array
518
-                end($this->_model_relations[$relationName]);
519
-                // and grab the key so that we can return it
520
-                $return = key($this->_model_relations[$relationName]);
521
-            }
522
-        }
523
-        return $return;
524
-    }
525
-
526
-
527
-
528
-    /**
529
-     * For adding an item to the cached_properties property.
530
-     *
531
-     * @access protected
532
-     * @param string      $fieldname the property item the corresponding value is for.
533
-     * @param mixed       $value     The value we are caching.
534
-     * @param string|null $cache_type
535
-     * @return void
536
-     * @throws \EE_Error
537
-     */
538
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
539
-    {
540
-        //first make sure this property exists
541
-        $this->get_model()->field_settings_for($fieldname);
542
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
543
-        $this->_cached_properties[$fieldname][$cache_type] = $value;
544
-    }
545
-
546
-
547
-
548
-    /**
549
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
550
-     * This also SETS the cache if we return the actual property!
551
-     *
552
-     * @param string $fieldname        the name of the property we're trying to retrieve
553
-     * @param bool   $pretty
554
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
555
-     *                                 (in cases where the same property may be used for different outputs
556
-     *                                 - i.e. datetime, money etc.)
557
-     *                                 It can also accept certain pre-defined "schema" strings
558
-     *                                 to define how to output the property.
559
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
560
-     * @return mixed                   whatever the value for the property is we're retrieving
561
-     * @throws \EE_Error
562
-     */
563
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
564
-    {
565
-        //verify the field exists
566
-        $this->get_model()->field_settings_for($fieldname);
567
-        $cache_type = $pretty ? 'pretty' : 'standard';
568
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
569
-        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
570
-            return $this->_cached_properties[$fieldname][$cache_type];
571
-        }
572
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
573
-        $this->_set_cached_property($fieldname, $value, $cache_type);
574
-        return $value;
575
-    }
576
-
577
-
578
-
579
-    /**
580
-     * If the cache didn't fetch the needed item, this fetches it.
581
-     * @param string $fieldname
582
-     * @param bool $pretty
583
-     * @param string $extra_cache_ref
584
-     * @return mixed
585
-     */
586
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
587
-    {
588
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
589
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
590
-        if ($field_obj instanceof EE_Datetime_Field) {
591
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
592
-        }
593
-        if ( ! isset($this->_fields[$fieldname])) {
594
-            $this->_fields[$fieldname] = null;
595
-        }
596
-        $value = $pretty
597
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
598
-            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
599
-        return $value;
600
-    }
601
-
602
-
603
-
604
-    /**
605
-     * set timezone, formats, and output for EE_Datetime_Field objects
606
-     *
607
-     * @param \EE_Datetime_Field $datetime_field
608
-     * @param bool               $pretty
609
-     * @param null $date_or_time
610
-     * @return void
611
-     * @throws \EE_Error
612
-     */
613
-    protected function _prepare_datetime_field(
614
-        EE_Datetime_Field $datetime_field,
615
-        $pretty = false,
616
-        $date_or_time = null
617
-    ) {
618
-        $datetime_field->set_timezone($this->_timezone);
619
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
620
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
621
-        //set the output returned
622
-        switch ($date_or_time) {
623
-            case 'D' :
624
-                $datetime_field->set_date_time_output('date');
625
-                break;
626
-            case 'T' :
627
-                $datetime_field->set_date_time_output('time');
628
-                break;
629
-            default :
630
-                $datetime_field->set_date_time_output();
631
-        }
632
-    }
633
-
634
-
635
-
636
-    /**
637
-     * This just takes care of clearing out the cached_properties
638
-     *
639
-     * @return void
640
-     */
641
-    protected function _clear_cached_properties()
642
-    {
643
-        $this->_cached_properties = array();
644
-    }
645
-
646
-
647
-
648
-    /**
649
-     * This just clears out ONE property if it exists in the cache
650
-     *
651
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
652
-     * @return void
653
-     */
654
-    protected function _clear_cached_property($property_name)
655
-    {
656
-        if (isset($this->_cached_properties[$property_name])) {
657
-            unset($this->_cached_properties[$property_name]);
658
-        }
659
-    }
660
-
661
-
662
-
663
-    /**
664
-     * Ensures that this related thing is a model object.
665
-     *
666
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
667
-     * @param string $model_name   name of the related thing, eg 'Attendee',
668
-     * @return EE_Base_Class
669
-     * @throws \EE_Error
670
-     */
671
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
672
-    {
673
-        $other_model_instance = self::_get_model_instance_with_name(
674
-            self::_get_model_classname($model_name),
675
-            $this->_timezone
676
-        );
677
-        return $other_model_instance->ensure_is_obj($object_or_id);
678
-    }
679
-
680
-
681
-
682
-    /**
683
-     * Forgets the cached model of the given relation Name. So the next time we request it,
684
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
685
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
686
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
687
-     *
688
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
689
-     *                                                     Eg 'Registration'
690
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
691
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
692
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
693
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
694
-     *                                                     this is HasMany or HABTM.
695
-     * @throws EE_Error
696
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
697
-     *                       relation from all
698
-     */
699
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
700
-    {
701
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
702
-        $index_in_cache = '';
703
-        if ( ! $relationship_to_model) {
704
-            throw new EE_Error(
705
-                sprintf(
706
-                    __("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
707
-                    $relationName,
708
-                    get_class($this)
709
-                )
710
-            );
711
-        }
712
-        if ($clear_all) {
713
-            $obj_removed = true;
714
-            $this->_model_relations[$relationName] = null;
715
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
716
-            $obj_removed = $this->_model_relations[$relationName];
717
-            $this->_model_relations[$relationName] = null;
718
-        } else {
719
-            if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
720
-                && $object_to_remove_or_index_into_array->ID()
721
-            ) {
722
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
723
-                if (is_array($this->_model_relations[$relationName])
724
-                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
725
-                ) {
726
-                    $index_found_at = null;
727
-                    //find this object in the array even though it has a different key
728
-                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
729
-                        if (
730
-                            $obj instanceof EE_Base_Class
731
-                            && (
732
-                                $obj == $object_to_remove_or_index_into_array
733
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
734
-                            )
735
-                        ) {
736
-                            $index_found_at = $index;
737
-                            break;
738
-                        }
739
-                    }
740
-                    if ($index_found_at) {
741
-                        $index_in_cache = $index_found_at;
742
-                    } else {
743
-                        //it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
744
-                        //if it wasn't in it to begin with. So we're done
745
-                        return $object_to_remove_or_index_into_array;
746
-                    }
747
-                }
748
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
749
-                //so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
750
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
751
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
752
-                        $index_in_cache = $index;
753
-                    }
754
-                }
755
-            } else {
756
-                $index_in_cache = $object_to_remove_or_index_into_array;
757
-            }
758
-            //supposedly we've found it. But it could just be that the client code
759
-            //provided a bad index/object
760
-            if (
761
-            isset(
762
-                $this->_model_relations[$relationName],
763
-                $this->_model_relations[$relationName][$index_in_cache]
764
-            )
765
-            ) {
766
-                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
767
-                unset($this->_model_relations[$relationName][$index_in_cache]);
768
-            } else {
769
-                //that thing was never cached anyways.
770
-                $obj_removed = null;
771
-            }
772
-        }
773
-        return $obj_removed;
774
-    }
775
-
776
-
777
-
778
-    /**
779
-     * update_cache_after_object_save
780
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
781
-     * obtained after being saved to the db
782
-     *
783
-     * @param string         $relationName       - the type of object that is cached
784
-     * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
785
-     * @param string         $current_cache_id   - the ID that was used when originally caching the object
786
-     * @return boolean TRUE on success, FALSE on fail
787
-     * @throws \EE_Error
788
-     */
789
-    public function update_cache_after_object_save(
790
-        $relationName,
791
-        EE_Base_Class $newly_saved_object,
792
-        $current_cache_id = ''
793
-    ) {
794
-        // verify that incoming object is of the correct type
795
-        $obj_class = 'EE_' . $relationName;
796
-        if ($newly_saved_object instanceof $obj_class) {
797
-            /* @type EE_Base_Class $newly_saved_object */
798
-            // now get the type of relation
799
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
800
-            // if this is a 1:1 relationship
801
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
802
-                // then just replace the cached object with the newly saved object
803
-                $this->_model_relations[$relationName] = $newly_saved_object;
804
-                return true;
805
-                // or if it's some kind of sordid feral polyamorous relationship...
806
-            } elseif (is_array($this->_model_relations[$relationName])
807
-                      && isset($this->_model_relations[$relationName][$current_cache_id])
808
-            ) {
809
-                // then remove the current cached item
810
-                unset($this->_model_relations[$relationName][$current_cache_id]);
811
-                // and cache the newly saved object using it's new ID
812
-                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
813
-                return true;
814
-            }
815
-        }
816
-        return false;
817
-    }
818
-
819
-
820
-
821
-    /**
822
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
823
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
824
-     *
825
-     * @param string $relationName
826
-     * @return EE_Base_Class
827
-     */
828
-    public function get_one_from_cache($relationName)
829
-    {
830
-        $cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
831
-            : null;
832
-        if (is_array($cached_array_or_object)) {
833
-            return array_shift($cached_array_or_object);
834
-        } else {
835
-            return $cached_array_or_object;
836
-        }
837
-    }
838
-
839
-
840
-
841
-    /**
842
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
843
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
844
-     *
845
-     * @param string $relationName
846
-     * @throws \EE_Error
847
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
848
-     */
849
-    public function get_all_from_cache($relationName)
850
-    {
851
-        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
852
-        // if the result is not an array, but exists, make it an array
853
-        $objects = is_array($objects) ? $objects : array($objects);
854
-        //bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
855
-        //basically, if this model object was stored in the session, and these cached model objects
856
-        //already have IDs, let's make sure they're in their model's entity mapper
857
-        //otherwise we will have duplicates next time we call
858
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
859
-        $model = EE_Registry::instance()->load_model($relationName);
860
-        foreach ($objects as $model_object) {
861
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
862
-                //ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
863
-                if ($model_object->ID()) {
864
-                    $model->add_to_entity_map($model_object);
865
-                }
866
-            } else {
867
-                throw new EE_Error(
868
-                    sprintf(
869
-                        __(
870
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
871
-                            'event_espresso'
872
-                        ),
873
-                        $relationName,
874
-                        gettype($model_object)
875
-                    )
876
-                );
877
-            }
878
-        }
879
-        return $objects;
880
-    }
881
-
882
-
883
-
884
-    /**
885
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
886
-     * matching the given query conditions.
887
-     *
888
-     * @param null  $field_to_order_by  What field is being used as the reference point.
889
-     * @param int   $limit              How many objects to return.
890
-     * @param array $query_params       Any additional conditions on the query.
891
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
892
-     *                                  you can indicate just the columns you want returned
893
-     * @return array|EE_Base_Class[]
894
-     * @throws \EE_Error
895
-     */
896
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
897
-    {
898
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
899
-            ? $this->get_model()->get_primary_key_field()->get_name()
900
-            : $field_to_order_by;
901
-        $current_value = ! empty($field) ? $this->get($field) : null;
902
-        if (empty($field) || empty($current_value)) {
903
-            return array();
904
-        }
905
-        return $this->get_model()->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
906
-    }
907
-
908
-
909
-
910
-    /**
911
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
912
-     * matching the given query conditions.
913
-     *
914
-     * @param null  $field_to_order_by  What field is being used as the reference point.
915
-     * @param int   $limit              How many objects to return.
916
-     * @param array $query_params       Any additional conditions on the query.
917
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
918
-     *                                  you can indicate just the columns you want returned
919
-     * @return array|EE_Base_Class[]
920
-     * @throws \EE_Error
921
-     */
922
-    public function previous_x(
923
-        $field_to_order_by = null,
924
-        $limit = 1,
925
-        $query_params = array(),
926
-        $columns_to_select = null
927
-    ) {
928
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
929
-            ? $this->get_model()->get_primary_key_field()->get_name()
930
-            : $field_to_order_by;
931
-        $current_value = ! empty($field) ? $this->get($field) : null;
932
-        if (empty($field) || empty($current_value)) {
933
-            return array();
934
-        }
935
-        return $this->get_model()->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
936
-    }
937
-
938
-
939
-
940
-    /**
941
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
942
-     * matching the given query conditions.
943
-     *
944
-     * @param null  $field_to_order_by  What field is being used as the reference point.
945
-     * @param array $query_params       Any additional conditions on the query.
946
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
947
-     *                                  you can indicate just the columns you want returned
948
-     * @return array|EE_Base_Class
949
-     * @throws \EE_Error
950
-     */
951
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
952
-    {
953
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
954
-            ? $this->get_model()->get_primary_key_field()->get_name()
955
-            : $field_to_order_by;
956
-        $current_value = ! empty($field) ? $this->get($field) : null;
957
-        if (empty($field) || empty($current_value)) {
958
-            return array();
959
-        }
960
-        return $this->get_model()->next($current_value, $field, $query_params, $columns_to_select);
961
-    }
962
-
963
-
964
-
965
-    /**
966
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
967
-     * matching the given query conditions.
968
-     *
969
-     * @param null  $field_to_order_by  What field is being used as the reference point.
970
-     * @param array $query_params       Any additional conditions on the query.
971
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
972
-     *                                  you can indicate just the column you want returned
973
-     * @return array|EE_Base_Class
974
-     * @throws \EE_Error
975
-     */
976
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
977
-    {
978
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
979
-            ? $this->get_model()->get_primary_key_field()->get_name()
980
-            : $field_to_order_by;
981
-        $current_value = ! empty($field) ? $this->get($field) : null;
982
-        if (empty($field) || empty($current_value)) {
983
-            return array();
984
-        }
985
-        return $this->get_model()->previous($current_value, $field, $query_params, $columns_to_select);
986
-    }
987
-
988
-
989
-
990
-    /**
991
-     * Overrides parent because parent expects old models.
992
-     * This also doesn't do any validation, and won't work for serialized arrays
993
-     *
994
-     * @param string $field_name
995
-     * @param mixed  $field_value_from_db
996
-     * @throws \EE_Error
997
-     */
998
-    public function set_from_db($field_name, $field_value_from_db)
999
-    {
1000
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1001
-        if ($field_obj instanceof EE_Model_Field_Base) {
1002
-            //you would think the DB has no NULLs for non-null label fields right? wrong!
1003
-            //eg, a CPT model object could have an entry in the posts table, but no
1004
-            //entry in the meta table. Meaning that all its columns in the meta table
1005
-            //are null! yikes! so when we find one like that, use defaults for its meta columns
1006
-            if ($field_value_from_db === null) {
1007
-                if ($field_obj->is_nullable()) {
1008
-                    //if the field allows nulls, then let it be null
1009
-                    $field_value = null;
1010
-                } else {
1011
-                    $field_value = $field_obj->get_default_value();
1012
-                }
1013
-            } else {
1014
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1015
-            }
1016
-            $this->_fields[$field_name] = $field_value;
1017
-            $this->_clear_cached_property($field_name);
1018
-        }
1019
-    }
1020
-
1021
-
1022
-
1023
-    /**
1024
-     * verifies that the specified field is of the correct type
1025
-     *
1026
-     * @param string $field_name
1027
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1028
-     *                                (in cases where the same property may be used for different outputs
1029
-     *                                - i.e. datetime, money etc.)
1030
-     * @return mixed
1031
-     * @throws \EE_Error
1032
-     */
1033
-    public function get($field_name, $extra_cache_ref = null)
1034
-    {
1035
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1036
-    }
1037
-
1038
-
1039
-
1040
-    /**
1041
-     * This method simply returns the RAW unprocessed value for the given property in this class
1042
-     *
1043
-     * @param  string $field_name A valid fieldname
1044
-     * @return mixed              Whatever the raw value stored on the property is.
1045
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1046
-     */
1047
-    public function get_raw($field_name)
1048
-    {
1049
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1050
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1051
-            ? $this->_fields[$field_name]->format('U')
1052
-            : $this->_fields[$field_name];
1053
-    }
1054
-
1055
-
1056
-
1057
-    /**
1058
-     * This is used to return the internal DateTime object used for a field that is a
1059
-     * EE_Datetime_Field.
1060
-     *
1061
-     * @param string $field_name               The field name retrieving the DateTime object.
1062
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1063
-     * @throws \EE_Error
1064
-     *                                         an error is set and false returned.  If the field IS an
1065
-     *                                         EE_Datetime_Field and but the field value is null, then
1066
-     *                                         just null is returned (because that indicates that likely
1067
-     *                                         this field is nullable).
1068
-     */
1069
-    public function get_DateTime_object($field_name)
1070
-    {
1071
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1072
-        if ( ! $field_settings instanceof EE_Datetime_Field) {
1073
-            EE_Error::add_error(
1074
-                sprintf(
1075
-                    __(
1076
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1077
-                        'event_espresso'
1078
-                    ),
1079
-                    $field_name
1080
-                ),
1081
-                __FILE__,
1082
-                __FUNCTION__,
1083
-                __LINE__
1084
-            );
1085
-            return false;
1086
-        }
1087
-        return $this->_fields[$field_name];
1088
-    }
1089
-
1090
-
1091
-
1092
-    /**
1093
-     * To be used in template to immediately echo out the value, and format it for output.
1094
-     * Eg, should call stripslashes and whatnot before echoing
1095
-     *
1096
-     * @param string $field_name      the name of the field as it appears in the DB
1097
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1098
-     *                                (in cases where the same property may be used for different outputs
1099
-     *                                - i.e. datetime, money etc.)
1100
-     * @return void
1101
-     * @throws \EE_Error
1102
-     */
1103
-    public function e($field_name, $extra_cache_ref = null)
1104
-    {
1105
-        echo $this->get_pretty($field_name, $extra_cache_ref);
1106
-    }
1107
-
1108
-
1109
-
1110
-    /**
1111
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1112
-     * can be easily used as the value of form input.
1113
-     *
1114
-     * @param string $field_name
1115
-     * @return void
1116
-     * @throws \EE_Error
1117
-     */
1118
-    public function f($field_name)
1119
-    {
1120
-        $this->e($field_name, 'form_input');
1121
-    }
1122
-
1123
-
1124
-
1125
-    /**
1126
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1127
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1128
-     * to see what options are available.
1129
-     * @param string $field_name
1130
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1131
-     *                                (in cases where the same property may be used for different outputs
1132
-     *                                - i.e. datetime, money etc.)
1133
-     * @return mixed
1134
-     * @throws \EE_Error
1135
-     */
1136
-    public function get_pretty($field_name, $extra_cache_ref = null)
1137
-    {
1138
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1139
-    }
1140
-
1141
-
1142
-
1143
-    /**
1144
-     * This simply returns the datetime for the given field name
1145
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1146
-     * (and the equivalent e_date, e_time, e_datetime).
1147
-     *
1148
-     * @access   protected
1149
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1150
-     * @param string   $dt_frmt      valid datetime format used for date
1151
-     *                               (if '' then we just use the default on the field,
1152
-     *                               if NULL we use the last-used format)
1153
-     * @param string   $tm_frmt      Same as above except this is for time format
1154
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1155
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1156
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1157
-     *                               if field is not a valid dtt field, or void if echoing
1158
-     * @throws \EE_Error
1159
-     */
1160
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1161
-    {
1162
-        // clear cached property
1163
-        $this->_clear_cached_property($field_name);
1164
-        //reset format properties because they are used in get()
1165
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1166
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1167
-        if ($echo) {
1168
-            $this->e($field_name, $date_or_time);
1169
-            return '';
1170
-        }
1171
-        return $this->get($field_name, $date_or_time);
1172
-    }
1173
-
1174
-
1175
-
1176
-    /**
1177
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1178
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1179
-     * other echoes the pretty value for dtt)
1180
-     *
1181
-     * @param  string $field_name name of model object datetime field holding the value
1182
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1183
-     * @return string            datetime value formatted
1184
-     * @throws \EE_Error
1185
-     */
1186
-    public function get_date($field_name, $format = '')
1187
-    {
1188
-        return $this->_get_datetime($field_name, $format, null, 'D');
1189
-    }
1190
-
1191
-
1192
-
1193
-    /**
1194
-     * @param      $field_name
1195
-     * @param string $format
1196
-     * @throws \EE_Error
1197
-     */
1198
-    public function e_date($field_name, $format = '')
1199
-    {
1200
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1201
-    }
1202
-
1203
-
1204
-
1205
-    /**
1206
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1207
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1208
-     * other echoes the pretty value for dtt)
1209
-     *
1210
-     * @param  string $field_name name of model object datetime field holding the value
1211
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1212
-     * @return string             datetime value formatted
1213
-     * @throws \EE_Error
1214
-     */
1215
-    public function get_time($field_name, $format = '')
1216
-    {
1217
-        return $this->_get_datetime($field_name, null, $format, 'T');
1218
-    }
1219
-
1220
-
1221
-
1222
-    /**
1223
-     * @param      $field_name
1224
-     * @param string $format
1225
-     * @throws \EE_Error
1226
-     */
1227
-    public function e_time($field_name, $format = '')
1228
-    {
1229
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1230
-    }
1231
-
1232
-
1233
-
1234
-    /**
1235
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1236
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1237
-     * other echoes the pretty value for dtt)
1238
-     *
1239
-     * @param  string $field_name name of model object datetime field holding the value
1240
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1241
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1242
-     * @return string             datetime value formatted
1243
-     * @throws \EE_Error
1244
-     */
1245
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1246
-    {
1247
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1248
-    }
1249
-
1250
-
1251
-
1252
-    /**
1253
-     * @param string $field_name
1254
-     * @param string $dt_frmt
1255
-     * @param string $tm_frmt
1256
-     * @throws \EE_Error
1257
-     */
1258
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1259
-    {
1260
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1261
-    }
1262
-
1263
-
1264
-
1265
-    /**
1266
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1267
-     *
1268
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1269
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1270
-     *                           on the object will be used.
1271
-     * @return string Date and time string in set locale or false if no field exists for the given
1272
-     * @throws \EE_Error
1273
-     *                           field name.
1274
-     */
1275
-    public function get_i18n_datetime($field_name, $format = '')
1276
-    {
1277
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1278
-        return date_i18n(
1279
-            $format,
1280
-            EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1281
-        );
1282
-    }
1283
-
1284
-
1285
-
1286
-    /**
1287
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1288
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1289
-     * thrown.
1290
-     *
1291
-     * @param  string $field_name The field name being checked
1292
-     * @throws EE_Error
1293
-     * @return EE_Datetime_Field
1294
-     */
1295
-    protected function _get_dtt_field_settings($field_name)
1296
-    {
1297
-        $field = $this->get_model()->field_settings_for($field_name);
1298
-        //check if field is dtt
1299
-        if ($field instanceof EE_Datetime_Field) {
1300
-            return $field;
1301
-        } else {
1302
-            throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1303
-                'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1304
-        }
1305
-    }
1306
-
1307
-
1308
-
1309
-
1310
-    /**
1311
-     * NOTE ABOUT BELOW:
1312
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1313
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1314
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1315
-     * method and make sure you send the entire datetime value for setting.
1316
-     */
1317
-    /**
1318
-     * sets the time on a datetime property
1319
-     *
1320
-     * @access protected
1321
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1322
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1323
-     * @throws \EE_Error
1324
-     */
1325
-    protected function _set_time_for($time, $fieldname)
1326
-    {
1327
-        $this->_set_date_time('T', $time, $fieldname);
1328
-    }
1329
-
1330
-
1331
-
1332
-    /**
1333
-     * sets the date on a datetime property
1334
-     *
1335
-     * @access protected
1336
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1337
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1338
-     * @throws \EE_Error
1339
-     */
1340
-    protected function _set_date_for($date, $fieldname)
1341
-    {
1342
-        $this->_set_date_time('D', $date, $fieldname);
1343
-    }
1344
-
1345
-
1346
-
1347
-    /**
1348
-     * This takes care of setting a date or time independently on a given model object property. This method also
1349
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1350
-     *
1351
-     * @access protected
1352
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1353
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1354
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1355
-     *                                        EE_Datetime_Field property)
1356
-     * @throws \EE_Error
1357
-     */
1358
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1359
-    {
1360
-        $field = $this->_get_dtt_field_settings($fieldname);
1361
-        $field->set_timezone($this->_timezone);
1362
-        $field->set_date_format($this->_dt_frmt);
1363
-        $field->set_time_format($this->_tm_frmt);
1364
-        switch ($what) {
1365
-            case 'T' :
1366
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1367
-                    $datetime_value,
1368
-                    $this->_fields[$fieldname]
1369
-                );
1370
-                break;
1371
-            case 'D' :
1372
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1373
-                    $datetime_value,
1374
-                    $this->_fields[$fieldname]
1375
-                );
1376
-                break;
1377
-            case 'B' :
1378
-                $this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1379
-                break;
1380
-        }
1381
-        $this->_clear_cached_property($fieldname);
1382
-    }
1383
-
1384
-
1385
-
1386
-    /**
1387
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1388
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1389
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1390
-     * that could lead to some unexpected results!
1391
-     *
1392
-     * @access public
1393
-     * @param string               $field_name This is the name of the field on the object that contains the date/time
1394
-     *                                         value being returned.
1395
-     * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1396
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1397
-     * @param string               $prepend    You can include something to prepend on the timestamp
1398
-     * @param string               $append     You can include something to append on the timestamp
1399
-     * @throws EE_Error
1400
-     * @return string timestamp
1401
-     */
1402
-    public function display_in_my_timezone(
1403
-        $field_name,
1404
-        $callback = 'get_datetime',
1405
-        $args = null,
1406
-        $prepend = '',
1407
-        $append = ''
1408
-    ) {
1409
-        $timezone = EEH_DTT_Helper::get_timezone();
1410
-        if ($timezone === $this->_timezone) {
1411
-            return '';
1412
-        }
1413
-        $original_timezone = $this->_timezone;
1414
-        $this->set_timezone($timezone);
1415
-        $fn = (array)$field_name;
1416
-        $args = array_merge($fn, (array)$args);
1417
-        if ( ! method_exists($this, $callback)) {
1418
-            throw new EE_Error(
1419
-                sprintf(
1420
-                    __(
1421
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1422
-                        'event_espresso'
1423
-                    ),
1424
-                    $callback
1425
-                )
1426
-            );
1427
-        }
1428
-        $args = (array)$args;
1429
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1430
-        $this->set_timezone($original_timezone);
1431
-        return $return;
1432
-    }
1433
-
1434
-
1435
-
1436
-    /**
1437
-     * Deletes this model object.
1438
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1439
-     * override
1440
-     * `EE_Base_Class::_delete` NOT this class.
1441
-     *
1442
-     * @return boolean | int
1443
-     * @throws \EE_Error
1444
-     */
1445
-    public function delete()
1446
-    {
1447
-        /**
1448
-         * Called just before the `EE_Base_Class::_delete` method call.
1449
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1450
-         * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1451
-         * soft deletes (trash) the object and does not permanently delete it.
1452
-         *
1453
-         * @param EE_Base_Class $model_object about to be 'deleted'
1454
-         */
1455
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1456
-        $result = $this->_delete();
1457
-        /**
1458
-         * Called just after the `EE_Base_Class::_delete` method call.
1459
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1460
-         * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1461
-         * soft deletes (trash) the object and does not permanently delete it.
1462
-         *
1463
-         * @param EE_Base_Class $model_object that was just 'deleted'
1464
-         * @param boolean       $result
1465
-         */
1466
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1467
-        return $result;
1468
-    }
1469
-
1470
-
1471
-
1472
-    /**
1473
-     * Calls the specific delete method for the instantiated class.
1474
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1475
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1476
-     * `EE_Base_Class::delete`
1477
-     *
1478
-     * @return bool|int
1479
-     * @throws \EE_Error
1480
-     */
1481
-    protected function _delete()
1482
-    {
1483
-        return $this->delete_permanently();
1484
-    }
1485
-
1486
-
1487
-
1488
-    /**
1489
-     * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1490
-     * error)
1491
-     *
1492
-     * @return bool | int
1493
-     * @throws \EE_Error
1494
-     */
1495
-    public function delete_permanently()
1496
-    {
1497
-        /**
1498
-         * Called just before HARD deleting a model object
1499
-         *
1500
-         * @param EE_Base_Class $model_object about to be 'deleted'
1501
-         */
1502
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1503
-        $model = $this->get_model();
1504
-        $result = $model->delete_permanently_by_ID($this->ID());
1505
-        $this->refresh_cache_of_related_objects();
1506
-        /**
1507
-         * Called just after HARD deleting a model object
1508
-         *
1509
-         * @param EE_Base_Class $model_object that was just 'deleted'
1510
-         * @param boolean       $result
1511
-         */
1512
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1513
-        return $result;
1514
-    }
1515
-
1516
-
1517
-
1518
-    /**
1519
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1520
-     * related model objects
1521
-     *
1522
-     * @throws \EE_Error
1523
-     */
1524
-    public function refresh_cache_of_related_objects()
1525
-    {
1526
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1527
-            if ( ! empty($this->_model_relations[$relation_name])) {
1528
-                $related_objects = $this->_model_relations[$relation_name];
1529
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1530
-                    //this relation only stores a single model object, not an array
1531
-                    //but let's make it consistent
1532
-                    $related_objects = array($related_objects);
1533
-                }
1534
-                foreach ($related_objects as $related_object) {
1535
-                    //only refresh their cache if they're in memory
1536
-                    if ($related_object instanceof EE_Base_Class) {
1537
-                        $related_object->clear_cache($this->get_model()->get_this_model_name(), $this);
1538
-                    }
1539
-                }
1540
-            }
1541
-        }
1542
-    }
1543
-
1544
-
1545
-
1546
-    /**
1547
-     *        Saves this object to the database. An array may be supplied to set some values on this
1548
-     * object just before saving.
1549
-     *
1550
-     * @access public
1551
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1552
-     *                                 if provided during the save() method (often client code will change the fields'
1553
-     *                                 values before calling save)
1554
-     * @throws \EE_Error
1555
-     * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1556
-     *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1557
-     */
1558
-    public function save($set_cols_n_values = array())
1559
-    {
1560
-        /**
1561
-         * Filters the fields we're about to save on the model object
1562
-         *
1563
-         * @param array         $set_cols_n_values
1564
-         * @param EE_Base_Class $model_object
1565
-         */
1566
-        $set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1567
-            $this);
1568
-        //set attributes as provided in $set_cols_n_values
1569
-        foreach ($set_cols_n_values as $column => $value) {
1570
-            $this->set($column, $value);
1571
-        }
1572
-        /**
1573
-         * Saving a model object.
1574
-         * Before we perform a save, this action is fired.
1575
-         *
1576
-         * @param EE_Base_Class $model_object the model object about to be saved.
1577
-         */
1578
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1579
-        if ( ! $this->allow_persist()) {
1580
-            return 0;
1581
-        }
1582
-        //now get current attribute values
1583
-        $save_cols_n_values = $this->_fields;
1584
-        //if the object already has an ID, update it. Otherwise, insert it
1585
-        //also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1586
-        $old_assumption_concerning_value_preparation = $this->get_model()
1587
-                                                            ->get_assumption_concerning_values_already_prepared_by_model_object();
1588
-        $this->get_model()->assume_values_already_prepared_by_model_object(true);
1589
-        //does this model have an autoincrement PK?
1590
-        if ($this->get_model()->has_primary_key_field()) {
1591
-            if ($this->get_model()->get_primary_key_field()->is_auto_increment()) {
1592
-                //ok check if it's set, if so: update; if not, insert
1593
-                if ( ! empty($save_cols_n_values[self::_get_primary_key_name(get_class($this))])) {
1594
-                    $results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1595
-                } else {
1596
-                    unset($save_cols_n_values[self::_get_primary_key_name(get_class($this))]);
1597
-                    $results = $this->get_model()->insert($save_cols_n_values);
1598
-                    if ($results) {
1599
-                        //if successful, set the primary key
1600
-                        //but don't use the normal SET method, because it will check if
1601
-                        //an item with the same ID exists in the mapper & db, then
1602
-                        //will find it in the db (because we just added it) and THAT object
1603
-                        //will get added to the mapper before we can add this one!
1604
-                        //but if we just avoid using the SET method, all that headache can be avoided
1605
-                        $pk_field_name = self::_get_primary_key_name(get_class($this));
1606
-                        $this->_fields[$pk_field_name] = $results;
1607
-                        $this->_clear_cached_property($pk_field_name);
1608
-                        $this->get_model()->add_to_entity_map($this);
1609
-                        $this->_update_cached_related_model_objs_fks();
1610
-                    }
1611
-                }
1612
-            } else {//PK is NOT auto-increment
1613
-                //so check if one like it already exists in the db
1614
-                if ($this->get_model()->exists_by_ID($this->ID())) {
1615
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1616
-                        throw new EE_Error(
1617
-                            sprintf(
1618
-                                __('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1619
-                                    'event_espresso'),
1620
-                                get_class($this),
1621
-                                get_class($this->get_model()) . '::instance()->add_to_entity_map()',
1622
-                                get_class($this->get_model()) . '::instance()->get_one_by_ID()',
1623
-                                '<br />'
1624
-                            )
1625
-                        );
1626
-                    }
1627
-                    $results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1628
-                } else {
1629
-                    $results = $this->get_model()->insert($save_cols_n_values);
1630
-                    $this->_update_cached_related_model_objs_fks();
1631
-                }
1632
-            }
1633
-        } else {//there is NO primary key
1634
-            $already_in_db = false;
1635
-            foreach ($this->get_model()->unique_indexes() as $index) {
1636
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1637
-                if ($this->get_model()->exists(array($uniqueness_where_params))) {
1638
-                    $already_in_db = true;
1639
-                }
1640
-            }
1641
-            if ($already_in_db) {
1642
-                $combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1643
-                    $this->get_model()->get_combined_primary_key_fields());
1644
-                $results = $this->get_model()->update($save_cols_n_values, $combined_pk_fields_n_values);
1645
-            } else {
1646
-                $results = $this->get_model()->insert($save_cols_n_values);
1647
-            }
1648
-        }
1649
-        //restore the old assumption about values being prepared by the model object
1650
-        $this->get_model()
1651
-             ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1652
-        /**
1653
-         * After saving the model object this action is called
1654
-         *
1655
-         * @param EE_Base_Class $model_object which was just saved
1656
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1657
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1658
-         */
1659
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1660
-        return $results;
1661
-    }
1662
-
1663
-
1664
-
1665
-    /**
1666
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1667
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1668
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1669
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1670
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1671
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1672
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1673
-     *
1674
-     * @return void
1675
-     * @throws \EE_Error
1676
-     */
1677
-    protected function _update_cached_related_model_objs_fks()
1678
-    {
1679
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1680
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1681
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1682
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1683
-                        $this->get_model()->get_this_model_name()
1684
-                    );
1685
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1686
-                    if ($related_model_obj_in_cache->ID()) {
1687
-                        $related_model_obj_in_cache->save();
1688
-                    }
1689
-                }
1690
-            }
1691
-        }
1692
-    }
1693
-
1694
-
1695
-
1696
-    /**
1697
-     * Saves this model object and its NEW cached relations to the database.
1698
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1699
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1700
-     * because otherwise, there's a potential for infinite looping of saving
1701
-     * Saves the cached related model objects, and ensures the relation between them
1702
-     * and this object and properly setup
1703
-     *
1704
-     * @return int ID of new model object on save; 0 on failure+
1705
-     * @throws \EE_Error
1706
-     */
1707
-    public function save_new_cached_related_model_objs()
1708
-    {
1709
-        //make sure this has been saved
1710
-        if ( ! $this->ID()) {
1711
-            $id = $this->save();
1712
-        } else {
1713
-            $id = $this->ID();
1714
-        }
1715
-        //now save all the NEW cached model objects  (ie they don't exist in the DB)
1716
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1717
-            if ($this->_model_relations[$relationName]) {
1718
-                //is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1719
-                //or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1720
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1721
-                    //add a relation to that relation type (which saves the appropriate thing in the process)
1722
-                    //but ONLY if it DOES NOT exist in the DB
1723
-                    /* @var $related_model_obj EE_Base_Class */
1724
-                    $related_model_obj = $this->_model_relations[$relationName];
1725
-                    //					if( ! $related_model_obj->ID()){
1726
-                    $this->_add_relation_to($related_model_obj, $relationName);
1727
-                    $related_model_obj->save_new_cached_related_model_objs();
1728
-                    //					}
1729
-                } else {
1730
-                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1731
-                        //add a relation to that relation type (which saves the appropriate thing in the process)
1732
-                        //but ONLY if it DOES NOT exist in the DB
1733
-                        //						if( ! $related_model_obj->ID()){
1734
-                        $this->_add_relation_to($related_model_obj, $relationName);
1735
-                        $related_model_obj->save_new_cached_related_model_objs();
1736
-                        //						}
1737
-                    }
1738
-                }
1739
-            }
1740
-        }
1741
-        return $id;
1742
-    }
1743
-
1744
-
1745
-
1746
-    /**
1747
-     * for getting a model while instantiated.
1748
-     *
1749
-     * @return \EEM_Base | \EEM_CPT_Base
1750
-     */
1751
-    public function get_model()
1752
-    {
1753
-        $modelName = self::_get_model_classname(get_class($this));
1754
-        return self::_get_model_instance_with_name($modelName, $this->_timezone);
1755
-    }
1756
-
1757
-
1758
-
1759
-    /**
1760
-     * @param $props_n_values
1761
-     * @param $classname
1762
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1763
-     * @throws \EE_Error
1764
-     */
1765
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1766
-    {
1767
-        //TODO: will not work for Term_Relationships because they have no PK!
1768
-        $primary_id_ref = self::_get_primary_key_name($classname);
1769
-        if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1770
-            $id = $props_n_values[$primary_id_ref];
1771
-            return self::_get_model($classname)->get_from_entity_map($id);
1772
-        }
1773
-        return false;
1774
-    }
1775
-
1776
-
1777
-
1778
-    /**
1779
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1780
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1781
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
1782
-     * we return false.
1783
-     *
1784
-     * @param  array  $props_n_values   incoming array of properties and their values
1785
-     * @param  string $classname        the classname of the child class
1786
-     * @param null    $timezone
1787
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
1788
-     *                                  date_format and the second value is the time format
1789
-     * @return mixed (EE_Base_Class|bool)
1790
-     * @throws \EE_Error
1791
-     */
1792
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1793
-    {
1794
-        $existing = null;
1795
-        if (self::_get_model($classname)->has_primary_key_field()) {
1796
-            $primary_id_ref = self::_get_primary_key_name($classname);
1797
-            if (array_key_exists($primary_id_ref, $props_n_values)
1798
-                && ! empty($props_n_values[$primary_id_ref])
1799
-            ) {
1800
-                $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1801
-                    $props_n_values[$primary_id_ref]
1802
-                );
1803
-            }
1804
-        } elseif (self::_get_model($classname, $timezone)->has_all_combined_primary_key_fields($props_n_values)) {
1805
-            //no primary key on this model, but there's still a matching item in the DB
1806
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1807
-                self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1808
-            );
1809
-        }
1810
-        if ($existing) {
1811
-            //set date formats if present before setting values
1812
-            if ( ! empty($date_formats) && is_array($date_formats)) {
1813
-                $existing->set_date_format($date_formats[0]);
1814
-                $existing->set_time_format($date_formats[1]);
1815
-            } else {
1816
-                //set default formats for date and time
1817
-                $existing->set_date_format(get_option('date_format'));
1818
-                $existing->set_time_format(get_option('time_format'));
1819
-            }
1820
-            foreach ($props_n_values as $property => $field_value) {
1821
-                $existing->set($property, $field_value);
1822
-            }
1823
-            return $existing;
1824
-        } else {
1825
-            return false;
1826
-        }
1827
-    }
1828
-
1829
-
1830
-
1831
-    /**
1832
-     * Gets the EEM_*_Model for this class
1833
-     *
1834
-     * @access public now, as this is more convenient
1835
-     * @param      $classname
1836
-     * @param null $timezone
1837
-     * @throws EE_Error
1838
-     * @return EEM_Base
1839
-     */
1840
-    protected static function _get_model($classname, $timezone = null)
1841
-    {
1842
-        //find model for this class
1843
-        if ( ! $classname) {
1844
-            throw new EE_Error(
1845
-                sprintf(
1846
-                    __(
1847
-                        "What were you thinking calling _get_model(%s)?? You need to specify the class name",
1848
-                        "event_espresso"
1849
-                    ),
1850
-                    $classname
1851
-                )
1852
-            );
1853
-        }
1854
-        $modelName = self::_get_model_classname($classname);
1855
-        return self::_get_model_instance_with_name($modelName, $timezone);
1856
-    }
1857
-
1858
-
1859
-
1860
-    /**
1861
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1862
-     *
1863
-     * @param string $model_classname
1864
-     * @param null   $timezone
1865
-     * @return EEM_Base
1866
-     */
1867
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1868
-    {
1869
-        $model_classname = str_replace('EEM_', '', $model_classname);
1870
-        $model = EE_Registry::instance()->load_model($model_classname);
1871
-        $model->set_timezone($timezone);
1872
-        return $model;
1873
-    }
1874
-
1875
-
1876
-
1877
-    /**
1878
-     * If a model name is provided (eg Registration), gets the model classname for that model.
1879
-     * Also works if a model class's classname is provided (eg EE_Registration).
1880
-     *
1881
-     * @param null $model_name
1882
-     * @return string like EEM_Attendee
1883
-     */
1884
-    private static function _get_model_classname($model_name = null)
1885
-    {
1886
-        if (strpos($model_name, "EE_") === 0) {
1887
-            $model_classname = str_replace("EE_", "EEM_", $model_name);
1888
-        } else {
1889
-            $model_classname = "EEM_" . $model_name;
1890
-        }
1891
-        return $model_classname;
1892
-    }
1893
-
1894
-
1895
-
1896
-    /**
1897
-     * returns the name of the primary key attribute
1898
-     *
1899
-     * @param null $classname
1900
-     * @throws EE_Error
1901
-     * @return string
1902
-     */
1903
-    protected static function _get_primary_key_name($classname = null)
1904
-    {
1905
-        if ( ! $classname) {
1906
-            throw new EE_Error(
1907
-                sprintf(
1908
-                    __("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
1909
-                    $classname
1910
-                )
1911
-            );
1912
-        }
1913
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
1914
-    }
1915
-
1916
-
1917
-
1918
-    /**
1919
-     * Gets the value of the primary key.
1920
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
1921
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
1922
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
1923
-     *
1924
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
1925
-     * @throws \EE_Error
1926
-     */
1927
-    public function ID()
1928
-    {
1929
-        //now that we know the name of the variable, use a variable variable to get its value and return its
1930
-        if ($this->get_model()->has_primary_key_field()) {
1931
-            return $this->_fields[self::_get_primary_key_name(get_class($this))];
1932
-        } else {
1933
-            return $this->get_model()->get_index_primary_key_string($this->_fields);
1934
-        }
1935
-    }
1936
-
1937
-
1938
-
1939
-    /**
1940
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
1941
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
1942
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
1943
-     *
1944
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
1945
-     * @param string $relationName                     eg 'Events','Question',etc.
1946
-     *                                                 an attendee to a group, you also want to specify which role they
1947
-     *                                                 will have in that group. So you would use this parameter to
1948
-     *                                                 specify array('role-column-name'=>'role-id')
1949
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
1950
-     *                                                 allow you to further constrict the relation to being added.
1951
-     *                                                 However, keep in mind that the columns (keys) given must match a
1952
-     *                                                 column on the JOIN table and currently only the HABTM models
1953
-     *                                                 accept these additional conditions.  Also remember that if an
1954
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
1955
-     *                                                 NEW row is created in the join table.
1956
-     * @param null   $cache_id
1957
-     * @throws EE_Error
1958
-     * @return EE_Base_Class the object the relation was added to
1959
-     */
1960
-    public function _add_relation_to(
1961
-        $otherObjectModelObjectOrID,
1962
-        $relationName,
1963
-        $extra_join_model_fields_n_values = array(),
1964
-        $cache_id = null
1965
-    ) {
1966
-        //if this thing exists in the DB, save the relation to the DB
1967
-        if ($this->ID()) {
1968
-            $otherObject = $this->get_model()
1969
-                                ->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
1970
-                                    $extra_join_model_fields_n_values);
1971
-            //clear cache so future get_many_related and get_first_related() return new results.
1972
-            $this->clear_cache($relationName, $otherObject, true);
1973
-            if ($otherObject instanceof EE_Base_Class) {
1974
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
1975
-            }
1976
-        } else {
1977
-            //this thing doesn't exist in the DB,  so just cache it
1978
-            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
1979
-                throw new EE_Error(sprintf(
1980
-                    __('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
1981
-                        'event_espresso'),
1982
-                    $otherObjectModelObjectOrID,
1983
-                    get_class($this)
1984
-                ));
1985
-            } else {
1986
-                $otherObject = $otherObjectModelObjectOrID;
1987
-            }
1988
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
1989
-        }
1990
-        if ($otherObject instanceof EE_Base_Class) {
1991
-            //fix the reciprocal relation too
1992
-            if ($otherObject->ID()) {
1993
-                //its saved so assumed relations exist in the DB, so we can just
1994
-                //clear the cache so future queries use the updated info in the DB
1995
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), null, true);
1996
-            } else {
1997
-                //it's not saved, so it caches relations like this
1998
-                $otherObject->cache($this->get_model()->get_this_model_name(), $this);
1999
-            }
2000
-        }
2001
-        return $otherObject;
2002
-    }
2003
-
2004
-
2005
-
2006
-    /**
2007
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2008
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2009
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2010
-     * from the cache
2011
-     *
2012
-     * @param mixed  $otherObjectModelObjectOrID
2013
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2014
-     *                to the DB yet
2015
-     * @param string $relationName
2016
-     * @param array  $where_query
2017
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2018
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2019
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2020
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2021
-     *                created in the join table.
2022
-     * @return EE_Base_Class the relation was removed from
2023
-     * @throws \EE_Error
2024
-     */
2025
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2026
-    {
2027
-        if ($this->ID()) {
2028
-            //if this exists in the DB, save the relation change to the DB too
2029
-            $otherObject = $this->get_model()
2030
-                                ->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2031
-                                    $where_query);
2032
-            $this->clear_cache($relationName, $otherObject);
2033
-        } else {
2034
-            //this doesn't exist in the DB, just remove it from the cache
2035
-            $otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2036
-        }
2037
-        if ($otherObject instanceof EE_Base_Class) {
2038
-            $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2039
-        }
2040
-        return $otherObject;
2041
-    }
2042
-
2043
-
2044
-
2045
-    /**
2046
-     * Removes ALL the related things for the $relationName.
2047
-     *
2048
-     * @param string $relationName
2049
-     * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2050
-     * @return EE_Base_Class
2051
-     * @throws \EE_Error
2052
-     */
2053
-    public function _remove_relations($relationName, $where_query_params = array())
2054
-    {
2055
-        if ($this->ID()) {
2056
-            //if this exists in the DB, save the relation change to the DB too
2057
-            $otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2058
-            $this->clear_cache($relationName, null, true);
2059
-        } else {
2060
-            //this doesn't exist in the DB, just remove it from the cache
2061
-            $otherObjects = $this->clear_cache($relationName, null, true);
2062
-        }
2063
-        if (is_array($otherObjects)) {
2064
-            foreach ($otherObjects as $otherObject) {
2065
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2066
-            }
2067
-        }
2068
-        return $otherObjects;
2069
-    }
2070
-
2071
-
2072
-
2073
-    /**
2074
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2075
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2076
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2077
-     * because we want to get even deleted items etc.
2078
-     *
2079
-     * @param string $relationName key in the model's _model_relations array
2080
-     * @param array  $query_params like EEM_Base::get_all
2081
-     * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2082
-     * @throws \EE_Error
2083
-     *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2084
-     *                             you want IDs
2085
-     */
2086
-    public function get_many_related($relationName, $query_params = array())
2087
-    {
2088
-        if ($this->ID()) {
2089
-            //this exists in the DB, so get the related things from either the cache or the DB
2090
-            //if there are query parameters, forget about caching the related model objects.
2091
-            if ($query_params) {
2092
-                $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2093
-            } else {
2094
-                //did we already cache the result of this query?
2095
-                $cached_results = $this->get_all_from_cache($relationName);
2096
-                if ( ! $cached_results) {
2097
-                    $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2098
-                    //if no query parameters were passed, then we got all the related model objects
2099
-                    //for that relation. We can cache them then.
2100
-                    foreach ($related_model_objects as $related_model_object) {
2101
-                        $this->cache($relationName, $related_model_object);
2102
-                    }
2103
-                } else {
2104
-                    $related_model_objects = $cached_results;
2105
-                }
2106
-            }
2107
-        } else {
2108
-            //this doesn't exist in the DB, so just get the related things from the cache
2109
-            $related_model_objects = $this->get_all_from_cache($relationName);
2110
-        }
2111
-        return $related_model_objects;
2112
-    }
2113
-
2114
-
2115
-
2116
-    /**
2117
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2118
-     * unless otherwise specified in the $query_params
2119
-     *
2120
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2121
-     * @param array  $query_params   like EEM_Base::get_all's
2122
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2123
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2124
-     *                               that by the setting $distinct to TRUE;
2125
-     * @return int
2126
-     */
2127
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2128
-    {
2129
-        return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2130
-    }
2131
-
2132
-
2133
-
2134
-    /**
2135
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2136
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2137
-     *
2138
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2139
-     * @param array  $query_params  like EEM_Base::get_all's
2140
-     * @param string $field_to_sum  name of field to count by.
2141
-     *                              By default, uses primary key (which doesn't make much sense, so you should probably
2142
-     *                              change it)
2143
-     * @return int
2144
-     */
2145
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2146
-    {
2147
-        return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2148
-    }
2149
-
2150
-
2151
-
2152
-    /**
2153
-     * Gets the first (ie, one) related model object of the specified type.
2154
-     *
2155
-     * @param string $relationName key in the model's _model_relations array
2156
-     * @param array  $query_params like EEM_Base::get_all
2157
-     * @return EE_Base_Class (not an array, a single object)
2158
-     * @throws \EE_Error
2159
-     */
2160
-    public function get_first_related($relationName, $query_params = array())
2161
-    {
2162
-        if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2163
-            //if they've provided some query parameters, don't bother trying to cache the result
2164
-            //also make sure we're not caching the result of get_first_related
2165
-            //on a relation which should have an array of objects (because the cache might have an array of objects)
2166
-            if ($query_params
2167
-                || ! $this->get_model()->related_settings_for($relationName)
2168
-                     instanceof
2169
-                     EE_Belongs_To_Relation
2170
-            ) {
2171
-                $related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2172
-            } else {
2173
-                //first, check if we've already cached the result of this query
2174
-                $cached_result = $this->get_one_from_cache($relationName);
2175
-                if ( ! $cached_result) {
2176
-                    $related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2177
-                    $this->cache($relationName, $related_model_object);
2178
-                } else {
2179
-                    $related_model_object = $cached_result;
2180
-                }
2181
-            }
2182
-        } else {
2183
-            $related_model_object = null;
2184
-            //this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2185
-            if ($this->get_model()->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2186
-                $related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2187
-            }
2188
-            //this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2189
-            if ( ! $related_model_object) {
2190
-                $related_model_object = $this->get_one_from_cache($relationName);
2191
-            }
2192
-        }
2193
-        return $related_model_object;
2194
-    }
2195
-
2196
-
2197
-
2198
-    /**
2199
-     * Does a delete on all related objects of type $relationName and removes
2200
-     * the current model object's relation to them. If they can't be deleted (because
2201
-     * of blocking related model objects) does nothing. If the related model objects are
2202
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2203
-     * If this model object doesn't exist yet in the DB, just removes its related things
2204
-     *
2205
-     * @param string $relationName
2206
-     * @param array  $query_params like EEM_Base::get_all's
2207
-     * @return int how many deleted
2208
-     * @throws \EE_Error
2209
-     */
2210
-    public function delete_related($relationName, $query_params = array())
2211
-    {
2212
-        if ($this->ID()) {
2213
-            $count = $this->get_model()->delete_related($this, $relationName, $query_params);
2214
-        } else {
2215
-            $count = count($this->get_all_from_cache($relationName));
2216
-            $this->clear_cache($relationName, null, true);
2217
-        }
2218
-        return $count;
2219
-    }
2220
-
2221
-
2222
-
2223
-    /**
2224
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2225
-     * the current model object's relation to them. If they can't be deleted (because
2226
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2227
-     * If the related thing isn't a soft-deletable model object, this function is identical
2228
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2229
-     *
2230
-     * @param string $relationName
2231
-     * @param array  $query_params like EEM_Base::get_all's
2232
-     * @return int how many deleted (including those soft deleted)
2233
-     * @throws \EE_Error
2234
-     */
2235
-    public function delete_related_permanently($relationName, $query_params = array())
2236
-    {
2237
-        if ($this->ID()) {
2238
-            $count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2239
-        } else {
2240
-            $count = count($this->get_all_from_cache($relationName));
2241
-        }
2242
-        $this->clear_cache($relationName, null, true);
2243
-        return $count;
2244
-    }
2245
-
2246
-
2247
-
2248
-    /**
2249
-     * is_set
2250
-     * Just a simple utility function children can use for checking if property exists
2251
-     *
2252
-     * @access  public
2253
-     * @param  string $field_name property to check
2254
-     * @return bool                              TRUE if existing,FALSE if not.
2255
-     */
2256
-    public function is_set($field_name)
2257
-    {
2258
-        return isset($this->_fields[$field_name]);
2259
-    }
2260
-
2261
-
2262
-
2263
-    /**
2264
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2265
-     * EE_Error exception if they don't
2266
-     *
2267
-     * @param  mixed (string|array) $properties properties to check
2268
-     * @throws EE_Error
2269
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2270
-     */
2271
-    protected function _property_exists($properties)
2272
-    {
2273
-        foreach ((array)$properties as $property_name) {
2274
-            //first make sure this property exists
2275
-            if ( ! $this->_fields[$property_name]) {
2276
-                throw new EE_Error(
2277
-                    sprintf(
2278
-                        __(
2279
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2280
-                            'event_espresso'
2281
-                        ),
2282
-                        $property_name
2283
-                    )
2284
-                );
2285
-            }
2286
-        }
2287
-        return true;
2288
-    }
2289
-
2290
-
2291
-
2292
-    /**
2293
-     * This simply returns an array of model fields for this object
2294
-     *
2295
-     * @return array
2296
-     * @throws \EE_Error
2297
-     */
2298
-    public function model_field_array()
2299
-    {
2300
-        $fields = $this->get_model()->field_settings(false);
2301
-        $properties = array();
2302
-        //remove prepended underscore
2303
-        foreach ($fields as $field_name => $settings) {
2304
-            $properties[$field_name] = $this->get($field_name);
2305
-        }
2306
-        return $properties;
2307
-    }
2308
-
2309
-
2310
-
2311
-    /**
2312
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2313
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2314
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2315
-     * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2316
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2317
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2318
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
2319
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
2320
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2321
-     * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2322
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2323
-     *        return $previousReturnValue.$returnString;
2324
-     * }
2325
-     * require('EE_Answer.class.php');
2326
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2327
-     * echo $answer->my_callback('monkeys',100);
2328
-     * //will output "you called my_callback! and passed args:monkeys,100"
2329
-     *
2330
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2331
-     * @param array  $args       array of original arguments passed to the function
2332
-     * @throws EE_Error
2333
-     * @return mixed whatever the plugin which calls add_filter decides
2334
-     */
2335
-    public function __call($methodName, $args)
2336
-    {
2337
-        $className = get_class($this);
2338
-        $tagName = "FHEE__{$className}__{$methodName}";
2339
-        if ( ! has_filter($tagName)) {
2340
-            throw new EE_Error(
2341
-                sprintf(
2342
-                    __(
2343
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2344
-                        "event_espresso"
2345
-                    ),
2346
-                    $methodName,
2347
-                    $className,
2348
-                    $tagName
2349
-                )
2350
-            );
2351
-        }
2352
-        return apply_filters($tagName, null, $this, $args);
2353
-    }
2354
-
2355
-
2356
-
2357
-    /**
2358
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2359
-     * A $previous_value can be specified in case there are many meta rows with the same key
2360
-     *
2361
-     * @param string $meta_key
2362
-     * @param string $meta_value
2363
-     * @param string $previous_value
2364
-     * @return int records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2365
-     * @throws \EE_Error
2366
-     * NOTE: if the values haven't changed, returns 0
2367
-     */
2368
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2369
-    {
2370
-        $query_params = array(
2371
-            array(
2372
-                'EXM_key'  => $meta_key,
2373
-                'OBJ_ID'   => $this->ID(),
2374
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2375
-            ),
2376
-        );
2377
-        if ($previous_value !== null) {
2378
-            $query_params[0]['EXM_value'] = $meta_value;
2379
-        }
2380
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2381
-        if ( ! $existing_rows_like_that) {
2382
-            return $this->add_extra_meta($meta_key, $meta_value);
2383
-        } else {
2384
-            foreach ($existing_rows_like_that as $existing_row) {
2385
-                $existing_row->save(array('EXM_value' => $meta_value));
2386
-            }
2387
-            return count($existing_rows_like_that);
2388
-        }
2389
-    }
2390
-
2391
-
2392
-
2393
-    /**
2394
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2395
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2396
-     * extra meta row was entered, false if not
2397
-     *
2398
-     * @param string  $meta_key
2399
-     * @param string  $meta_value
2400
-     * @param boolean $unique
2401
-     * @return boolean
2402
-     * @throws \EE_Error
2403
-     */
2404
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2405
-    {
2406
-        if ($unique) {
2407
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2408
-                array(
2409
-                    array(
2410
-                        'EXM_key'  => $meta_key,
2411
-                        'OBJ_ID'   => $this->ID(),
2412
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2413
-                    ),
2414
-                )
2415
-            );
2416
-            if ($existing_extra_meta) {
2417
-                return false;
2418
-            }
2419
-        }
2420
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2421
-            array(
2422
-                'EXM_key'   => $meta_key,
2423
-                'EXM_value' => $meta_value,
2424
-                'OBJ_ID'    => $this->ID(),
2425
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2426
-            )
2427
-        );
2428
-        $new_extra_meta->save();
2429
-        return true;
2430
-    }
2431
-
2432
-
2433
-
2434
-    /**
2435
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2436
-     * is specified, only deletes extra meta records with that value.
2437
-     *
2438
-     * @param string $meta_key
2439
-     * @param string $meta_value
2440
-     * @return int number of extra meta rows deleted
2441
-     * @throws \EE_Error
2442
-     */
2443
-    public function delete_extra_meta($meta_key, $meta_value = null)
2444
-    {
2445
-        $query_params = array(
2446
-            array(
2447
-                'EXM_key'  => $meta_key,
2448
-                'OBJ_ID'   => $this->ID(),
2449
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2450
-            ),
2451
-        );
2452
-        if ($meta_value !== null) {
2453
-            $query_params[0]['EXM_value'] = $meta_value;
2454
-        }
2455
-        return EEM_Extra_Meta::instance()->delete($query_params);
2456
-    }
2457
-
2458
-
2459
-
2460
-    /**
2461
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2462
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2463
-     * You can specify $default is case you haven't found the extra meta
2464
-     *
2465
-     * @param string  $meta_key
2466
-     * @param boolean $single
2467
-     * @param mixed   $default if we don't find anything, what should we return?
2468
-     * @return mixed single value if $single; array if ! $single
2469
-     * @throws \EE_Error
2470
-     */
2471
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2472
-    {
2473
-        if ($single) {
2474
-            $result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2475
-            if ($result instanceof EE_Extra_Meta) {
2476
-                return $result->value();
2477
-            } else {
2478
-                return $default;
2479
-            }
2480
-        } else {
2481
-            $results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2482
-            if ($results) {
2483
-                $values = array();
2484
-                foreach ($results as $result) {
2485
-                    if ($result instanceof EE_Extra_Meta) {
2486
-                        $values[$result->ID()] = $result->value();
2487
-                    }
2488
-                }
2489
-                return $values;
2490
-            } else {
2491
-                return $default;
2492
-            }
2493
-        }
2494
-    }
2495
-
2496
-
2497
-
2498
-    /**
2499
-     * Returns a simple array of all the extra meta associated with this model object.
2500
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2501
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2502
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2503
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2504
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2505
-     * finally the extra meta's value as each sub-value. (eg
2506
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2507
-     *
2508
-     * @param boolean $one_of_each_key
2509
-     * @return array
2510
-     * @throws \EE_Error
2511
-     */
2512
-    public function all_extra_meta_array($one_of_each_key = true)
2513
-    {
2514
-        $return_array = array();
2515
-        if ($one_of_each_key) {
2516
-            $extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2517
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2518
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2519
-                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2520
-                }
2521
-            }
2522
-        } else {
2523
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2524
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2525
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2526
-                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2527
-                        $return_array[$extra_meta_obj->key()] = array();
2528
-                    }
2529
-                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2530
-                }
2531
-            }
2532
-        }
2533
-        return $return_array;
2534
-    }
2535
-
2536
-
2537
-
2538
-    /**
2539
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2540
-     *
2541
-     * @return string
2542
-     * @throws \EE_Error
2543
-     */
2544
-    public function name()
2545
-    {
2546
-        //find a field that's not a text field
2547
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2548
-        if ($field_we_can_use) {
2549
-            return $this->get($field_we_can_use->get_name());
2550
-        } else {
2551
-            $first_few_properties = $this->model_field_array();
2552
-            $first_few_properties = array_slice($first_few_properties, 0, 3);
2553
-            $name_parts = array();
2554
-            foreach ($first_few_properties as $name => $value) {
2555
-                $name_parts[] = "$name:$value";
2556
-            }
2557
-            return implode(",", $name_parts);
2558
-        }
2559
-    }
2560
-
2561
-
2562
-
2563
-    /**
2564
-     * in_entity_map
2565
-     * Checks if this model object has been proven to already be in the entity map
2566
-     *
2567
-     * @return boolean
2568
-     * @throws \EE_Error
2569
-     */
2570
-    public function in_entity_map()
2571
-    {
2572
-        if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2573
-            //well, if we looked, did we find it in the entity map?
2574
-            return true;
2575
-        } else {
2576
-            return false;
2577
-        }
2578
-    }
2579
-
2580
-
2581
-
2582
-    /**
2583
-     * refresh_from_db
2584
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
2585
-     *
2586
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2587
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2588
-     */
2589
-    public function refresh_from_db()
2590
-    {
2591
-        if ($this->ID() && $this->in_entity_map()) {
2592
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
2593
-        } else {
2594
-            //if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2595
-            //if it has an ID but it's not in the map, and you're asking me to refresh it
2596
-            //that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2597
-            //absolutely nothing in it for this ID
2598
-            if (WP_DEBUG) {
2599
-                throw new EE_Error(
2600
-                    sprintf(
2601
-                        __('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2602
-                            'event_espresso'),
2603
-                        $this->ID(),
2604
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2605
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2606
-                    )
2607
-                );
2608
-            }
2609
-        }
2610
-    }
2611
-
2612
-
2613
-
2614
-    /**
2615
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2616
-     * (probably a bad assumption they have made, oh well)
2617
-     *
2618
-     * @return string
2619
-     */
2620
-    public function __toString()
2621
-    {
2622
-        try {
2623
-            return sprintf('%s (%s)', $this->name(), $this->ID());
2624
-        } catch (Exception $e) {
2625
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2626
-            return '';
2627
-        }
2628
-    }
2629
-
2630
-
2631
-
2632
-    /**
2633
-     * Clear related model objects if they're already in the DB, because otherwise when we
2634
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
2635
-     * This means if we have made changes to those related model objects, and want to unserialize
2636
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
2637
-     * Instead, those related model objects should be directly serialized and stored.
2638
-     * Eg, the following won't work:
2639
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2640
-     * $att = $reg->attendee();
2641
-     * $att->set( 'ATT_fname', 'Dirk' );
2642
-     * update_option( 'my_option', serialize( $reg ) );
2643
-     * //END REQUEST
2644
-     * //START NEXT REQUEST
2645
-     * $reg = get_option( 'my_option' );
2646
-     * $reg->attendee()->save();
2647
-     * And would need to be replace with:
2648
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2649
-     * $att = $reg->attendee();
2650
-     * $att->set( 'ATT_fname', 'Dirk' );
2651
-     * update_option( 'my_option', serialize( $reg ) );
2652
-     * //END REQUEST
2653
-     * //START NEXT REQUEST
2654
-     * $att = get_option( 'my_option' );
2655
-     * $att->save();
2656
-     *
2657
-     * @return array
2658
-     * @throws \EE_Error
2659
-     */
2660
-    public function __sleep()
2661
-    {
2662
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
2663
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
2664
-                $classname = 'EE_' . $this->get_model()->get_this_model_name();
2665
-                if (
2666
-                    $this->get_one_from_cache($relation_name) instanceof $classname
2667
-                    && $this->get_one_from_cache($relation_name)->ID()
2668
-                ) {
2669
-                    $this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2670
-                }
2671
-            }
2672
-        }
2673
-        $this->_props_n_values_provided_in_constructor = array();
2674
-        return array_keys(get_object_vars($this));
2675
-    }
2676
-
2677
-
2678
-
2679
-    /**
2680
-     * restore _props_n_values_provided_in_constructor
2681
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2682
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
2683
-     * At best, you would only be able to detect if state change has occurred during THIS request.
2684
-     */
2685
-    public function __wakeup()
2686
-    {
2687
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
2688
-    }
28
+	/**
29
+	 * This is an array of the original properties and values provided during construction
30
+	 * of this model object. (keys are model field names, values are their values).
31
+	 * This list is important to remember so that when we are merging data from the db, we know
32
+	 * which values to override and which to not override.
33
+	 *
34
+	 * @var array
35
+	 */
36
+	protected $_props_n_values_provided_in_constructor;
37
+
38
+	/**
39
+	 * Timezone
40
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
41
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
42
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
43
+	 * access to it.
44
+	 *
45
+	 * @var string
46
+	 */
47
+	protected $_timezone;
48
+
49
+
50
+
51
+	/**
52
+	 * date format
53
+	 * pattern or format for displaying dates
54
+	 *
55
+	 * @var string $_dt_frmt
56
+	 */
57
+	protected $_dt_frmt;
58
+
59
+
60
+
61
+	/**
62
+	 * time format
63
+	 * pattern or format for displaying time
64
+	 *
65
+	 * @var string $_tm_frmt
66
+	 */
67
+	protected $_tm_frmt;
68
+
69
+
70
+
71
+	/**
72
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
73
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
74
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
75
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
76
+	 *
77
+	 * @var array
78
+	 */
79
+	protected $_cached_properties = array();
80
+
81
+	/**
82
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
83
+	 * single
84
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
85
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
86
+	 * all others have an array)
87
+	 *
88
+	 * @var array
89
+	 */
90
+	protected $_model_relations = array();
91
+
92
+	/**
93
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
94
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
95
+	 *
96
+	 * @var array
97
+	 */
98
+	protected $_fields = array();
99
+
100
+	/**
101
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
102
+	 * For example, we might create model objects intended to only be used for the duration
103
+	 * of this request and to be thrown away, and if they were accidentally saved
104
+	 * it would be a bug.
105
+	 */
106
+	protected $_allow_persist = true;
107
+
108
+
109
+
110
+	/**
111
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
112
+	 * play nice
113
+	 *
114
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
115
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
116
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
117
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
118
+	 *                                                         corresponding db model or not.
119
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
120
+	 *                                                         be in when instantiating a EE_Base_Class object.
121
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
122
+	 *                                                         value is the date_format and second value is the time
123
+	 *                                                         format.
124
+	 * @throws EE_Error
125
+	 */
126
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
127
+	{
128
+		$className = get_class($this);
129
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
130
+		$model = $this->get_model();
131
+		$model_fields = $model->field_settings(false);
132
+		// ensure $fieldValues is an array
133
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
134
+		// EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
135
+		// verify client code has not passed any invalid field names
136
+		foreach ($fieldValues as $field_name => $field_value) {
137
+			if ( ! isset($model_fields[$field_name])) {
138
+				throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
139
+					"event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
140
+			}
141
+		}
142
+		// EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
143
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
144
+		if ( ! empty($date_formats) && is_array($date_formats)) {
145
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
146
+		} else {
147
+			//set default formats for date and time
148
+			$this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
149
+			$this->_tm_frmt = (string)get_option('time_format', 'g:i a');
150
+		}
151
+		//if db model is instantiating
152
+		if ($bydb) {
153
+			//client code has indicated these field values are from the database
154
+			foreach ($model_fields as $fieldName => $field) {
155
+				$this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
156
+			}
157
+		} else {
158
+			//we're constructing a brand
159
+			//new instance of the model object. Generally, this means we'll need to do more field validation
160
+			foreach ($model_fields as $fieldName => $field) {
161
+				$this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
162
+			}
163
+		}
164
+		//remember what values were passed to this constructor
165
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
166
+		//remember in entity mapper
167
+		if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
168
+			$model->add_to_entity_map($this);
169
+		}
170
+		//setup all the relations
171
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
172
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
173
+				$this->_model_relations[$relation_name] = null;
174
+			} else {
175
+				$this->_model_relations[$relation_name] = array();
176
+			}
177
+		}
178
+		/**
179
+		 * Action done at the end of each model object construction
180
+		 *
181
+		 * @param EE_Base_Class $this the model object just created
182
+		 */
183
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
184
+	}
185
+
186
+
187
+
188
+	/**
189
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
190
+	 *
191
+	 * @return boolean
192
+	 */
193
+	public function allow_persist()
194
+	{
195
+		return $this->_allow_persist;
196
+	}
197
+
198
+
199
+
200
+	/**
201
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
202
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
203
+	 * you got new information that somehow made you change your mind.
204
+	 *
205
+	 * @param boolean $allow_persist
206
+	 * @return boolean
207
+	 */
208
+	public function set_allow_persist($allow_persist)
209
+	{
210
+		return $this->_allow_persist = $allow_persist;
211
+	}
212
+
213
+
214
+
215
+	/**
216
+	 * Gets the field's original value when this object was constructed during this request.
217
+	 * This can be helpful when determining if a model object has changed or not
218
+	 *
219
+	 * @param string $field_name
220
+	 * @return mixed|null
221
+	 * @throws \EE_Error
222
+	 */
223
+	public function get_original($field_name)
224
+	{
225
+		if (isset($this->_props_n_values_provided_in_constructor[$field_name])
226
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
227
+		) {
228
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
229
+		} else {
230
+			return null;
231
+		}
232
+	}
233
+
234
+
235
+
236
+	/**
237
+	 * @param EE_Base_Class $obj
238
+	 * @return string
239
+	 */
240
+	public function get_class($obj)
241
+	{
242
+		return get_class($obj);
243
+	}
244
+
245
+
246
+
247
+	/**
248
+	 * Overrides parent because parent expects old models.
249
+	 * This also doesn't do any validation, and won't work for serialized arrays
250
+	 *
251
+	 * @param    string $field_name
252
+	 * @param    mixed  $field_value
253
+	 * @param bool      $use_default
254
+	 * @throws \EE_Error
255
+	 */
256
+	public function set($field_name, $field_value, $use_default = false)
257
+	{
258
+		$field_obj = $this->get_model()->field_settings_for($field_name);
259
+		if ($field_obj instanceof EE_Model_Field_Base) {
260
+			//			if ( method_exists( $field_obj, 'set_timezone' )) {
261
+			if ($field_obj instanceof EE_Datetime_Field) {
262
+				$field_obj->set_timezone($this->_timezone);
263
+				$field_obj->set_date_format($this->_dt_frmt);
264
+				$field_obj->set_time_format($this->_tm_frmt);
265
+			}
266
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
267
+			//should the value be null?
268
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
269
+				$this->_fields[$field_name] = $field_obj->get_default_value();
270
+				/**
271
+				 * To save having to refactor all the models, if a default value is used for a
272
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
273
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
274
+				 * object.
275
+				 *
276
+				 * @since 4.6.10+
277
+				 */
278
+				if (
279
+					$field_obj instanceof EE_Datetime_Field
280
+					&& $this->_fields[$field_name] !== null
281
+					&& ! $this->_fields[$field_name] instanceof DateTime
282
+				) {
283
+					empty($this->_fields[$field_name])
284
+						? $this->set($field_name, time())
285
+						: $this->set($field_name, $this->_fields[$field_name]);
286
+				}
287
+			} else {
288
+				$this->_fields[$field_name] = $holder_of_value;
289
+			}
290
+			//if we're not in the constructor...
291
+			//now check if what we set was a primary key
292
+			if (
293
+				//note: props_n_values_provided_in_constructor is only set at the END of the constructor
294
+				$this->_props_n_values_provided_in_constructor
295
+				&& $field_value
296
+				&& $field_name === self::_get_primary_key_name(get_class($this))
297
+			) {
298
+				//if so, we want all this object's fields to be filled either with
299
+				//what we've explicitly set on this model
300
+				//or what we have in the db
301
+				// echo "setting primary key!";
302
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
303
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
304
+				foreach ($fields_on_model as $field_obj) {
305
+					if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
306
+						 && $field_obj->get_name() !== $field_name
307
+					) {
308
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
309
+					}
310
+				}
311
+				//oh this model object has an ID? well make sure its in the entity mapper
312
+				$this->get_model()->add_to_entity_map($this);
313
+			}
314
+			//let's unset any cache for this field_name from the $_cached_properties property.
315
+			$this->_clear_cached_property($field_name);
316
+		} else {
317
+			throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
318
+				"event_espresso"), $field_name));
319
+		}
320
+	}
321
+
322
+
323
+
324
+	/**
325
+	 * This sets the field value on the db column if it exists for the given $column_name or
326
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
327
+	 *
328
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
329
+	 * @param string $field_name  Must be the exact column name.
330
+	 * @param mixed  $field_value The value to set.
331
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
332
+	 * @throws \EE_Error
333
+	 */
334
+	public function set_field_or_extra_meta($field_name, $field_value)
335
+	{
336
+		if ($this->get_model()->has_field($field_name)) {
337
+			$this->set($field_name, $field_value);
338
+			return true;
339
+		} else {
340
+			//ensure this object is saved first so that extra meta can be properly related.
341
+			$this->save();
342
+			return $this->update_extra_meta($field_name, $field_value);
343
+		}
344
+	}
345
+
346
+
347
+
348
+	/**
349
+	 * This retrieves the value of the db column set on this class or if that's not present
350
+	 * it will attempt to retrieve from extra_meta if found.
351
+	 * Example Usage:
352
+	 * Via EE_Message child class:
353
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
354
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
355
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
356
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
357
+	 * value for those extra fields dynamically via the EE_message object.
358
+	 *
359
+	 * @param  string $field_name expecting the fully qualified field name.
360
+	 * @return mixed|null  value for the field if found.  null if not found.
361
+	 * @throws \EE_Error
362
+	 */
363
+	public function get_field_or_extra_meta($field_name)
364
+	{
365
+		if ($this->get_model()->has_field($field_name)) {
366
+			$column_value = $this->get($field_name);
367
+		} else {
368
+			//This isn't a column in the main table, let's see if it is in the extra meta.
369
+			$column_value = $this->get_extra_meta($field_name, true, null);
370
+		}
371
+		return $column_value;
372
+	}
373
+
374
+
375
+
376
+	/**
377
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
378
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
379
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
380
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
381
+	 *
382
+	 * @access public
383
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
384
+	 * @return void
385
+	 * @throws \EE_Error
386
+	 */
387
+	public function set_timezone($timezone = '')
388
+	{
389
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
390
+		//make sure we clear all cached properties because they won't be relevant now
391
+		$this->_clear_cached_properties();
392
+		//make sure we update field settings and the date for all EE_Datetime_Fields
393
+		$model_fields = $this->get_model()->field_settings(false);
394
+		foreach ($model_fields as $field_name => $field_obj) {
395
+			if ($field_obj instanceof EE_Datetime_Field) {
396
+				$field_obj->set_timezone($this->_timezone);
397
+				if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
398
+					$this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
399
+				}
400
+			}
401
+		}
402
+	}
403
+
404
+
405
+
406
+	/**
407
+	 * This just returns whatever is set for the current timezone.
408
+	 *
409
+	 * @access public
410
+	 * @return string timezone string
411
+	 */
412
+	public function get_timezone()
413
+	{
414
+		return $this->_timezone;
415
+	}
416
+
417
+
418
+
419
+	/**
420
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
421
+	 * internally instead of wp set date format options
422
+	 *
423
+	 * @since 4.6
424
+	 * @param string $format should be a format recognizable by PHP date() functions.
425
+	 */
426
+	public function set_date_format($format)
427
+	{
428
+		$this->_dt_frmt = $format;
429
+		//clear cached_properties because they won't be relevant now.
430
+		$this->_clear_cached_properties();
431
+	}
432
+
433
+
434
+
435
+	/**
436
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
437
+	 * class internally instead of wp set time format options.
438
+	 *
439
+	 * @since 4.6
440
+	 * @param string $format should be a format recognizable by PHP date() functions.
441
+	 */
442
+	public function set_time_format($format)
443
+	{
444
+		$this->_tm_frmt = $format;
445
+		//clear cached_properties because they won't be relevant now.
446
+		$this->_clear_cached_properties();
447
+	}
448
+
449
+
450
+
451
+	/**
452
+	 * This returns the current internal set format for the date and time formats.
453
+	 *
454
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
455
+	 *                             where the first value is the date format and the second value is the time format.
456
+	 * @return mixed string|array
457
+	 */
458
+	public function get_format($full = true)
459
+	{
460
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
461
+	}
462
+
463
+
464
+
465
+	/**
466
+	 * cache
467
+	 * stores the passed model object on the current model object.
468
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
469
+	 *
470
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
471
+	 *                                       'Registration' associated with this model object
472
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
473
+	 *                                       that could be a payment or a registration)
474
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
475
+	 *                                       items which will be stored in an array on this object
476
+	 * @throws EE_Error
477
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
478
+	 *                  related thing, no array)
479
+	 */
480
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
481
+	{
482
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
483
+		if ( ! $object_to_cache instanceof EE_Base_Class) {
484
+			return false;
485
+		}
486
+		// also get "how" the object is related, or throw an error
487
+		if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
488
+			throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
489
+				$relationName, get_class($this)));
490
+		}
491
+		// how many things are related ?
492
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
493
+			// if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
494
+			// so for these model objects just set it to be cached
495
+			$this->_model_relations[$relationName] = $object_to_cache;
496
+			$return = true;
497
+		} else {
498
+			// otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
499
+			// eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
500
+			if ( ! is_array($this->_model_relations[$relationName])) {
501
+				// if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
502
+				$this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
503
+					? array($this->_model_relations[$relationName]) : array();
504
+			}
505
+			// first check for a cache_id which is normally empty
506
+			if ( ! empty($cache_id)) {
507
+				// if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
508
+				$this->_model_relations[$relationName][$cache_id] = $object_to_cache;
509
+				$return = $cache_id;
510
+			} elseif ($object_to_cache->ID()) {
511
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
512
+				$this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
513
+				$return = $object_to_cache->ID();
514
+			} else {
515
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
516
+				$this->_model_relations[$relationName][] = $object_to_cache;
517
+				// move the internal pointer to the end of the array
518
+				end($this->_model_relations[$relationName]);
519
+				// and grab the key so that we can return it
520
+				$return = key($this->_model_relations[$relationName]);
521
+			}
522
+		}
523
+		return $return;
524
+	}
525
+
526
+
527
+
528
+	/**
529
+	 * For adding an item to the cached_properties property.
530
+	 *
531
+	 * @access protected
532
+	 * @param string      $fieldname the property item the corresponding value is for.
533
+	 * @param mixed       $value     The value we are caching.
534
+	 * @param string|null $cache_type
535
+	 * @return void
536
+	 * @throws \EE_Error
537
+	 */
538
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
539
+	{
540
+		//first make sure this property exists
541
+		$this->get_model()->field_settings_for($fieldname);
542
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
543
+		$this->_cached_properties[$fieldname][$cache_type] = $value;
544
+	}
545
+
546
+
547
+
548
+	/**
549
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
550
+	 * This also SETS the cache if we return the actual property!
551
+	 *
552
+	 * @param string $fieldname        the name of the property we're trying to retrieve
553
+	 * @param bool   $pretty
554
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
555
+	 *                                 (in cases where the same property may be used for different outputs
556
+	 *                                 - i.e. datetime, money etc.)
557
+	 *                                 It can also accept certain pre-defined "schema" strings
558
+	 *                                 to define how to output the property.
559
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
560
+	 * @return mixed                   whatever the value for the property is we're retrieving
561
+	 * @throws \EE_Error
562
+	 */
563
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
564
+	{
565
+		//verify the field exists
566
+		$this->get_model()->field_settings_for($fieldname);
567
+		$cache_type = $pretty ? 'pretty' : 'standard';
568
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
569
+		if (isset($this->_cached_properties[$fieldname][$cache_type])) {
570
+			return $this->_cached_properties[$fieldname][$cache_type];
571
+		}
572
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
573
+		$this->_set_cached_property($fieldname, $value, $cache_type);
574
+		return $value;
575
+	}
576
+
577
+
578
+
579
+	/**
580
+	 * If the cache didn't fetch the needed item, this fetches it.
581
+	 * @param string $fieldname
582
+	 * @param bool $pretty
583
+	 * @param string $extra_cache_ref
584
+	 * @return mixed
585
+	 */
586
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
587
+	{
588
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
589
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
590
+		if ($field_obj instanceof EE_Datetime_Field) {
591
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
592
+		}
593
+		if ( ! isset($this->_fields[$fieldname])) {
594
+			$this->_fields[$fieldname] = null;
595
+		}
596
+		$value = $pretty
597
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
598
+			: $field_obj->prepare_for_get($this->_fields[$fieldname]);
599
+		return $value;
600
+	}
601
+
602
+
603
+
604
+	/**
605
+	 * set timezone, formats, and output for EE_Datetime_Field objects
606
+	 *
607
+	 * @param \EE_Datetime_Field $datetime_field
608
+	 * @param bool               $pretty
609
+	 * @param null $date_or_time
610
+	 * @return void
611
+	 * @throws \EE_Error
612
+	 */
613
+	protected function _prepare_datetime_field(
614
+		EE_Datetime_Field $datetime_field,
615
+		$pretty = false,
616
+		$date_or_time = null
617
+	) {
618
+		$datetime_field->set_timezone($this->_timezone);
619
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
620
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
621
+		//set the output returned
622
+		switch ($date_or_time) {
623
+			case 'D' :
624
+				$datetime_field->set_date_time_output('date');
625
+				break;
626
+			case 'T' :
627
+				$datetime_field->set_date_time_output('time');
628
+				break;
629
+			default :
630
+				$datetime_field->set_date_time_output();
631
+		}
632
+	}
633
+
634
+
635
+
636
+	/**
637
+	 * This just takes care of clearing out the cached_properties
638
+	 *
639
+	 * @return void
640
+	 */
641
+	protected function _clear_cached_properties()
642
+	{
643
+		$this->_cached_properties = array();
644
+	}
645
+
646
+
647
+
648
+	/**
649
+	 * This just clears out ONE property if it exists in the cache
650
+	 *
651
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
652
+	 * @return void
653
+	 */
654
+	protected function _clear_cached_property($property_name)
655
+	{
656
+		if (isset($this->_cached_properties[$property_name])) {
657
+			unset($this->_cached_properties[$property_name]);
658
+		}
659
+	}
660
+
661
+
662
+
663
+	/**
664
+	 * Ensures that this related thing is a model object.
665
+	 *
666
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
667
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
668
+	 * @return EE_Base_Class
669
+	 * @throws \EE_Error
670
+	 */
671
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
672
+	{
673
+		$other_model_instance = self::_get_model_instance_with_name(
674
+			self::_get_model_classname($model_name),
675
+			$this->_timezone
676
+		);
677
+		return $other_model_instance->ensure_is_obj($object_or_id);
678
+	}
679
+
680
+
681
+
682
+	/**
683
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
684
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
685
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
686
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
687
+	 *
688
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
689
+	 *                                                     Eg 'Registration'
690
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
691
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
692
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
693
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
694
+	 *                                                     this is HasMany or HABTM.
695
+	 * @throws EE_Error
696
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
697
+	 *                       relation from all
698
+	 */
699
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
700
+	{
701
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
702
+		$index_in_cache = '';
703
+		if ( ! $relationship_to_model) {
704
+			throw new EE_Error(
705
+				sprintf(
706
+					__("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
707
+					$relationName,
708
+					get_class($this)
709
+				)
710
+			);
711
+		}
712
+		if ($clear_all) {
713
+			$obj_removed = true;
714
+			$this->_model_relations[$relationName] = null;
715
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
716
+			$obj_removed = $this->_model_relations[$relationName];
717
+			$this->_model_relations[$relationName] = null;
718
+		} else {
719
+			if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
720
+				&& $object_to_remove_or_index_into_array->ID()
721
+			) {
722
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
723
+				if (is_array($this->_model_relations[$relationName])
724
+					&& ! isset($this->_model_relations[$relationName][$index_in_cache])
725
+				) {
726
+					$index_found_at = null;
727
+					//find this object in the array even though it has a different key
728
+					foreach ($this->_model_relations[$relationName] as $index => $obj) {
729
+						if (
730
+							$obj instanceof EE_Base_Class
731
+							&& (
732
+								$obj == $object_to_remove_or_index_into_array
733
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
734
+							)
735
+						) {
736
+							$index_found_at = $index;
737
+							break;
738
+						}
739
+					}
740
+					if ($index_found_at) {
741
+						$index_in_cache = $index_found_at;
742
+					} else {
743
+						//it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
744
+						//if it wasn't in it to begin with. So we're done
745
+						return $object_to_remove_or_index_into_array;
746
+					}
747
+				}
748
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
749
+				//so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
750
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
751
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
752
+						$index_in_cache = $index;
753
+					}
754
+				}
755
+			} else {
756
+				$index_in_cache = $object_to_remove_or_index_into_array;
757
+			}
758
+			//supposedly we've found it. But it could just be that the client code
759
+			//provided a bad index/object
760
+			if (
761
+			isset(
762
+				$this->_model_relations[$relationName],
763
+				$this->_model_relations[$relationName][$index_in_cache]
764
+			)
765
+			) {
766
+				$obj_removed = $this->_model_relations[$relationName][$index_in_cache];
767
+				unset($this->_model_relations[$relationName][$index_in_cache]);
768
+			} else {
769
+				//that thing was never cached anyways.
770
+				$obj_removed = null;
771
+			}
772
+		}
773
+		return $obj_removed;
774
+	}
775
+
776
+
777
+
778
+	/**
779
+	 * update_cache_after_object_save
780
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
781
+	 * obtained after being saved to the db
782
+	 *
783
+	 * @param string         $relationName       - the type of object that is cached
784
+	 * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
785
+	 * @param string         $current_cache_id   - the ID that was used when originally caching the object
786
+	 * @return boolean TRUE on success, FALSE on fail
787
+	 * @throws \EE_Error
788
+	 */
789
+	public function update_cache_after_object_save(
790
+		$relationName,
791
+		EE_Base_Class $newly_saved_object,
792
+		$current_cache_id = ''
793
+	) {
794
+		// verify that incoming object is of the correct type
795
+		$obj_class = 'EE_' . $relationName;
796
+		if ($newly_saved_object instanceof $obj_class) {
797
+			/* @type EE_Base_Class $newly_saved_object */
798
+			// now get the type of relation
799
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
800
+			// if this is a 1:1 relationship
801
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
802
+				// then just replace the cached object with the newly saved object
803
+				$this->_model_relations[$relationName] = $newly_saved_object;
804
+				return true;
805
+				// or if it's some kind of sordid feral polyamorous relationship...
806
+			} elseif (is_array($this->_model_relations[$relationName])
807
+					  && isset($this->_model_relations[$relationName][$current_cache_id])
808
+			) {
809
+				// then remove the current cached item
810
+				unset($this->_model_relations[$relationName][$current_cache_id]);
811
+				// and cache the newly saved object using it's new ID
812
+				$this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
813
+				return true;
814
+			}
815
+		}
816
+		return false;
817
+	}
818
+
819
+
820
+
821
+	/**
822
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
823
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
824
+	 *
825
+	 * @param string $relationName
826
+	 * @return EE_Base_Class
827
+	 */
828
+	public function get_one_from_cache($relationName)
829
+	{
830
+		$cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
831
+			: null;
832
+		if (is_array($cached_array_or_object)) {
833
+			return array_shift($cached_array_or_object);
834
+		} else {
835
+			return $cached_array_or_object;
836
+		}
837
+	}
838
+
839
+
840
+
841
+	/**
842
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
843
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
844
+	 *
845
+	 * @param string $relationName
846
+	 * @throws \EE_Error
847
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
848
+	 */
849
+	public function get_all_from_cache($relationName)
850
+	{
851
+		$objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
852
+		// if the result is not an array, but exists, make it an array
853
+		$objects = is_array($objects) ? $objects : array($objects);
854
+		//bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
855
+		//basically, if this model object was stored in the session, and these cached model objects
856
+		//already have IDs, let's make sure they're in their model's entity mapper
857
+		//otherwise we will have duplicates next time we call
858
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
859
+		$model = EE_Registry::instance()->load_model($relationName);
860
+		foreach ($objects as $model_object) {
861
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
862
+				//ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
863
+				if ($model_object->ID()) {
864
+					$model->add_to_entity_map($model_object);
865
+				}
866
+			} else {
867
+				throw new EE_Error(
868
+					sprintf(
869
+						__(
870
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
871
+							'event_espresso'
872
+						),
873
+						$relationName,
874
+						gettype($model_object)
875
+					)
876
+				);
877
+			}
878
+		}
879
+		return $objects;
880
+	}
881
+
882
+
883
+
884
+	/**
885
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
886
+	 * matching the given query conditions.
887
+	 *
888
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
889
+	 * @param int   $limit              How many objects to return.
890
+	 * @param array $query_params       Any additional conditions on the query.
891
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
892
+	 *                                  you can indicate just the columns you want returned
893
+	 * @return array|EE_Base_Class[]
894
+	 * @throws \EE_Error
895
+	 */
896
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
897
+	{
898
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
899
+			? $this->get_model()->get_primary_key_field()->get_name()
900
+			: $field_to_order_by;
901
+		$current_value = ! empty($field) ? $this->get($field) : null;
902
+		if (empty($field) || empty($current_value)) {
903
+			return array();
904
+		}
905
+		return $this->get_model()->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
906
+	}
907
+
908
+
909
+
910
+	/**
911
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
912
+	 * matching the given query conditions.
913
+	 *
914
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
915
+	 * @param int   $limit              How many objects to return.
916
+	 * @param array $query_params       Any additional conditions on the query.
917
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
918
+	 *                                  you can indicate just the columns you want returned
919
+	 * @return array|EE_Base_Class[]
920
+	 * @throws \EE_Error
921
+	 */
922
+	public function previous_x(
923
+		$field_to_order_by = null,
924
+		$limit = 1,
925
+		$query_params = array(),
926
+		$columns_to_select = null
927
+	) {
928
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
929
+			? $this->get_model()->get_primary_key_field()->get_name()
930
+			: $field_to_order_by;
931
+		$current_value = ! empty($field) ? $this->get($field) : null;
932
+		if (empty($field) || empty($current_value)) {
933
+			return array();
934
+		}
935
+		return $this->get_model()->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
936
+	}
937
+
938
+
939
+
940
+	/**
941
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
942
+	 * matching the given query conditions.
943
+	 *
944
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
945
+	 * @param array $query_params       Any additional conditions on the query.
946
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
947
+	 *                                  you can indicate just the columns you want returned
948
+	 * @return array|EE_Base_Class
949
+	 * @throws \EE_Error
950
+	 */
951
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
952
+	{
953
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
954
+			? $this->get_model()->get_primary_key_field()->get_name()
955
+			: $field_to_order_by;
956
+		$current_value = ! empty($field) ? $this->get($field) : null;
957
+		if (empty($field) || empty($current_value)) {
958
+			return array();
959
+		}
960
+		return $this->get_model()->next($current_value, $field, $query_params, $columns_to_select);
961
+	}
962
+
963
+
964
+
965
+	/**
966
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
967
+	 * matching the given query conditions.
968
+	 *
969
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
970
+	 * @param array $query_params       Any additional conditions on the query.
971
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
972
+	 *                                  you can indicate just the column you want returned
973
+	 * @return array|EE_Base_Class
974
+	 * @throws \EE_Error
975
+	 */
976
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
977
+	{
978
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
979
+			? $this->get_model()->get_primary_key_field()->get_name()
980
+			: $field_to_order_by;
981
+		$current_value = ! empty($field) ? $this->get($field) : null;
982
+		if (empty($field) || empty($current_value)) {
983
+			return array();
984
+		}
985
+		return $this->get_model()->previous($current_value, $field, $query_params, $columns_to_select);
986
+	}
987
+
988
+
989
+
990
+	/**
991
+	 * Overrides parent because parent expects old models.
992
+	 * This also doesn't do any validation, and won't work for serialized arrays
993
+	 *
994
+	 * @param string $field_name
995
+	 * @param mixed  $field_value_from_db
996
+	 * @throws \EE_Error
997
+	 */
998
+	public function set_from_db($field_name, $field_value_from_db)
999
+	{
1000
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1001
+		if ($field_obj instanceof EE_Model_Field_Base) {
1002
+			//you would think the DB has no NULLs for non-null label fields right? wrong!
1003
+			//eg, a CPT model object could have an entry in the posts table, but no
1004
+			//entry in the meta table. Meaning that all its columns in the meta table
1005
+			//are null! yikes! so when we find one like that, use defaults for its meta columns
1006
+			if ($field_value_from_db === null) {
1007
+				if ($field_obj->is_nullable()) {
1008
+					//if the field allows nulls, then let it be null
1009
+					$field_value = null;
1010
+				} else {
1011
+					$field_value = $field_obj->get_default_value();
1012
+				}
1013
+			} else {
1014
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1015
+			}
1016
+			$this->_fields[$field_name] = $field_value;
1017
+			$this->_clear_cached_property($field_name);
1018
+		}
1019
+	}
1020
+
1021
+
1022
+
1023
+	/**
1024
+	 * verifies that the specified field is of the correct type
1025
+	 *
1026
+	 * @param string $field_name
1027
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1028
+	 *                                (in cases where the same property may be used for different outputs
1029
+	 *                                - i.e. datetime, money etc.)
1030
+	 * @return mixed
1031
+	 * @throws \EE_Error
1032
+	 */
1033
+	public function get($field_name, $extra_cache_ref = null)
1034
+	{
1035
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1036
+	}
1037
+
1038
+
1039
+
1040
+	/**
1041
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1042
+	 *
1043
+	 * @param  string $field_name A valid fieldname
1044
+	 * @return mixed              Whatever the raw value stored on the property is.
1045
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1046
+	 */
1047
+	public function get_raw($field_name)
1048
+	{
1049
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1050
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1051
+			? $this->_fields[$field_name]->format('U')
1052
+			: $this->_fields[$field_name];
1053
+	}
1054
+
1055
+
1056
+
1057
+	/**
1058
+	 * This is used to return the internal DateTime object used for a field that is a
1059
+	 * EE_Datetime_Field.
1060
+	 *
1061
+	 * @param string $field_name               The field name retrieving the DateTime object.
1062
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1063
+	 * @throws \EE_Error
1064
+	 *                                         an error is set and false returned.  If the field IS an
1065
+	 *                                         EE_Datetime_Field and but the field value is null, then
1066
+	 *                                         just null is returned (because that indicates that likely
1067
+	 *                                         this field is nullable).
1068
+	 */
1069
+	public function get_DateTime_object($field_name)
1070
+	{
1071
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1072
+		if ( ! $field_settings instanceof EE_Datetime_Field) {
1073
+			EE_Error::add_error(
1074
+				sprintf(
1075
+					__(
1076
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1077
+						'event_espresso'
1078
+					),
1079
+					$field_name
1080
+				),
1081
+				__FILE__,
1082
+				__FUNCTION__,
1083
+				__LINE__
1084
+			);
1085
+			return false;
1086
+		}
1087
+		return $this->_fields[$field_name];
1088
+	}
1089
+
1090
+
1091
+
1092
+	/**
1093
+	 * To be used in template to immediately echo out the value, and format it for output.
1094
+	 * Eg, should call stripslashes and whatnot before echoing
1095
+	 *
1096
+	 * @param string $field_name      the name of the field as it appears in the DB
1097
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1098
+	 *                                (in cases where the same property may be used for different outputs
1099
+	 *                                - i.e. datetime, money etc.)
1100
+	 * @return void
1101
+	 * @throws \EE_Error
1102
+	 */
1103
+	public function e($field_name, $extra_cache_ref = null)
1104
+	{
1105
+		echo $this->get_pretty($field_name, $extra_cache_ref);
1106
+	}
1107
+
1108
+
1109
+
1110
+	/**
1111
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1112
+	 * can be easily used as the value of form input.
1113
+	 *
1114
+	 * @param string $field_name
1115
+	 * @return void
1116
+	 * @throws \EE_Error
1117
+	 */
1118
+	public function f($field_name)
1119
+	{
1120
+		$this->e($field_name, 'form_input');
1121
+	}
1122
+
1123
+
1124
+
1125
+	/**
1126
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1127
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1128
+	 * to see what options are available.
1129
+	 * @param string $field_name
1130
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1131
+	 *                                (in cases where the same property may be used for different outputs
1132
+	 *                                - i.e. datetime, money etc.)
1133
+	 * @return mixed
1134
+	 * @throws \EE_Error
1135
+	 */
1136
+	public function get_pretty($field_name, $extra_cache_ref = null)
1137
+	{
1138
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1139
+	}
1140
+
1141
+
1142
+
1143
+	/**
1144
+	 * This simply returns the datetime for the given field name
1145
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1146
+	 * (and the equivalent e_date, e_time, e_datetime).
1147
+	 *
1148
+	 * @access   protected
1149
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1150
+	 * @param string   $dt_frmt      valid datetime format used for date
1151
+	 *                               (if '' then we just use the default on the field,
1152
+	 *                               if NULL we use the last-used format)
1153
+	 * @param string   $tm_frmt      Same as above except this is for time format
1154
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1155
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1156
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1157
+	 *                               if field is not a valid dtt field, or void if echoing
1158
+	 * @throws \EE_Error
1159
+	 */
1160
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1161
+	{
1162
+		// clear cached property
1163
+		$this->_clear_cached_property($field_name);
1164
+		//reset format properties because they are used in get()
1165
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1166
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1167
+		if ($echo) {
1168
+			$this->e($field_name, $date_or_time);
1169
+			return '';
1170
+		}
1171
+		return $this->get($field_name, $date_or_time);
1172
+	}
1173
+
1174
+
1175
+
1176
+	/**
1177
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1178
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1179
+	 * other echoes the pretty value for dtt)
1180
+	 *
1181
+	 * @param  string $field_name name of model object datetime field holding the value
1182
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1183
+	 * @return string            datetime value formatted
1184
+	 * @throws \EE_Error
1185
+	 */
1186
+	public function get_date($field_name, $format = '')
1187
+	{
1188
+		return $this->_get_datetime($field_name, $format, null, 'D');
1189
+	}
1190
+
1191
+
1192
+
1193
+	/**
1194
+	 * @param      $field_name
1195
+	 * @param string $format
1196
+	 * @throws \EE_Error
1197
+	 */
1198
+	public function e_date($field_name, $format = '')
1199
+	{
1200
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1201
+	}
1202
+
1203
+
1204
+
1205
+	/**
1206
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1207
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1208
+	 * other echoes the pretty value for dtt)
1209
+	 *
1210
+	 * @param  string $field_name name of model object datetime field holding the value
1211
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1212
+	 * @return string             datetime value formatted
1213
+	 * @throws \EE_Error
1214
+	 */
1215
+	public function get_time($field_name, $format = '')
1216
+	{
1217
+		return $this->_get_datetime($field_name, null, $format, 'T');
1218
+	}
1219
+
1220
+
1221
+
1222
+	/**
1223
+	 * @param      $field_name
1224
+	 * @param string $format
1225
+	 * @throws \EE_Error
1226
+	 */
1227
+	public function e_time($field_name, $format = '')
1228
+	{
1229
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1230
+	}
1231
+
1232
+
1233
+
1234
+	/**
1235
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1236
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1237
+	 * other echoes the pretty value for dtt)
1238
+	 *
1239
+	 * @param  string $field_name name of model object datetime field holding the value
1240
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1241
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1242
+	 * @return string             datetime value formatted
1243
+	 * @throws \EE_Error
1244
+	 */
1245
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1246
+	{
1247
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1248
+	}
1249
+
1250
+
1251
+
1252
+	/**
1253
+	 * @param string $field_name
1254
+	 * @param string $dt_frmt
1255
+	 * @param string $tm_frmt
1256
+	 * @throws \EE_Error
1257
+	 */
1258
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1259
+	{
1260
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1261
+	}
1262
+
1263
+
1264
+
1265
+	/**
1266
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1267
+	 *
1268
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1269
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1270
+	 *                           on the object will be used.
1271
+	 * @return string Date and time string in set locale or false if no field exists for the given
1272
+	 * @throws \EE_Error
1273
+	 *                           field name.
1274
+	 */
1275
+	public function get_i18n_datetime($field_name, $format = '')
1276
+	{
1277
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1278
+		return date_i18n(
1279
+			$format,
1280
+			EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1281
+		);
1282
+	}
1283
+
1284
+
1285
+
1286
+	/**
1287
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1288
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1289
+	 * thrown.
1290
+	 *
1291
+	 * @param  string $field_name The field name being checked
1292
+	 * @throws EE_Error
1293
+	 * @return EE_Datetime_Field
1294
+	 */
1295
+	protected function _get_dtt_field_settings($field_name)
1296
+	{
1297
+		$field = $this->get_model()->field_settings_for($field_name);
1298
+		//check if field is dtt
1299
+		if ($field instanceof EE_Datetime_Field) {
1300
+			return $field;
1301
+		} else {
1302
+			throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1303
+				'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1304
+		}
1305
+	}
1306
+
1307
+
1308
+
1309
+
1310
+	/**
1311
+	 * NOTE ABOUT BELOW:
1312
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1313
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1314
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1315
+	 * method and make sure you send the entire datetime value for setting.
1316
+	 */
1317
+	/**
1318
+	 * sets the time on a datetime property
1319
+	 *
1320
+	 * @access protected
1321
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1322
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1323
+	 * @throws \EE_Error
1324
+	 */
1325
+	protected function _set_time_for($time, $fieldname)
1326
+	{
1327
+		$this->_set_date_time('T', $time, $fieldname);
1328
+	}
1329
+
1330
+
1331
+
1332
+	/**
1333
+	 * sets the date on a datetime property
1334
+	 *
1335
+	 * @access protected
1336
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1337
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1338
+	 * @throws \EE_Error
1339
+	 */
1340
+	protected function _set_date_for($date, $fieldname)
1341
+	{
1342
+		$this->_set_date_time('D', $date, $fieldname);
1343
+	}
1344
+
1345
+
1346
+
1347
+	/**
1348
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1349
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1350
+	 *
1351
+	 * @access protected
1352
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1353
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1354
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1355
+	 *                                        EE_Datetime_Field property)
1356
+	 * @throws \EE_Error
1357
+	 */
1358
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1359
+	{
1360
+		$field = $this->_get_dtt_field_settings($fieldname);
1361
+		$field->set_timezone($this->_timezone);
1362
+		$field->set_date_format($this->_dt_frmt);
1363
+		$field->set_time_format($this->_tm_frmt);
1364
+		switch ($what) {
1365
+			case 'T' :
1366
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1367
+					$datetime_value,
1368
+					$this->_fields[$fieldname]
1369
+				);
1370
+				break;
1371
+			case 'D' :
1372
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1373
+					$datetime_value,
1374
+					$this->_fields[$fieldname]
1375
+				);
1376
+				break;
1377
+			case 'B' :
1378
+				$this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1379
+				break;
1380
+		}
1381
+		$this->_clear_cached_property($fieldname);
1382
+	}
1383
+
1384
+
1385
+
1386
+	/**
1387
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1388
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1389
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1390
+	 * that could lead to some unexpected results!
1391
+	 *
1392
+	 * @access public
1393
+	 * @param string               $field_name This is the name of the field on the object that contains the date/time
1394
+	 *                                         value being returned.
1395
+	 * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1396
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1397
+	 * @param string               $prepend    You can include something to prepend on the timestamp
1398
+	 * @param string               $append     You can include something to append on the timestamp
1399
+	 * @throws EE_Error
1400
+	 * @return string timestamp
1401
+	 */
1402
+	public function display_in_my_timezone(
1403
+		$field_name,
1404
+		$callback = 'get_datetime',
1405
+		$args = null,
1406
+		$prepend = '',
1407
+		$append = ''
1408
+	) {
1409
+		$timezone = EEH_DTT_Helper::get_timezone();
1410
+		if ($timezone === $this->_timezone) {
1411
+			return '';
1412
+		}
1413
+		$original_timezone = $this->_timezone;
1414
+		$this->set_timezone($timezone);
1415
+		$fn = (array)$field_name;
1416
+		$args = array_merge($fn, (array)$args);
1417
+		if ( ! method_exists($this, $callback)) {
1418
+			throw new EE_Error(
1419
+				sprintf(
1420
+					__(
1421
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1422
+						'event_espresso'
1423
+					),
1424
+					$callback
1425
+				)
1426
+			);
1427
+		}
1428
+		$args = (array)$args;
1429
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1430
+		$this->set_timezone($original_timezone);
1431
+		return $return;
1432
+	}
1433
+
1434
+
1435
+
1436
+	/**
1437
+	 * Deletes this model object.
1438
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1439
+	 * override
1440
+	 * `EE_Base_Class::_delete` NOT this class.
1441
+	 *
1442
+	 * @return boolean | int
1443
+	 * @throws \EE_Error
1444
+	 */
1445
+	public function delete()
1446
+	{
1447
+		/**
1448
+		 * Called just before the `EE_Base_Class::_delete` method call.
1449
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1450
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1451
+		 * soft deletes (trash) the object and does not permanently delete it.
1452
+		 *
1453
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1454
+		 */
1455
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1456
+		$result = $this->_delete();
1457
+		/**
1458
+		 * Called just after the `EE_Base_Class::_delete` method call.
1459
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1460
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1461
+		 * soft deletes (trash) the object and does not permanently delete it.
1462
+		 *
1463
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1464
+		 * @param boolean       $result
1465
+		 */
1466
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1467
+		return $result;
1468
+	}
1469
+
1470
+
1471
+
1472
+	/**
1473
+	 * Calls the specific delete method for the instantiated class.
1474
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1475
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1476
+	 * `EE_Base_Class::delete`
1477
+	 *
1478
+	 * @return bool|int
1479
+	 * @throws \EE_Error
1480
+	 */
1481
+	protected function _delete()
1482
+	{
1483
+		return $this->delete_permanently();
1484
+	}
1485
+
1486
+
1487
+
1488
+	/**
1489
+	 * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1490
+	 * error)
1491
+	 *
1492
+	 * @return bool | int
1493
+	 * @throws \EE_Error
1494
+	 */
1495
+	public function delete_permanently()
1496
+	{
1497
+		/**
1498
+		 * Called just before HARD deleting a model object
1499
+		 *
1500
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1501
+		 */
1502
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1503
+		$model = $this->get_model();
1504
+		$result = $model->delete_permanently_by_ID($this->ID());
1505
+		$this->refresh_cache_of_related_objects();
1506
+		/**
1507
+		 * Called just after HARD deleting a model object
1508
+		 *
1509
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1510
+		 * @param boolean       $result
1511
+		 */
1512
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1513
+		return $result;
1514
+	}
1515
+
1516
+
1517
+
1518
+	/**
1519
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1520
+	 * related model objects
1521
+	 *
1522
+	 * @throws \EE_Error
1523
+	 */
1524
+	public function refresh_cache_of_related_objects()
1525
+	{
1526
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1527
+			if ( ! empty($this->_model_relations[$relation_name])) {
1528
+				$related_objects = $this->_model_relations[$relation_name];
1529
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1530
+					//this relation only stores a single model object, not an array
1531
+					//but let's make it consistent
1532
+					$related_objects = array($related_objects);
1533
+				}
1534
+				foreach ($related_objects as $related_object) {
1535
+					//only refresh their cache if they're in memory
1536
+					if ($related_object instanceof EE_Base_Class) {
1537
+						$related_object->clear_cache($this->get_model()->get_this_model_name(), $this);
1538
+					}
1539
+				}
1540
+			}
1541
+		}
1542
+	}
1543
+
1544
+
1545
+
1546
+	/**
1547
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1548
+	 * object just before saving.
1549
+	 *
1550
+	 * @access public
1551
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1552
+	 *                                 if provided during the save() method (often client code will change the fields'
1553
+	 *                                 values before calling save)
1554
+	 * @throws \EE_Error
1555
+	 * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1556
+	 *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1557
+	 */
1558
+	public function save($set_cols_n_values = array())
1559
+	{
1560
+		/**
1561
+		 * Filters the fields we're about to save on the model object
1562
+		 *
1563
+		 * @param array         $set_cols_n_values
1564
+		 * @param EE_Base_Class $model_object
1565
+		 */
1566
+		$set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1567
+			$this);
1568
+		//set attributes as provided in $set_cols_n_values
1569
+		foreach ($set_cols_n_values as $column => $value) {
1570
+			$this->set($column, $value);
1571
+		}
1572
+		/**
1573
+		 * Saving a model object.
1574
+		 * Before we perform a save, this action is fired.
1575
+		 *
1576
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1577
+		 */
1578
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1579
+		if ( ! $this->allow_persist()) {
1580
+			return 0;
1581
+		}
1582
+		//now get current attribute values
1583
+		$save_cols_n_values = $this->_fields;
1584
+		//if the object already has an ID, update it. Otherwise, insert it
1585
+		//also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1586
+		$old_assumption_concerning_value_preparation = $this->get_model()
1587
+															->get_assumption_concerning_values_already_prepared_by_model_object();
1588
+		$this->get_model()->assume_values_already_prepared_by_model_object(true);
1589
+		//does this model have an autoincrement PK?
1590
+		if ($this->get_model()->has_primary_key_field()) {
1591
+			if ($this->get_model()->get_primary_key_field()->is_auto_increment()) {
1592
+				//ok check if it's set, if so: update; if not, insert
1593
+				if ( ! empty($save_cols_n_values[self::_get_primary_key_name(get_class($this))])) {
1594
+					$results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1595
+				} else {
1596
+					unset($save_cols_n_values[self::_get_primary_key_name(get_class($this))]);
1597
+					$results = $this->get_model()->insert($save_cols_n_values);
1598
+					if ($results) {
1599
+						//if successful, set the primary key
1600
+						//but don't use the normal SET method, because it will check if
1601
+						//an item with the same ID exists in the mapper & db, then
1602
+						//will find it in the db (because we just added it) and THAT object
1603
+						//will get added to the mapper before we can add this one!
1604
+						//but if we just avoid using the SET method, all that headache can be avoided
1605
+						$pk_field_name = self::_get_primary_key_name(get_class($this));
1606
+						$this->_fields[$pk_field_name] = $results;
1607
+						$this->_clear_cached_property($pk_field_name);
1608
+						$this->get_model()->add_to_entity_map($this);
1609
+						$this->_update_cached_related_model_objs_fks();
1610
+					}
1611
+				}
1612
+			} else {//PK is NOT auto-increment
1613
+				//so check if one like it already exists in the db
1614
+				if ($this->get_model()->exists_by_ID($this->ID())) {
1615
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1616
+						throw new EE_Error(
1617
+							sprintf(
1618
+								__('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1619
+									'event_espresso'),
1620
+								get_class($this),
1621
+								get_class($this->get_model()) . '::instance()->add_to_entity_map()',
1622
+								get_class($this->get_model()) . '::instance()->get_one_by_ID()',
1623
+								'<br />'
1624
+							)
1625
+						);
1626
+					}
1627
+					$results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1628
+				} else {
1629
+					$results = $this->get_model()->insert($save_cols_n_values);
1630
+					$this->_update_cached_related_model_objs_fks();
1631
+				}
1632
+			}
1633
+		} else {//there is NO primary key
1634
+			$already_in_db = false;
1635
+			foreach ($this->get_model()->unique_indexes() as $index) {
1636
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1637
+				if ($this->get_model()->exists(array($uniqueness_where_params))) {
1638
+					$already_in_db = true;
1639
+				}
1640
+			}
1641
+			if ($already_in_db) {
1642
+				$combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1643
+					$this->get_model()->get_combined_primary_key_fields());
1644
+				$results = $this->get_model()->update($save_cols_n_values, $combined_pk_fields_n_values);
1645
+			} else {
1646
+				$results = $this->get_model()->insert($save_cols_n_values);
1647
+			}
1648
+		}
1649
+		//restore the old assumption about values being prepared by the model object
1650
+		$this->get_model()
1651
+			 ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1652
+		/**
1653
+		 * After saving the model object this action is called
1654
+		 *
1655
+		 * @param EE_Base_Class $model_object which was just saved
1656
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1657
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1658
+		 */
1659
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1660
+		return $results;
1661
+	}
1662
+
1663
+
1664
+
1665
+	/**
1666
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1667
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1668
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1669
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1670
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1671
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1672
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1673
+	 *
1674
+	 * @return void
1675
+	 * @throws \EE_Error
1676
+	 */
1677
+	protected function _update_cached_related_model_objs_fks()
1678
+	{
1679
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1680
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1681
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1682
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1683
+						$this->get_model()->get_this_model_name()
1684
+					);
1685
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1686
+					if ($related_model_obj_in_cache->ID()) {
1687
+						$related_model_obj_in_cache->save();
1688
+					}
1689
+				}
1690
+			}
1691
+		}
1692
+	}
1693
+
1694
+
1695
+
1696
+	/**
1697
+	 * Saves this model object and its NEW cached relations to the database.
1698
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1699
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1700
+	 * because otherwise, there's a potential for infinite looping of saving
1701
+	 * Saves the cached related model objects, and ensures the relation between them
1702
+	 * and this object and properly setup
1703
+	 *
1704
+	 * @return int ID of new model object on save; 0 on failure+
1705
+	 * @throws \EE_Error
1706
+	 */
1707
+	public function save_new_cached_related_model_objs()
1708
+	{
1709
+		//make sure this has been saved
1710
+		if ( ! $this->ID()) {
1711
+			$id = $this->save();
1712
+		} else {
1713
+			$id = $this->ID();
1714
+		}
1715
+		//now save all the NEW cached model objects  (ie they don't exist in the DB)
1716
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1717
+			if ($this->_model_relations[$relationName]) {
1718
+				//is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1719
+				//or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1720
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1721
+					//add a relation to that relation type (which saves the appropriate thing in the process)
1722
+					//but ONLY if it DOES NOT exist in the DB
1723
+					/* @var $related_model_obj EE_Base_Class */
1724
+					$related_model_obj = $this->_model_relations[$relationName];
1725
+					//					if( ! $related_model_obj->ID()){
1726
+					$this->_add_relation_to($related_model_obj, $relationName);
1727
+					$related_model_obj->save_new_cached_related_model_objs();
1728
+					//					}
1729
+				} else {
1730
+					foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1731
+						//add a relation to that relation type (which saves the appropriate thing in the process)
1732
+						//but ONLY if it DOES NOT exist in the DB
1733
+						//						if( ! $related_model_obj->ID()){
1734
+						$this->_add_relation_to($related_model_obj, $relationName);
1735
+						$related_model_obj->save_new_cached_related_model_objs();
1736
+						//						}
1737
+					}
1738
+				}
1739
+			}
1740
+		}
1741
+		return $id;
1742
+	}
1743
+
1744
+
1745
+
1746
+	/**
1747
+	 * for getting a model while instantiated.
1748
+	 *
1749
+	 * @return \EEM_Base | \EEM_CPT_Base
1750
+	 */
1751
+	public function get_model()
1752
+	{
1753
+		$modelName = self::_get_model_classname(get_class($this));
1754
+		return self::_get_model_instance_with_name($modelName, $this->_timezone);
1755
+	}
1756
+
1757
+
1758
+
1759
+	/**
1760
+	 * @param $props_n_values
1761
+	 * @param $classname
1762
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1763
+	 * @throws \EE_Error
1764
+	 */
1765
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1766
+	{
1767
+		//TODO: will not work for Term_Relationships because they have no PK!
1768
+		$primary_id_ref = self::_get_primary_key_name($classname);
1769
+		if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1770
+			$id = $props_n_values[$primary_id_ref];
1771
+			return self::_get_model($classname)->get_from_entity_map($id);
1772
+		}
1773
+		return false;
1774
+	}
1775
+
1776
+
1777
+
1778
+	/**
1779
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1780
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1781
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
1782
+	 * we return false.
1783
+	 *
1784
+	 * @param  array  $props_n_values   incoming array of properties and their values
1785
+	 * @param  string $classname        the classname of the child class
1786
+	 * @param null    $timezone
1787
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
1788
+	 *                                  date_format and the second value is the time format
1789
+	 * @return mixed (EE_Base_Class|bool)
1790
+	 * @throws \EE_Error
1791
+	 */
1792
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1793
+	{
1794
+		$existing = null;
1795
+		if (self::_get_model($classname)->has_primary_key_field()) {
1796
+			$primary_id_ref = self::_get_primary_key_name($classname);
1797
+			if (array_key_exists($primary_id_ref, $props_n_values)
1798
+				&& ! empty($props_n_values[$primary_id_ref])
1799
+			) {
1800
+				$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1801
+					$props_n_values[$primary_id_ref]
1802
+				);
1803
+			}
1804
+		} elseif (self::_get_model($classname, $timezone)->has_all_combined_primary_key_fields($props_n_values)) {
1805
+			//no primary key on this model, but there's still a matching item in the DB
1806
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1807
+				self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1808
+			);
1809
+		}
1810
+		if ($existing) {
1811
+			//set date formats if present before setting values
1812
+			if ( ! empty($date_formats) && is_array($date_formats)) {
1813
+				$existing->set_date_format($date_formats[0]);
1814
+				$existing->set_time_format($date_formats[1]);
1815
+			} else {
1816
+				//set default formats for date and time
1817
+				$existing->set_date_format(get_option('date_format'));
1818
+				$existing->set_time_format(get_option('time_format'));
1819
+			}
1820
+			foreach ($props_n_values as $property => $field_value) {
1821
+				$existing->set($property, $field_value);
1822
+			}
1823
+			return $existing;
1824
+		} else {
1825
+			return false;
1826
+		}
1827
+	}
1828
+
1829
+
1830
+
1831
+	/**
1832
+	 * Gets the EEM_*_Model for this class
1833
+	 *
1834
+	 * @access public now, as this is more convenient
1835
+	 * @param      $classname
1836
+	 * @param null $timezone
1837
+	 * @throws EE_Error
1838
+	 * @return EEM_Base
1839
+	 */
1840
+	protected static function _get_model($classname, $timezone = null)
1841
+	{
1842
+		//find model for this class
1843
+		if ( ! $classname) {
1844
+			throw new EE_Error(
1845
+				sprintf(
1846
+					__(
1847
+						"What were you thinking calling _get_model(%s)?? You need to specify the class name",
1848
+						"event_espresso"
1849
+					),
1850
+					$classname
1851
+				)
1852
+			);
1853
+		}
1854
+		$modelName = self::_get_model_classname($classname);
1855
+		return self::_get_model_instance_with_name($modelName, $timezone);
1856
+	}
1857
+
1858
+
1859
+
1860
+	/**
1861
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1862
+	 *
1863
+	 * @param string $model_classname
1864
+	 * @param null   $timezone
1865
+	 * @return EEM_Base
1866
+	 */
1867
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1868
+	{
1869
+		$model_classname = str_replace('EEM_', '', $model_classname);
1870
+		$model = EE_Registry::instance()->load_model($model_classname);
1871
+		$model->set_timezone($timezone);
1872
+		return $model;
1873
+	}
1874
+
1875
+
1876
+
1877
+	/**
1878
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
1879
+	 * Also works if a model class's classname is provided (eg EE_Registration).
1880
+	 *
1881
+	 * @param null $model_name
1882
+	 * @return string like EEM_Attendee
1883
+	 */
1884
+	private static function _get_model_classname($model_name = null)
1885
+	{
1886
+		if (strpos($model_name, "EE_") === 0) {
1887
+			$model_classname = str_replace("EE_", "EEM_", $model_name);
1888
+		} else {
1889
+			$model_classname = "EEM_" . $model_name;
1890
+		}
1891
+		return $model_classname;
1892
+	}
1893
+
1894
+
1895
+
1896
+	/**
1897
+	 * returns the name of the primary key attribute
1898
+	 *
1899
+	 * @param null $classname
1900
+	 * @throws EE_Error
1901
+	 * @return string
1902
+	 */
1903
+	protected static function _get_primary_key_name($classname = null)
1904
+	{
1905
+		if ( ! $classname) {
1906
+			throw new EE_Error(
1907
+				sprintf(
1908
+					__("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
1909
+					$classname
1910
+				)
1911
+			);
1912
+		}
1913
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
1914
+	}
1915
+
1916
+
1917
+
1918
+	/**
1919
+	 * Gets the value of the primary key.
1920
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
1921
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
1922
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
1923
+	 *
1924
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
1925
+	 * @throws \EE_Error
1926
+	 */
1927
+	public function ID()
1928
+	{
1929
+		//now that we know the name of the variable, use a variable variable to get its value and return its
1930
+		if ($this->get_model()->has_primary_key_field()) {
1931
+			return $this->_fields[self::_get_primary_key_name(get_class($this))];
1932
+		} else {
1933
+			return $this->get_model()->get_index_primary_key_string($this->_fields);
1934
+		}
1935
+	}
1936
+
1937
+
1938
+
1939
+	/**
1940
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
1941
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
1942
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
1943
+	 *
1944
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
1945
+	 * @param string $relationName                     eg 'Events','Question',etc.
1946
+	 *                                                 an attendee to a group, you also want to specify which role they
1947
+	 *                                                 will have in that group. So you would use this parameter to
1948
+	 *                                                 specify array('role-column-name'=>'role-id')
1949
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
1950
+	 *                                                 allow you to further constrict the relation to being added.
1951
+	 *                                                 However, keep in mind that the columns (keys) given must match a
1952
+	 *                                                 column on the JOIN table and currently only the HABTM models
1953
+	 *                                                 accept these additional conditions.  Also remember that if an
1954
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
1955
+	 *                                                 NEW row is created in the join table.
1956
+	 * @param null   $cache_id
1957
+	 * @throws EE_Error
1958
+	 * @return EE_Base_Class the object the relation was added to
1959
+	 */
1960
+	public function _add_relation_to(
1961
+		$otherObjectModelObjectOrID,
1962
+		$relationName,
1963
+		$extra_join_model_fields_n_values = array(),
1964
+		$cache_id = null
1965
+	) {
1966
+		//if this thing exists in the DB, save the relation to the DB
1967
+		if ($this->ID()) {
1968
+			$otherObject = $this->get_model()
1969
+								->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
1970
+									$extra_join_model_fields_n_values);
1971
+			//clear cache so future get_many_related and get_first_related() return new results.
1972
+			$this->clear_cache($relationName, $otherObject, true);
1973
+			if ($otherObject instanceof EE_Base_Class) {
1974
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
1975
+			}
1976
+		} else {
1977
+			//this thing doesn't exist in the DB,  so just cache it
1978
+			if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
1979
+				throw new EE_Error(sprintf(
1980
+					__('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
1981
+						'event_espresso'),
1982
+					$otherObjectModelObjectOrID,
1983
+					get_class($this)
1984
+				));
1985
+			} else {
1986
+				$otherObject = $otherObjectModelObjectOrID;
1987
+			}
1988
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
1989
+		}
1990
+		if ($otherObject instanceof EE_Base_Class) {
1991
+			//fix the reciprocal relation too
1992
+			if ($otherObject->ID()) {
1993
+				//its saved so assumed relations exist in the DB, so we can just
1994
+				//clear the cache so future queries use the updated info in the DB
1995
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), null, true);
1996
+			} else {
1997
+				//it's not saved, so it caches relations like this
1998
+				$otherObject->cache($this->get_model()->get_this_model_name(), $this);
1999
+			}
2000
+		}
2001
+		return $otherObject;
2002
+	}
2003
+
2004
+
2005
+
2006
+	/**
2007
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2008
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2009
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2010
+	 * from the cache
2011
+	 *
2012
+	 * @param mixed  $otherObjectModelObjectOrID
2013
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2014
+	 *                to the DB yet
2015
+	 * @param string $relationName
2016
+	 * @param array  $where_query
2017
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2018
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2019
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2020
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2021
+	 *                created in the join table.
2022
+	 * @return EE_Base_Class the relation was removed from
2023
+	 * @throws \EE_Error
2024
+	 */
2025
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2026
+	{
2027
+		if ($this->ID()) {
2028
+			//if this exists in the DB, save the relation change to the DB too
2029
+			$otherObject = $this->get_model()
2030
+								->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2031
+									$where_query);
2032
+			$this->clear_cache($relationName, $otherObject);
2033
+		} else {
2034
+			//this doesn't exist in the DB, just remove it from the cache
2035
+			$otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2036
+		}
2037
+		if ($otherObject instanceof EE_Base_Class) {
2038
+			$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2039
+		}
2040
+		return $otherObject;
2041
+	}
2042
+
2043
+
2044
+
2045
+	/**
2046
+	 * Removes ALL the related things for the $relationName.
2047
+	 *
2048
+	 * @param string $relationName
2049
+	 * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2050
+	 * @return EE_Base_Class
2051
+	 * @throws \EE_Error
2052
+	 */
2053
+	public function _remove_relations($relationName, $where_query_params = array())
2054
+	{
2055
+		if ($this->ID()) {
2056
+			//if this exists in the DB, save the relation change to the DB too
2057
+			$otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2058
+			$this->clear_cache($relationName, null, true);
2059
+		} else {
2060
+			//this doesn't exist in the DB, just remove it from the cache
2061
+			$otherObjects = $this->clear_cache($relationName, null, true);
2062
+		}
2063
+		if (is_array($otherObjects)) {
2064
+			foreach ($otherObjects as $otherObject) {
2065
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2066
+			}
2067
+		}
2068
+		return $otherObjects;
2069
+	}
2070
+
2071
+
2072
+
2073
+	/**
2074
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2075
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2076
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2077
+	 * because we want to get even deleted items etc.
2078
+	 *
2079
+	 * @param string $relationName key in the model's _model_relations array
2080
+	 * @param array  $query_params like EEM_Base::get_all
2081
+	 * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2082
+	 * @throws \EE_Error
2083
+	 *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2084
+	 *                             you want IDs
2085
+	 */
2086
+	public function get_many_related($relationName, $query_params = array())
2087
+	{
2088
+		if ($this->ID()) {
2089
+			//this exists in the DB, so get the related things from either the cache or the DB
2090
+			//if there are query parameters, forget about caching the related model objects.
2091
+			if ($query_params) {
2092
+				$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2093
+			} else {
2094
+				//did we already cache the result of this query?
2095
+				$cached_results = $this->get_all_from_cache($relationName);
2096
+				if ( ! $cached_results) {
2097
+					$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2098
+					//if no query parameters were passed, then we got all the related model objects
2099
+					//for that relation. We can cache them then.
2100
+					foreach ($related_model_objects as $related_model_object) {
2101
+						$this->cache($relationName, $related_model_object);
2102
+					}
2103
+				} else {
2104
+					$related_model_objects = $cached_results;
2105
+				}
2106
+			}
2107
+		} else {
2108
+			//this doesn't exist in the DB, so just get the related things from the cache
2109
+			$related_model_objects = $this->get_all_from_cache($relationName);
2110
+		}
2111
+		return $related_model_objects;
2112
+	}
2113
+
2114
+
2115
+
2116
+	/**
2117
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2118
+	 * unless otherwise specified in the $query_params
2119
+	 *
2120
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2121
+	 * @param array  $query_params   like EEM_Base::get_all's
2122
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2123
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2124
+	 *                               that by the setting $distinct to TRUE;
2125
+	 * @return int
2126
+	 */
2127
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2128
+	{
2129
+		return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2130
+	}
2131
+
2132
+
2133
+
2134
+	/**
2135
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2136
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2137
+	 *
2138
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2139
+	 * @param array  $query_params  like EEM_Base::get_all's
2140
+	 * @param string $field_to_sum  name of field to count by.
2141
+	 *                              By default, uses primary key (which doesn't make much sense, so you should probably
2142
+	 *                              change it)
2143
+	 * @return int
2144
+	 */
2145
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2146
+	{
2147
+		return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2148
+	}
2149
+
2150
+
2151
+
2152
+	/**
2153
+	 * Gets the first (ie, one) related model object of the specified type.
2154
+	 *
2155
+	 * @param string $relationName key in the model's _model_relations array
2156
+	 * @param array  $query_params like EEM_Base::get_all
2157
+	 * @return EE_Base_Class (not an array, a single object)
2158
+	 * @throws \EE_Error
2159
+	 */
2160
+	public function get_first_related($relationName, $query_params = array())
2161
+	{
2162
+		if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2163
+			//if they've provided some query parameters, don't bother trying to cache the result
2164
+			//also make sure we're not caching the result of get_first_related
2165
+			//on a relation which should have an array of objects (because the cache might have an array of objects)
2166
+			if ($query_params
2167
+				|| ! $this->get_model()->related_settings_for($relationName)
2168
+					 instanceof
2169
+					 EE_Belongs_To_Relation
2170
+			) {
2171
+				$related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2172
+			} else {
2173
+				//first, check if we've already cached the result of this query
2174
+				$cached_result = $this->get_one_from_cache($relationName);
2175
+				if ( ! $cached_result) {
2176
+					$related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2177
+					$this->cache($relationName, $related_model_object);
2178
+				} else {
2179
+					$related_model_object = $cached_result;
2180
+				}
2181
+			}
2182
+		} else {
2183
+			$related_model_object = null;
2184
+			//this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2185
+			if ($this->get_model()->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2186
+				$related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2187
+			}
2188
+			//this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2189
+			if ( ! $related_model_object) {
2190
+				$related_model_object = $this->get_one_from_cache($relationName);
2191
+			}
2192
+		}
2193
+		return $related_model_object;
2194
+	}
2195
+
2196
+
2197
+
2198
+	/**
2199
+	 * Does a delete on all related objects of type $relationName and removes
2200
+	 * the current model object's relation to them. If they can't be deleted (because
2201
+	 * of blocking related model objects) does nothing. If the related model objects are
2202
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2203
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2204
+	 *
2205
+	 * @param string $relationName
2206
+	 * @param array  $query_params like EEM_Base::get_all's
2207
+	 * @return int how many deleted
2208
+	 * @throws \EE_Error
2209
+	 */
2210
+	public function delete_related($relationName, $query_params = array())
2211
+	{
2212
+		if ($this->ID()) {
2213
+			$count = $this->get_model()->delete_related($this, $relationName, $query_params);
2214
+		} else {
2215
+			$count = count($this->get_all_from_cache($relationName));
2216
+			$this->clear_cache($relationName, null, true);
2217
+		}
2218
+		return $count;
2219
+	}
2220
+
2221
+
2222
+
2223
+	/**
2224
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2225
+	 * the current model object's relation to them. If they can't be deleted (because
2226
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2227
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2228
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2229
+	 *
2230
+	 * @param string $relationName
2231
+	 * @param array  $query_params like EEM_Base::get_all's
2232
+	 * @return int how many deleted (including those soft deleted)
2233
+	 * @throws \EE_Error
2234
+	 */
2235
+	public function delete_related_permanently($relationName, $query_params = array())
2236
+	{
2237
+		if ($this->ID()) {
2238
+			$count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2239
+		} else {
2240
+			$count = count($this->get_all_from_cache($relationName));
2241
+		}
2242
+		$this->clear_cache($relationName, null, true);
2243
+		return $count;
2244
+	}
2245
+
2246
+
2247
+
2248
+	/**
2249
+	 * is_set
2250
+	 * Just a simple utility function children can use for checking if property exists
2251
+	 *
2252
+	 * @access  public
2253
+	 * @param  string $field_name property to check
2254
+	 * @return bool                              TRUE if existing,FALSE if not.
2255
+	 */
2256
+	public function is_set($field_name)
2257
+	{
2258
+		return isset($this->_fields[$field_name]);
2259
+	}
2260
+
2261
+
2262
+
2263
+	/**
2264
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2265
+	 * EE_Error exception if they don't
2266
+	 *
2267
+	 * @param  mixed (string|array) $properties properties to check
2268
+	 * @throws EE_Error
2269
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2270
+	 */
2271
+	protected function _property_exists($properties)
2272
+	{
2273
+		foreach ((array)$properties as $property_name) {
2274
+			//first make sure this property exists
2275
+			if ( ! $this->_fields[$property_name]) {
2276
+				throw new EE_Error(
2277
+					sprintf(
2278
+						__(
2279
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2280
+							'event_espresso'
2281
+						),
2282
+						$property_name
2283
+					)
2284
+				);
2285
+			}
2286
+		}
2287
+		return true;
2288
+	}
2289
+
2290
+
2291
+
2292
+	/**
2293
+	 * This simply returns an array of model fields for this object
2294
+	 *
2295
+	 * @return array
2296
+	 * @throws \EE_Error
2297
+	 */
2298
+	public function model_field_array()
2299
+	{
2300
+		$fields = $this->get_model()->field_settings(false);
2301
+		$properties = array();
2302
+		//remove prepended underscore
2303
+		foreach ($fields as $field_name => $settings) {
2304
+			$properties[$field_name] = $this->get($field_name);
2305
+		}
2306
+		return $properties;
2307
+	}
2308
+
2309
+
2310
+
2311
+	/**
2312
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2313
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2314
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2315
+	 * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2316
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2317
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2318
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
2319
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
2320
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2321
+	 * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2322
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2323
+	 *        return $previousReturnValue.$returnString;
2324
+	 * }
2325
+	 * require('EE_Answer.class.php');
2326
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2327
+	 * echo $answer->my_callback('monkeys',100);
2328
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2329
+	 *
2330
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2331
+	 * @param array  $args       array of original arguments passed to the function
2332
+	 * @throws EE_Error
2333
+	 * @return mixed whatever the plugin which calls add_filter decides
2334
+	 */
2335
+	public function __call($methodName, $args)
2336
+	{
2337
+		$className = get_class($this);
2338
+		$tagName = "FHEE__{$className}__{$methodName}";
2339
+		if ( ! has_filter($tagName)) {
2340
+			throw new EE_Error(
2341
+				sprintf(
2342
+					__(
2343
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2344
+						"event_espresso"
2345
+					),
2346
+					$methodName,
2347
+					$className,
2348
+					$tagName
2349
+				)
2350
+			);
2351
+		}
2352
+		return apply_filters($tagName, null, $this, $args);
2353
+	}
2354
+
2355
+
2356
+
2357
+	/**
2358
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2359
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2360
+	 *
2361
+	 * @param string $meta_key
2362
+	 * @param string $meta_value
2363
+	 * @param string $previous_value
2364
+	 * @return int records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2365
+	 * @throws \EE_Error
2366
+	 * NOTE: if the values haven't changed, returns 0
2367
+	 */
2368
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2369
+	{
2370
+		$query_params = array(
2371
+			array(
2372
+				'EXM_key'  => $meta_key,
2373
+				'OBJ_ID'   => $this->ID(),
2374
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2375
+			),
2376
+		);
2377
+		if ($previous_value !== null) {
2378
+			$query_params[0]['EXM_value'] = $meta_value;
2379
+		}
2380
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2381
+		if ( ! $existing_rows_like_that) {
2382
+			return $this->add_extra_meta($meta_key, $meta_value);
2383
+		} else {
2384
+			foreach ($existing_rows_like_that as $existing_row) {
2385
+				$existing_row->save(array('EXM_value' => $meta_value));
2386
+			}
2387
+			return count($existing_rows_like_that);
2388
+		}
2389
+	}
2390
+
2391
+
2392
+
2393
+	/**
2394
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2395
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2396
+	 * extra meta row was entered, false if not
2397
+	 *
2398
+	 * @param string  $meta_key
2399
+	 * @param string  $meta_value
2400
+	 * @param boolean $unique
2401
+	 * @return boolean
2402
+	 * @throws \EE_Error
2403
+	 */
2404
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2405
+	{
2406
+		if ($unique) {
2407
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2408
+				array(
2409
+					array(
2410
+						'EXM_key'  => $meta_key,
2411
+						'OBJ_ID'   => $this->ID(),
2412
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2413
+					),
2414
+				)
2415
+			);
2416
+			if ($existing_extra_meta) {
2417
+				return false;
2418
+			}
2419
+		}
2420
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2421
+			array(
2422
+				'EXM_key'   => $meta_key,
2423
+				'EXM_value' => $meta_value,
2424
+				'OBJ_ID'    => $this->ID(),
2425
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2426
+			)
2427
+		);
2428
+		$new_extra_meta->save();
2429
+		return true;
2430
+	}
2431
+
2432
+
2433
+
2434
+	/**
2435
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2436
+	 * is specified, only deletes extra meta records with that value.
2437
+	 *
2438
+	 * @param string $meta_key
2439
+	 * @param string $meta_value
2440
+	 * @return int number of extra meta rows deleted
2441
+	 * @throws \EE_Error
2442
+	 */
2443
+	public function delete_extra_meta($meta_key, $meta_value = null)
2444
+	{
2445
+		$query_params = array(
2446
+			array(
2447
+				'EXM_key'  => $meta_key,
2448
+				'OBJ_ID'   => $this->ID(),
2449
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2450
+			),
2451
+		);
2452
+		if ($meta_value !== null) {
2453
+			$query_params[0]['EXM_value'] = $meta_value;
2454
+		}
2455
+		return EEM_Extra_Meta::instance()->delete($query_params);
2456
+	}
2457
+
2458
+
2459
+
2460
+	/**
2461
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2462
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2463
+	 * You can specify $default is case you haven't found the extra meta
2464
+	 *
2465
+	 * @param string  $meta_key
2466
+	 * @param boolean $single
2467
+	 * @param mixed   $default if we don't find anything, what should we return?
2468
+	 * @return mixed single value if $single; array if ! $single
2469
+	 * @throws \EE_Error
2470
+	 */
2471
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2472
+	{
2473
+		if ($single) {
2474
+			$result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2475
+			if ($result instanceof EE_Extra_Meta) {
2476
+				return $result->value();
2477
+			} else {
2478
+				return $default;
2479
+			}
2480
+		} else {
2481
+			$results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2482
+			if ($results) {
2483
+				$values = array();
2484
+				foreach ($results as $result) {
2485
+					if ($result instanceof EE_Extra_Meta) {
2486
+						$values[$result->ID()] = $result->value();
2487
+					}
2488
+				}
2489
+				return $values;
2490
+			} else {
2491
+				return $default;
2492
+			}
2493
+		}
2494
+	}
2495
+
2496
+
2497
+
2498
+	/**
2499
+	 * Returns a simple array of all the extra meta associated with this model object.
2500
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2501
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2502
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2503
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2504
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2505
+	 * finally the extra meta's value as each sub-value. (eg
2506
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2507
+	 *
2508
+	 * @param boolean $one_of_each_key
2509
+	 * @return array
2510
+	 * @throws \EE_Error
2511
+	 */
2512
+	public function all_extra_meta_array($one_of_each_key = true)
2513
+	{
2514
+		$return_array = array();
2515
+		if ($one_of_each_key) {
2516
+			$extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2517
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2518
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2519
+					$return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2520
+				}
2521
+			}
2522
+		} else {
2523
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2524
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2525
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2526
+					if ( ! isset($return_array[$extra_meta_obj->key()])) {
2527
+						$return_array[$extra_meta_obj->key()] = array();
2528
+					}
2529
+					$return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2530
+				}
2531
+			}
2532
+		}
2533
+		return $return_array;
2534
+	}
2535
+
2536
+
2537
+
2538
+	/**
2539
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2540
+	 *
2541
+	 * @return string
2542
+	 * @throws \EE_Error
2543
+	 */
2544
+	public function name()
2545
+	{
2546
+		//find a field that's not a text field
2547
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2548
+		if ($field_we_can_use) {
2549
+			return $this->get($field_we_can_use->get_name());
2550
+		} else {
2551
+			$first_few_properties = $this->model_field_array();
2552
+			$first_few_properties = array_slice($first_few_properties, 0, 3);
2553
+			$name_parts = array();
2554
+			foreach ($first_few_properties as $name => $value) {
2555
+				$name_parts[] = "$name:$value";
2556
+			}
2557
+			return implode(",", $name_parts);
2558
+		}
2559
+	}
2560
+
2561
+
2562
+
2563
+	/**
2564
+	 * in_entity_map
2565
+	 * Checks if this model object has been proven to already be in the entity map
2566
+	 *
2567
+	 * @return boolean
2568
+	 * @throws \EE_Error
2569
+	 */
2570
+	public function in_entity_map()
2571
+	{
2572
+		if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2573
+			//well, if we looked, did we find it in the entity map?
2574
+			return true;
2575
+		} else {
2576
+			return false;
2577
+		}
2578
+	}
2579
+
2580
+
2581
+
2582
+	/**
2583
+	 * refresh_from_db
2584
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
2585
+	 *
2586
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2587
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2588
+	 */
2589
+	public function refresh_from_db()
2590
+	{
2591
+		if ($this->ID() && $this->in_entity_map()) {
2592
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
2593
+		} else {
2594
+			//if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2595
+			//if it has an ID but it's not in the map, and you're asking me to refresh it
2596
+			//that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2597
+			//absolutely nothing in it for this ID
2598
+			if (WP_DEBUG) {
2599
+				throw new EE_Error(
2600
+					sprintf(
2601
+						__('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2602
+							'event_espresso'),
2603
+						$this->ID(),
2604
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2605
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2606
+					)
2607
+				);
2608
+			}
2609
+		}
2610
+	}
2611
+
2612
+
2613
+
2614
+	/**
2615
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2616
+	 * (probably a bad assumption they have made, oh well)
2617
+	 *
2618
+	 * @return string
2619
+	 */
2620
+	public function __toString()
2621
+	{
2622
+		try {
2623
+			return sprintf('%s (%s)', $this->name(), $this->ID());
2624
+		} catch (Exception $e) {
2625
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2626
+			return '';
2627
+		}
2628
+	}
2629
+
2630
+
2631
+
2632
+	/**
2633
+	 * Clear related model objects if they're already in the DB, because otherwise when we
2634
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
2635
+	 * This means if we have made changes to those related model objects, and want to unserialize
2636
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
2637
+	 * Instead, those related model objects should be directly serialized and stored.
2638
+	 * Eg, the following won't work:
2639
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2640
+	 * $att = $reg->attendee();
2641
+	 * $att->set( 'ATT_fname', 'Dirk' );
2642
+	 * update_option( 'my_option', serialize( $reg ) );
2643
+	 * //END REQUEST
2644
+	 * //START NEXT REQUEST
2645
+	 * $reg = get_option( 'my_option' );
2646
+	 * $reg->attendee()->save();
2647
+	 * And would need to be replace with:
2648
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2649
+	 * $att = $reg->attendee();
2650
+	 * $att->set( 'ATT_fname', 'Dirk' );
2651
+	 * update_option( 'my_option', serialize( $reg ) );
2652
+	 * //END REQUEST
2653
+	 * //START NEXT REQUEST
2654
+	 * $att = get_option( 'my_option' );
2655
+	 * $att->save();
2656
+	 *
2657
+	 * @return array
2658
+	 * @throws \EE_Error
2659
+	 */
2660
+	public function __sleep()
2661
+	{
2662
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
2663
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
2664
+				$classname = 'EE_' . $this->get_model()->get_this_model_name();
2665
+				if (
2666
+					$this->get_one_from_cache($relation_name) instanceof $classname
2667
+					&& $this->get_one_from_cache($relation_name)->ID()
2668
+				) {
2669
+					$this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2670
+				}
2671
+			}
2672
+		}
2673
+		$this->_props_n_values_provided_in_constructor = array();
2674
+		return array_keys(get_object_vars($this));
2675
+	}
2676
+
2677
+
2678
+
2679
+	/**
2680
+	 * restore _props_n_values_provided_in_constructor
2681
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2682
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
2683
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
2684
+	 */
2685
+	public function __wakeup()
2686
+	{
2687
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
2688
+	}
2689 2689
 
2690 2690
 
2691 2691
 
Please login to merge, or discard this patch.
core/libraries/rest_api/controllers/model/Read.php 2 patches
Indentation   +1262 added lines, -1262 removed lines patch added patch discarded remove patch
@@ -9,7 +9,7 @@  discard block
 block discarded – undo
9 9
 use EE_Datetime_Field;
10 10
 
11 11
 if (! defined('EVENT_ESPRESSO_VERSION')) {
12
-    exit('No direct script access allowed');
12
+	exit('No direct script access allowed');
13 13
 }
14 14
 
15 15
 
@@ -27,1267 +27,1267 @@  discard block
 block discarded – undo
27 27
 
28 28
 
29 29
 
30
-    /**
31
-     * @var Calculated_Model_Fields
32
-     */
33
-    protected $_fields_calculator;
34
-
35
-
36
-
37
-    /**
38
-     * Read constructor.
39
-     */
40
-    public function __construct()
41
-    {
42
-        parent::__construct();
43
-        $this->_fields_calculator = new Calculated_Model_Fields();
44
-    }
45
-
46
-
47
-
48
-    /**
49
-     * Handles requests to get all (or a filtered subset) of entities for a particular model
50
-     *
51
-     * @param \WP_REST_Request $request
52
-     * @return \WP_REST_Response|\WP_Error
53
-     */
54
-    public static function handle_request_get_all(\WP_REST_Request $request)
55
-    {
56
-        $controller = new Read();
57
-        try {
58
-            $matches = $controller->parse_route(
59
-                $request->get_route(),
60
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)~',
61
-                array('version', 'model')
62
-            );
63
-            $controller->set_requested_version($matches['version']);
64
-            $model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
65
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
66
-                return $controller->send_response(
67
-                    new \WP_Error(
68
-                        'endpoint_parsing_error',
69
-                        sprintf(
70
-                            __('There is no model for endpoint %s. Please contact event espresso support',
71
-                                'event_espresso'),
72
-                            $model_name_singular
73
-                        )
74
-                    )
75
-                );
76
-            }
77
-            return $controller->send_response(
78
-                $controller->get_entities_from_model(
79
-                    $controller->get_model_version_info()->load_model($model_name_singular),
80
-                    $request
81
-                )
82
-            );
83
-        } catch (\Exception $e) {
84
-            return $controller->send_response($e);
85
-        }
86
-    }
87
-
88
-
89
-
90
-    /**
91
-     * Prepares and returns schema for any OPTIONS request.
92
-     *
93
-     * @param string $model_name Something like `Event` or `Registration`
94
-     * @param string $version    The API endpoint version being used.
95
-     * @return array
96
-     */
97
-    public static function handle_schema_request($model_name, $version)
98
-    {
99
-        $controller = new Read();
100
-        try {
101
-            $controller->set_requested_version($version);
102
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name)) {
103
-                return array();
104
-            }
105
-            //get the model for this version
106
-            $model = $controller->get_model_version_info()->load_model($model_name);
107
-            $model_schema = new JsonModelSchema($model);
108
-            return $model_schema->getModelSchemaForRelations(
109
-                $controller->get_model_version_info()->relation_settings($model),
110
-                $controller->_customize_schema_for_rest_response(
111
-                    $model,
112
-                    $model_schema->getModelSchemaForFields(
113
-                        $controller->get_model_version_info()->fields_on_model_in_this_version($model),
114
-                        $model_schema->getInitialSchemaStructure()
115
-                    )
116
-                )
117
-            );
118
-        } catch (\Exception $e) {
119
-            return array();
120
-        }
121
-    }
122
-
123
-
124
-
125
-    /**
126
-     * This loops through each field in the given schema for the model and does the following:
127
-     * - add any extra fields that are REST API specific and related to existing fields.
128
-     * - transform default values into the correct format for a REST API response.
129
-     *
130
-     * @param \EEM_Base $model
131
-     * @param array     $schema
132
-     * @return array  The final schema.
133
-     */
134
-    protected function _customize_schema_for_rest_response(\EEM_Base $model, array $schema)
135
-    {
136
-        foreach ($this->get_model_version_info()->fields_on_model_in_this_version($model) as $field_name => $field) {
137
-            $schema = $this->_translate_defaults_for_rest_response(
138
-                $field_name,
139
-                $field,
140
-                $this->_maybe_add_extra_fields_to_schema($field_name, $field, $schema)
141
-            );
142
-        }
143
-        return $schema;
144
-    }
145
-
146
-
147
-
148
-    /**
149
-     * This is used to ensure that the 'default' value set in the schema response is formatted correctly for the REST
150
-     * response.
151
-     *
152
-     * @param                      $field_name
153
-     * @param \EE_Model_Field_Base $field
154
-     * @param array                $schema
155
-     * @return array
156
-     */
157
-    protected function _translate_defaults_for_rest_response($field_name, \EE_Model_Field_Base $field, array $schema)
158
-    {
159
-        if (isset($schema['properties'][$field_name]['default'])) {
160
-            if (is_array($schema['properties'][$field_name]['default'])) {
161
-                foreach ($schema['properties'][$field_name]['default'] as $default_key => $default_value) {
162
-                    if ($default_key === 'raw') {
163
-                        $schema['properties'][$field_name]['default'][$default_key] = Model_Data_Translator::prepare_field_value_for_json(
164
-                            $field,
165
-                            $default_value,
166
-                            $this->get_model_version_info()->requested_version()
167
-                        );
168
-                    }
169
-                }
170
-            } else {
171
-                $schema['properties'][$field_name]['default'] = Model_Data_Translator::prepare_field_value_for_json(
172
-                    $field,
173
-                    $schema['properties'][$field_name]['default'],
174
-                    $this->get_model_version_info()->requested_version()
175
-                );
176
-            }
177
-        }
178
-        return $schema;
179
-    }
180
-
181
-
182
-
183
-    /**
184
-     * Adds additional fields to the schema
185
-     * The REST API returns a GMT value field for each datetime field in the resource.  Thus the description about this
186
-     * needs to be added to the schema.
187
-     *
188
-     * @param                      $field_name
189
-     * @param \EE_Model_Field_Base $field
190
-     * @param array                $schema
191
-     * @return array
192
-     */
193
-    protected function _maybe_add_extra_fields_to_schema($field_name, \EE_Model_Field_Base $field, array $schema)
194
-    {
195
-        if ($field instanceof EE_Datetime_Field) {
196
-            $schema['properties'][$field_name . '_gmt'] = $field->getSchema();
197
-            //modify the description
198
-            $schema['properties'][$field_name . '_gmt']['description'] = sprintf(
199
-                esc_html__('%s - the value for this field is in GMT.', 'event_espresso'),
200
-                $field->get_nicename()
201
-            );
202
-        }
203
-        return $schema;
204
-    }
205
-
206
-
207
-
208
-    /**
209
-     * Used to figure out the route from the request when a `WP_REST_Request` object is not available
210
-     *
211
-     * @return string
212
-     */
213
-    protected function get_route_from_request()
214
-    {
215
-        if (isset($GLOBALS['wp'])
216
-            && $GLOBALS['wp'] instanceof \WP
217
-            && isset($GLOBALS['wp']->query_vars['rest_route'])
218
-        ) {
219
-            return $GLOBALS['wp']->query_vars['rest_route'];
220
-        } else {
221
-            return isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/';
222
-        }
223
-    }
224
-
225
-
226
-
227
-    /**
228
-     * Gets a single entity related to the model indicated in the path and its id
229
-     *
230
-     * @param \WP_REST_Request $request
231
-     * @return \WP_REST_Response|\WP_Error
232
-     */
233
-    public static function handle_request_get_one(\WP_REST_Request $request)
234
-    {
235
-        $controller = new Read();
236
-        try {
237
-            $matches = $controller->parse_route(
238
-                $request->get_route(),
239
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)~',
240
-                array('version', 'model', 'id'));
241
-            $controller->set_requested_version($matches['version']);
242
-            $model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
243
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
244
-                return $controller->send_response(
245
-                    new \WP_Error(
246
-                        'endpoint_parsing_error',
247
-                        sprintf(
248
-                            __('There is no model for endpoint %s. Please contact event espresso support',
249
-                                'event_espresso'),
250
-                            $model_name_singular
251
-                        )
252
-                    )
253
-                );
254
-            }
255
-            return $controller->send_response(
256
-                $controller->get_entity_from_model(
257
-                    $controller->get_model_version_info()->load_model($model_name_singular),
258
-                    $request
259
-                )
260
-            );
261
-        } catch (\Exception $e) {
262
-            return $controller->send_response($e);
263
-        }
264
-    }
265
-
266
-
267
-
268
-    /**
269
-     * Gets all the related entities (or if its a belongs-to relation just the one)
270
-     * to the item with the given id
271
-     *
272
-     * @param \WP_REST_Request $request
273
-     * @return \WP_REST_Response|\WP_Error
274
-     */
275
-    public static function handle_request_get_related(\WP_REST_Request $request)
276
-    {
277
-        $controller = new Read();
278
-        try {
279
-            $matches = $controller->parse_route(
280
-                $request->get_route(),
281
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)/(.*)~',
282
-                array('version', 'model', 'id', 'related_model')
283
-            );
284
-            $controller->set_requested_version($matches['version']);
285
-            $main_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
286
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($main_model_name_singular)) {
287
-                return $controller->send_response(
288
-                    new \WP_Error(
289
-                        'endpoint_parsing_error',
290
-                        sprintf(
291
-                            __('There is no model for endpoint %s. Please contact event espresso support',
292
-                                'event_espresso'),
293
-                            $main_model_name_singular
294
-                        )
295
-                    )
296
-                );
297
-            }
298
-            $main_model = $controller->get_model_version_info()->load_model($main_model_name_singular);
299
-            //assume the related model name is plural and try to find the model's name
300
-            $related_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['related_model']);
301
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
302
-                //so the word didn't singularize well. Maybe that's just because it's a singular word?
303
-                $related_model_name_singular = \EEH_Inflector::humanize($matches['related_model']);
304
-            }
305
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
306
-                return $controller->send_response(
307
-                    new \WP_Error(
308
-                        'endpoint_parsing_error',
309
-                        sprintf(
310
-                            __('There is no model for endpoint %s. Please contact event espresso support',
311
-                                'event_espresso'),
312
-                            $related_model_name_singular
313
-                        )
314
-                    )
315
-                );
316
-            }
317
-            return $controller->send_response(
318
-                $controller->get_entities_from_relation(
319
-                    $request->get_param('id'),
320
-                    $main_model->related_settings_for($related_model_name_singular),
321
-                    $request
322
-                )
323
-            );
324
-        } catch (\Exception $e) {
325
-            return $controller->send_response($e);
326
-        }
327
-    }
328
-
329
-
330
-
331
-    /**
332
-     * Gets a collection for the given model and filters
333
-     *
334
-     * @param \EEM_Base        $model
335
-     * @param \WP_REST_Request $request
336
-     * @return array|\WP_Error
337
-     */
338
-    public function get_entities_from_model($model, $request)
339
-    {
340
-        $query_params = $this->create_model_query_params($model, $request->get_params());
341
-        if (! Capabilities::current_user_has_partial_access_to($model, $query_params['caps'])) {
342
-            $model_name_plural = \EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
343
-            return new \WP_Error(
344
-                sprintf('rest_%s_cannot_list', $model_name_plural),
345
-                sprintf(
346
-                    __('Sorry, you are not allowed to list %1$s. Missing permissions: %2$s', 'event_espresso'),
347
-                    $model_name_plural,
348
-                    Capabilities::get_missing_permissions_string($model, $query_params['caps'])
349
-                ),
350
-                array('status' => 403)
351
-            );
352
-        }
353
-        if (! $request->get_header('no_rest_headers')) {
354
-            $this->_set_headers_from_query_params($model, $query_params);
355
-        }
356
-        /** @type array $results */
357
-        $results = $model->get_all_wpdb_results($query_params);
358
-        $nice_results = array();
359
-        foreach ($results as $result) {
360
-            $nice_results[] = $this->create_entity_from_wpdb_result(
361
-                $model,
362
-                $result,
363
-                $request
364
-            );
365
-        }
366
-        return $nice_results;
367
-    }
368
-
369
-
370
-
371
-    /**
372
-     * @param array                   $primary_model_query_params query params for finding the item from which
373
-     *                                                            relations will be based
374
-     * @param \EE_Model_Relation_Base $relation
375
-     * @param \WP_REST_Request        $request
376
-     * @return \WP_Error|array
377
-     */
378
-    protected function _get_entities_from_relation($primary_model_query_params, $relation, $request)
379
-    {
380
-        $context = $this->validate_context($request->get_param('caps'));
381
-        $model = $relation->get_this_model();
382
-        $related_model = $relation->get_other_model();
383
-        if (! isset($primary_model_query_params[0])) {
384
-            $primary_model_query_params[0] = array();
385
-        }
386
-        //check if they can access the 1st model object
387
-        $primary_model_query_params = array(
388
-            0       => $primary_model_query_params[0],
389
-            'limit' => 1,
390
-        );
391
-        if ($model instanceof \EEM_Soft_Delete_Base) {
392
-            $primary_model_query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($primary_model_query_params);
393
-        }
394
-        $restricted_query_params = $primary_model_query_params;
395
-        $restricted_query_params['caps'] = $context;
396
-        $this->_set_debug_info('main model query params', $restricted_query_params);
397
-        $this->_set_debug_info('missing caps', Capabilities::get_missing_permissions_string($related_model, $context));
398
-        if (
399
-        ! (
400
-            Capabilities::current_user_has_partial_access_to($related_model, $context)
401
-            && $model->exists($restricted_query_params)
402
-        )
403
-        ) {
404
-            if ($relation instanceof \EE_Belongs_To_Relation) {
405
-                $related_model_name_maybe_plural = strtolower($related_model->get_this_model_name());
406
-            } else {
407
-                $related_model_name_maybe_plural = \EEH_Inflector::pluralize_and_lower($related_model->get_this_model_name());
408
-            }
409
-            return new \WP_Error(
410
-                sprintf('rest_%s_cannot_list', $related_model_name_maybe_plural),
411
-                sprintf(
412
-                    __('Sorry, you are not allowed to list %1$s related to %2$s. Missing permissions: %3$s',
413
-                        'event_espresso'),
414
-                    $related_model_name_maybe_plural,
415
-                    $relation->get_this_model()->get_this_model_name(),
416
-                    implode(
417
-                        ',',
418
-                        array_keys(
419
-                            Capabilities::get_missing_permissions($related_model, $context)
420
-                        )
421
-                    )
422
-                ),
423
-                array('status' => 403)
424
-            );
425
-        }
426
-        $query_params = $this->create_model_query_params($relation->get_other_model(), $request->get_params());
427
-        foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) {
428
-            $query_params[0][$relation->get_this_model()->get_this_model_name()
429
-                             . '.'
430
-                             . $where_condition_key] = $where_condition_value;
431
-        }
432
-        $query_params['default_where_conditions'] = 'none';
433
-        $query_params['caps'] = $context;
434
-        if (! $request->get_header('no_rest_headers')) {
435
-            $this->_set_headers_from_query_params($relation->get_other_model(), $query_params);
436
-        }
437
-        /** @type array $results */
438
-        $results = $relation->get_other_model()->get_all_wpdb_results($query_params);
439
-        $nice_results = array();
440
-        foreach ($results as $result) {
441
-            $nice_result = $this->create_entity_from_wpdb_result(
442
-                $relation->get_other_model(),
443
-                $result,
444
-                $request
445
-            );
446
-            if ($relation instanceof \EE_HABTM_Relation) {
447
-                //put the unusual stuff (properties from the HABTM relation) first, and make sure
448
-                //if there are conflicts we prefer the properties from the main model
449
-                $join_model_result = $this->create_entity_from_wpdb_result(
450
-                    $relation->get_join_model(),
451
-                    $result,
452
-                    $request
453
-                );
454
-                $joined_result = array_merge($nice_result, $join_model_result);
455
-                //but keep the meta stuff from the main model
456
-                if (isset($nice_result['meta'])) {
457
-                    $joined_result['meta'] = $nice_result['meta'];
458
-                }
459
-                $nice_result = $joined_result;
460
-            }
461
-            $nice_results[] = $nice_result;
462
-        }
463
-        if ($relation instanceof \EE_Belongs_To_Relation) {
464
-            return array_shift($nice_results);
465
-        } else {
466
-            return $nice_results;
467
-        }
468
-    }
469
-
470
-
471
-
472
-    /**
473
-     * Gets the collection for given relation object
474
-     * The same as Read::get_entities_from_model(), except if the relation
475
-     * is a HABTM relation, in which case it merges any non-foreign-key fields from
476
-     * the join-model-object into the results
477
-     *
478
-     * @param string                  $id the ID of the thing we are fetching related stuff from
479
-     * @param \EE_Model_Relation_Base $relation
480
-     * @param \WP_REST_Request        $request
481
-     * @return array|\WP_Error
482
-     * @throws \EE_Error
483
-     */
484
-    public function get_entities_from_relation($id, $relation, $request)
485
-    {
486
-        if (! $relation->get_this_model()->has_primary_key_field()) {
487
-            throw new \EE_Error(
488
-                sprintf(
489
-                    __('Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
490
-                        'event_espresso'),
491
-                    $relation->get_this_model()->get_this_model_name()
492
-                )
493
-            );
494
-        }
495
-        return $this->_get_entities_from_relation(
496
-            array(
497
-                array(
498
-                    $relation->get_this_model()->primary_key_name() => $id,
499
-                ),
500
-            ),
501
-            $relation,
502
-            $request
503
-        );
504
-    }
505
-
506
-
507
-
508
-    /**
509
-     * Sets the headers that are based on the model and query params,
510
-     * like the total records. This should only be called on the original request
511
-     * from the client, not on subsequent internal
512
-     *
513
-     * @param \EEM_Base $model
514
-     * @param array     $query_params
515
-     * @return void
516
-     */
517
-    protected function _set_headers_from_query_params($model, $query_params)
518
-    {
519
-        $this->_set_debug_info('model query params', $query_params);
520
-        $this->_set_debug_info('missing caps',
521
-            Capabilities::get_missing_permissions_string($model, $query_params['caps']));
522
-        //normally the limit to a 2-part array, where the 2nd item is the limit
523
-        if (! isset($query_params['limit'])) {
524
-            $query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
525
-        }
526
-        if (is_array($query_params['limit'])) {
527
-            $limit_parts = $query_params['limit'];
528
-        } else {
529
-            $limit_parts = explode(',', $query_params['limit']);
530
-            if (count($limit_parts) == 1) {
531
-                $limit_parts = array(0, $limit_parts[0]);
532
-            }
533
-        }
534
-        //remove the group by and having parts of the query, as those will
535
-        //make the sql query return an array of values, instead of just a single value
536
-        unset($query_params['group_by'], $query_params['having'], $query_params['limit']);
537
-        $count = $model->count($query_params, null, true);
538
-        $pages = $count / $limit_parts[1];
539
-        $this->_set_response_header('Total', $count, false);
540
-        $this->_set_response_header('PageSize', $limit_parts[1], false);
541
-        $this->_set_response_header('TotalPages', ceil($pages), false);
542
-    }
543
-
544
-
545
-
546
-    /**
547
-     * Changes database results into REST API entities
548
-     *
549
-     * @param \EEM_Base        $model
550
-     * @param array            $db_row     like results from $wpdb->get_results()
551
-     * @param \WP_REST_Request $rest_request
552
-     * @param string           $deprecated no longer used
553
-     * @return array ready for being converted into json for sending to client
554
-     */
555
-    public function create_entity_from_wpdb_result($model, $db_row, $rest_request, $deprecated = null)
556
-    {
557
-        if (! $rest_request instanceof \WP_REST_Request) {
558
-            //ok so this was called in the old style, where the 3rd arg was
559
-            //$include, and the 4th arg was $context
560
-            //now setup the request just to avoid fatal errors, although we won't be able
561
-            //to truly make use of it because it's kinda devoid of info
562
-            $rest_request = new \WP_REST_Request();
563
-            $rest_request->set_param('include', $rest_request);
564
-            $rest_request->set_param('caps', $deprecated);
565
-        }
566
-        if ($rest_request->get_param('caps') == null) {
567
-            $rest_request->set_param('caps', \EEM_Base::caps_read);
568
-        }
569
-        $entity_array = $this->_create_bare_entity_from_wpdb_results($model, $db_row);
570
-        $entity_array = $this->_add_extra_fields($model, $db_row, $entity_array);
571
-        $entity_array['_links'] = $this->_get_entity_links($model, $db_row, $entity_array);
572
-        $entity_array['_calculated_fields'] = $this->_get_entity_calculations($model, $db_row, $rest_request);
573
-        $entity_array = apply_filters('FHEE__Read__create_entity_from_wpdb_results__entity_before_including_requested_models',
574
-            $entity_array, $model, $rest_request->get_param('caps'), $rest_request, $this);
575
-        $entity_array = $this->_include_requested_models($model, $rest_request, $entity_array, $db_row);
576
-        $entity_array = apply_filters(
577
-            'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal',
578
-            $entity_array,
579
-            $model,
580
-            $rest_request->get_param('caps'),
581
-            $rest_request,
582
-            $this
583
-        );
584
-        $result_without_inaccessible_fields = Capabilities::filter_out_inaccessible_entity_fields(
585
-            $entity_array,
586
-            $model,
587
-            $rest_request->get_param('caps'),
588
-            $this->get_model_version_info(),
589
-            $model->get_index_primary_key_string(
590
-                $model->deduce_fields_n_values_from_cols_n_values($db_row)
591
-            )
592
-        );
593
-        $this->_set_debug_info(
594
-            'inaccessible fields',
595
-            array_keys(array_diff_key($entity_array, $result_without_inaccessible_fields))
596
-        );
597
-        return apply_filters(
598
-            'FHEE__Read__create_entity_from_wpdb_results__entity_return',
599
-            $result_without_inaccessible_fields,
600
-            $model,
601
-            $rest_request->get_param('caps')
602
-        );
603
-    }
604
-
605
-
606
-
607
-    /**
608
-     * Creates a REST entity array (JSON object we're going to return in the response, but
609
-     * for now still a PHP array, but soon enough we'll call json_encode on it, don't worry),
610
-     * from $wpdb->get_row( $sql, ARRAY_A)
611
-     *
612
-     * @param \EEM_Base $model
613
-     * @param array     $db_row
614
-     * @return array entity mostly ready for converting to JSON and sending in the response
615
-     */
616
-    protected function _create_bare_entity_from_wpdb_results(\EEM_Base $model, $db_row)
617
-    {
618
-        $result = $model->deduce_fields_n_values_from_cols_n_values($db_row);
619
-        $result = array_intersect_key($result,
620
-            $this->get_model_version_info()->fields_on_model_in_this_version($model));
621
-        //if this is a CPT, we need to set the global $post to it,
622
-        //otherwise shortcodes etc won't work properly while rendering it
623
-        if ($model instanceof \EEM_CPT_Base) {
624
-            $do_chevy_shuffle = true;
625
-        } else {
626
-            $do_chevy_shuffle = false;
627
-        }
628
-        if ($do_chevy_shuffle) {
629
-            global $post;
630
-            $old_post = $post;
631
-            $post = get_post($result[$model->primary_key_name()]);
632
-            $model_object_classname = 'EE_' . $model->get_this_model_name();
633
-            $post->{$model_object_classname} = \EE_Registry::instance()->load_class(
634
-                $model_object_classname,
635
-                $result,
636
-                false,
637
-                false
638
-                );
639
-        }
640
-        foreach ($result as $field_name => $raw_field_value) {
641
-            $field_obj = $model->field_settings_for($field_name);
642
-            $field_value = $field_obj->prepare_for_set_from_db($raw_field_value);
643
-            if ($this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_ignored())) {
644
-                unset($result[$field_name]);
645
-            } elseif (
646
-            $this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_that_have_rendered_format())
647
-            ) {
648
-                $result[$field_name] = array(
649
-                    'raw'      => $field_obj->prepare_for_get($field_value),
650
-                    'rendered' => $field_obj->prepare_for_pretty_echoing($field_value),
651
-                );
652
-            } elseif (
653
-            $this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_that_have_pretty_format())
654
-            ) {
655
-                $result[$field_name] = array(
656
-                    'raw'    => $field_obj->prepare_for_get($field_value),
657
-                    'pretty' => $field_obj->prepare_for_pretty_echoing($field_value),
658
-                );
659
-            } elseif ($field_obj instanceof \EE_Datetime_Field) {
660
-                if ($field_value instanceof \DateTime) {
661
-                    $timezone = $field_value->getTimezone();
662
-                    $field_value->setTimezone(new \DateTimeZone('UTC'));
663
-                    $result[$field_name . '_gmt'] = Model_Data_Translator::prepare_field_value_for_json(
664
-                        $field_obj,
665
-                        $field_value,
666
-                        $this->get_model_version_info()->requested_version()
667
-                    );
668
-                    $field_value->setTimezone($timezone);
669
-                    $result[$field_name] = Model_Data_Translator::prepare_field_value_for_json(
670
-                        $field_obj,
671
-                        $field_value,
672
-                        $this->get_model_version_info()->requested_version()
673
-                    );
674
-                }
675
-            } else {
676
-                $result[$field_name] = Model_Data_Translator::prepare_field_value_for_json(
677
-                    $field_obj,
678
-                    $field_obj->prepare_for_get($field_value),
679
-                    $this->get_model_version_info()->requested_version()
680
-                );
681
-            }
682
-        }
683
-        if ($do_chevy_shuffle) {
684
-            $post = $old_post;
685
-        }
686
-        return $result;
687
-    }
688
-
689
-
690
-
691
-    /**
692
-     * Adds a few extra fields to the entity response
693
-     *
694
-     * @param \EEM_Base $model
695
-     * @param array     $db_row
696
-     * @param array     $entity_array
697
-     * @return array modified entity
698
-     */
699
-    protected function _add_extra_fields(\EEM_Base $model, $db_row, $entity_array)
700
-    {
701
-        if ($model instanceof \EEM_CPT_Base) {
702
-            $entity_array['link'] = get_permalink($db_row[$model->get_primary_key_field()->get_qualified_column()]);
703
-        }
704
-        return $entity_array;
705
-    }
706
-
707
-
708
-
709
-    /**
710
-     * Gets links we want to add to the response
711
-     *
712
-     * @global \WP_REST_Server $wp_rest_server
713
-     * @param \EEM_Base        $model
714
-     * @param array            $db_row
715
-     * @param array            $entity_array
716
-     * @return array the _links item in the entity
717
-     */
718
-    protected function _get_entity_links($model, $db_row, $entity_array)
719
-    {
720
-        //add basic links
721
-        $links = array();
722
-        if ($model->has_primary_key_field()) {
723
-            $links['self'] = array(
724
-                array(
725
-                    'href' => $this->get_versioned_link_to(
726
-                        \EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
727
-                        . '/'
728
-                        . $entity_array[$model->primary_key_name()]
729
-                    ),
730
-                ),
731
-            );
732
-        }
733
-        $links['collection'] = array(
734
-            array(
735
-                'href' => $this->get_versioned_link_to(
736
-                    \EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
737
-                ),
738
-            ),
739
-        );
740
-        //add links to related models
741
-        if ($model->has_primary_key_field()) {
742
-            foreach ($this->get_model_version_info()->relation_settings($model) as $relation_name => $relation_obj) {
743
-                $related_model_part = Read::get_related_entity_name($relation_name, $relation_obj);
744
-                $links[\EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
745
-                    array(
746
-                        'href'   => $this->get_versioned_link_to(
747
-                            \EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
748
-                            . '/'
749
-                            . $entity_array[$model->primary_key_name()]
750
-                            . '/'
751
-                            . $related_model_part
752
-                        ),
753
-                        'single' => $relation_obj instanceof \EE_Belongs_To_Relation ? true : false,
754
-                    ),
755
-                );
756
-            }
757
-        }
758
-        return $links;
759
-    }
760
-
761
-
762
-
763
-    /**
764
-     * Adds the included models indicated in the request to the entity provided
765
-     *
766
-     * @param \EEM_Base        $model
767
-     * @param \WP_REST_Request $rest_request
768
-     * @param array            $entity_array
769
-     * @param array            $db_row
770
-     * @return array the modified entity
771
-     */
772
-    protected function _include_requested_models(
773
-        \EEM_Base $model,
774
-        \WP_REST_Request $rest_request,
775
-        $entity_array,
776
-        $db_row = array()
777
-    ) {
778
-        //if $db_row not included, hope the entity array has what we need
779
-        if (! $db_row) {
780
-            $db_row = $entity_array;
781
-        }
782
-        $includes_for_this_model = $this->explode_and_get_items_prefixed_with($rest_request->get_param('include'), '');
783
-        $includes_for_this_model = $this->_remove_model_names_from_array($includes_for_this_model);
784
-        //if they passed in * or didn't specify any includes, return everything
785
-        if (! in_array('*', $includes_for_this_model)
786
-            && ! empty($includes_for_this_model)
787
-        ) {
788
-            if ($model->has_primary_key_field()) {
789
-                //always include the primary key. ya just gotta know that at least
790
-                $includes_for_this_model[] = $model->primary_key_name();
791
-            }
792
-            if ($this->explode_and_get_items_prefixed_with($rest_request->get_param('calculate'), '')) {
793
-                $includes_for_this_model[] = '_calculated_fields';
794
-            }
795
-            $entity_array = array_intersect_key($entity_array, array_flip($includes_for_this_model));
796
-        }
797
-        $relation_settings = $this->get_model_version_info()->relation_settings($model);
798
-        foreach ($relation_settings as $relation_name => $relation_obj) {
799
-            $related_fields_to_include = $this->explode_and_get_items_prefixed_with(
800
-                $rest_request->get_param('include'),
801
-                $relation_name
802
-            );
803
-            $related_fields_to_calculate = $this->explode_and_get_items_prefixed_with(
804
-                $rest_request->get_param('calculate'),
805
-                $relation_name
806
-            );
807
-            //did they specify they wanted to include a related model, or
808
-            //specific fields from a related model?
809
-            //or did they specify to calculate a field from a related model?
810
-            if ($related_fields_to_include || $related_fields_to_calculate) {
811
-                //if so, we should include at least some part of the related model
812
-                $pretend_related_request = new \WP_REST_Request();
813
-                $pretend_related_request->set_query_params(
814
-                    array(
815
-                        'caps'      => $rest_request->get_param('caps'),
816
-                        'include'   => $related_fields_to_include,
817
-                        'calculate' => $related_fields_to_calculate,
818
-                    )
819
-                );
820
-                $pretend_related_request->add_header('no_rest_headers', true);
821
-                $primary_model_query_params = $model->alter_query_params_to_restrict_by_ID(
822
-                    $model->get_index_primary_key_string(
823
-                        $model->deduce_fields_n_values_from_cols_n_values($db_row)
824
-                    )
825
-                );
826
-                $related_results = $this->_get_entities_from_relation(
827
-                    $primary_model_query_params,
828
-                    $relation_obj,
829
-                    $pretend_related_request
830
-                );
831
-                $entity_array[Read::get_related_entity_name($relation_name, $relation_obj)] = $related_results
832
-                                                                                              instanceof
833
-                                                                                              \WP_Error
834
-                    ? null
835
-                    : $related_results;
836
-            }
837
-        }
838
-        return $entity_array;
839
-    }
840
-
841
-
842
-
843
-    /**
844
-     * Returns a new array with all the names of models removed. Eg
845
-     * array( 'Event', 'Datetime.*', 'foobar' ) would become array( 'Datetime.*', 'foobar' )
846
-     *
847
-     * @param array $arr
848
-     * @return array
849
-     */
850
-    private function _remove_model_names_from_array($arr)
851
-    {
852
-        return array_diff($arr, array_keys(\EE_Registry::instance()->non_abstract_db_models));
853
-    }
854
-
855
-
856
-
857
-    /**
858
-     * Gets the calculated fields for the response
859
-     *
860
-     * @param \EEM_Base        $model
861
-     * @param array            $wpdb_row
862
-     * @param \WP_REST_Request $rest_request
863
-     * @return \stdClass the _calculations item in the entity
864
-     */
865
-    protected function _get_entity_calculations($model, $wpdb_row, $rest_request)
866
-    {
867
-        $calculated_fields = $this->explode_and_get_items_prefixed_with(
868
-            $rest_request->get_param('calculate'),
869
-            ''
870
-        );
871
-        //note: setting calculate=* doesn't do anything
872
-        $calculated_fields_to_return = new \stdClass();
873
-        foreach ($calculated_fields as $field_to_calculate) {
874
-            try {
875
-                $calculated_fields_to_return->$field_to_calculate = Model_Data_Translator::prepare_field_value_for_json(
876
-                    null,
877
-                    $this->_fields_calculator->retrieve_calculated_field_value(
878
-                        $model,
879
-                        $field_to_calculate,
880
-                        $wpdb_row,
881
-                        $rest_request,
882
-                        $this
883
-                    ),
884
-                    $this->get_model_version_info()->requested_version()
885
-                );
886
-            } catch (Rest_Exception $e) {
887
-                //if we don't have permission to read it, just leave it out. but let devs know about the problem
888
-                $this->_set_response_header(
889
-                    'Notices-Field-Calculation-Errors['
890
-                    . $e->get_string_code()
891
-                    . ']['
892
-                    . $model->get_this_model_name()
893
-                    . ']['
894
-                    . $field_to_calculate
895
-                    . ']',
896
-                    $e->getMessage(),
897
-                    true
898
-                );
899
-            }
900
-        }
901
-        return $calculated_fields_to_return;
902
-    }
903
-
904
-
905
-
906
-    /**
907
-     * Gets the full URL to the resource, taking the requested version into account
908
-     *
909
-     * @param string $link_part_after_version_and_slash eg "events/10/datetimes"
910
-     * @return string url eg "http://mysite.com/wp-json/ee/v4.6/events/10/datetimes"
911
-     */
912
-    public function get_versioned_link_to($link_part_after_version_and_slash)
913
-    {
914
-        return rest_url(
915
-            \EED_Core_Rest_Api::ee_api_namespace
916
-            . $this->get_model_version_info()->requested_version()
917
-            . '/'
918
-            . $link_part_after_version_and_slash
919
-        );
920
-    }
921
-
922
-
923
-
924
-    /**
925
-     * Gets the correct lowercase name for the relation in the API according
926
-     * to the relation's type
927
-     *
928
-     * @param string                  $relation_name
929
-     * @param \EE_Model_Relation_Base $relation_obj
930
-     * @return string
931
-     */
932
-    public static function get_related_entity_name($relation_name, $relation_obj)
933
-    {
934
-        if ($relation_obj instanceof \EE_Belongs_To_Relation) {
935
-            return strtolower($relation_name);
936
-        } else {
937
-            return \EEH_Inflector::pluralize_and_lower($relation_name);
938
-        }
939
-    }
940
-
941
-
942
-
943
-    /**
944
-     * Gets the one model object with the specified id for the specified model
945
-     *
946
-     * @param \EEM_Base        $model
947
-     * @param \WP_REST_Request $request
948
-     * @return array|\WP_Error
949
-     */
950
-    public function get_entity_from_model($model, $request)
951
-    {
952
-        $query_params = array(array($model->primary_key_name() => $request->get_param('id')), 'limit' => 1);
953
-        if ($model instanceof \EEM_Soft_Delete_Base) {
954
-            $query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($query_params);
955
-        }
956
-        $restricted_query_params = $query_params;
957
-        $restricted_query_params['caps'] = $this->validate_context($request->get_param('caps'));
958
-        $this->_set_debug_info('model query params', $restricted_query_params);
959
-        $model_rows = $model->get_all_wpdb_results($restricted_query_params);
960
-        if (! empty ($model_rows)) {
961
-            return $this->create_entity_from_wpdb_result(
962
-                $model,
963
-                array_shift($model_rows),
964
-                $request);
965
-        } else {
966
-            //ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
967
-            $lowercase_model_name = strtolower($model->get_this_model_name());
968
-            $model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
969
-            if (! empty($model_rows_found_sans_restrictions)) {
970
-                //you got shafted- it existed but we didn't want to tell you!
971
-                return new \WP_Error(
972
-                    'rest_user_cannot_read',
973
-                    sprintf(
974
-                        __('Sorry, you cannot read this %1$s. Missing permissions are: %2$s', 'event_espresso'),
975
-                        strtolower($model->get_this_model_name()),
976
-                        Capabilities::get_missing_permissions_string(
977
-                            $model,
978
-                            $this->validate_context($request->get_param('caps')))
979
-                    ),
980
-                    array('status' => 403)
981
-                );
982
-            } else {
983
-                //it's not you. It just doesn't exist
984
-                return new \WP_Error(
985
-                    sprintf('rest_%s_invalid_id', $lowercase_model_name),
986
-                    sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
987
-                    array('status' => 404)
988
-                );
989
-            }
990
-        }
991
-    }
992
-
993
-
994
-
995
-    /**
996
-     * If a context is provided which isn't valid, maybe it was added in a future
997
-     * version so just treat it as a default read
998
-     *
999
-     * @param string $context
1000
-     * @return string array key of EEM_Base::cap_contexts_to_cap_action_map()
1001
-     */
1002
-    public function validate_context($context)
1003
-    {
1004
-        if (! $context) {
1005
-            $context = \EEM_Base::caps_read;
1006
-        }
1007
-        $valid_contexts = \EEM_Base::valid_cap_contexts();
1008
-        if (in_array($context, $valid_contexts)) {
1009
-            return $context;
1010
-        } else {
1011
-            return \EEM_Base::caps_read;
1012
-        }
1013
-    }
1014
-
1015
-
1016
-
1017
-    /**
1018
-     * Verifies the passed in value is an allowable default where conditions value.
1019
-     *
1020
-     * @param $default_query_params
1021
-     * @return string
1022
-     */
1023
-    public function validate_default_query_params($default_query_params)
1024
-    {
1025
-        $valid_default_where_conditions_for_api_calls = array(
1026
-            \EEM_Base::default_where_conditions_all,
1027
-            \EEM_Base::default_where_conditions_minimum_all,
1028
-            \EEM_Base::default_where_conditions_minimum_others,
1029
-        );
1030
-        if (! $default_query_params) {
1031
-            $default_query_params = \EEM_Base::default_where_conditions_all;
1032
-        }
1033
-        if (
1034
-        in_array(
1035
-            $default_query_params,
1036
-            $valid_default_where_conditions_for_api_calls,
1037
-            true
1038
-        )
1039
-        ) {
1040
-            return $default_query_params;
1041
-        } else {
1042
-            return \EEM_Base::default_where_conditions_all;
1043
-        }
1044
-    }
1045
-
1046
-
1047
-
1048
-    /**
1049
-     * Translates API filter get parameter into $query_params array used by EEM_Base::get_all().
1050
-     * Note: right now the query parameter keys for fields (and related fields)
1051
-     * can be left as-is, but it's quite possible this will change someday.
1052
-     * Also, this method's contents might be candidate for moving to Model_Data_Translator
1053
-     *
1054
-     * @param \EEM_Base $model
1055
-     * @param array     $query_parameters from $_GET parameter @see Read:handle_request_get_all
1056
-     * @return array like what EEM_Base::get_all() expects or FALSE to indicate
1057
-     *                                    that absolutely no results should be returned
1058
-     * @throws \EE_Error
1059
-     */
1060
-    public function create_model_query_params($model, $query_parameters)
1061
-    {
1062
-        $model_query_params = array();
1063
-        if (isset($query_parameters['where'])) {
1064
-            $model_query_params[0] = Model_Data_Translator::prepare_conditions_query_params_for_models(
1065
-                $query_parameters['where'],
1066
-                $model,
1067
-                $this->get_model_version_info()->requested_version()
1068
-            );
1069
-        }
1070
-        if (isset($query_parameters['order_by'])) {
1071
-            $order_by = $query_parameters['order_by'];
1072
-        } elseif (isset($query_parameters['orderby'])) {
1073
-            $order_by = $query_parameters['orderby'];
1074
-        } else {
1075
-            $order_by = null;
1076
-        }
1077
-        if ($order_by !== null) {
1078
-            if (is_array($order_by)) {
1079
-                $order_by = Model_Data_Translator::prepare_field_names_in_array_keys_from_json($order_by);
1080
-            } else {
1081
-                //it's a single item
1082
-                $order_by = Model_Data_Translator::prepare_field_name_from_json($order_by);
1083
-            }
1084
-            $model_query_params['order_by'] = $order_by;
1085
-        }
1086
-        if (isset($query_parameters['group_by'])) {
1087
-            $group_by = $query_parameters['group_by'];
1088
-        } elseif (isset($query_parameters['groupby'])) {
1089
-            $group_by = $query_parameters['groupby'];
1090
-        } else {
1091
-            $group_by = array_keys($model->get_combined_primary_key_fields());
1092
-        }
1093
-        //make sure they're all real names
1094
-        if (is_array($group_by)) {
1095
-            $group_by = Model_Data_Translator::prepare_field_names_from_json($group_by);
1096
-        }
1097
-        if ($group_by !== null) {
1098
-            $model_query_params['group_by'] = $group_by;
1099
-        }
1100
-        if (isset($query_parameters['having'])) {
1101
-            $model_query_params['having'] = Model_Data_Translator::prepare_conditions_query_params_for_models(
1102
-                $query_parameters['having'],
1103
-                $model,
1104
-                $this->get_model_version_info()->requested_version()
1105
-            );
1106
-        }
1107
-        if (isset($query_parameters['order'])) {
1108
-            $model_query_params['order'] = $query_parameters['order'];
1109
-        }
1110
-        if (isset($query_parameters['mine'])) {
1111
-            $model_query_params = $model->alter_query_params_to_only_include_mine($model_query_params);
1112
-        }
1113
-        if (isset($query_parameters['limit'])) {
1114
-            //limit should be either a string like '23' or '23,43', or an array with two items in it
1115
-            if (! is_array($query_parameters['limit'])) {
1116
-                $limit_array = explode(',', (string)$query_parameters['limit']);
1117
-            } else {
1118
-                $limit_array = $query_parameters['limit'];
1119
-            }
1120
-            $sanitized_limit = array();
1121
-            foreach ($limit_array as $key => $limit_part) {
1122
-                if ($this->_debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1123
-                    throw new \EE_Error(
1124
-                        sprintf(
1125
-                            __('An invalid limit filter was provided. It was: %s. If the EE4 JSON REST API weren\'t in debug mode, this message would not appear.',
1126
-                                'event_espresso'),
1127
-                            wp_json_encode($query_parameters['limit'])
1128
-                        )
1129
-                    );
1130
-                }
1131
-                $sanitized_limit[] = (int)$limit_part;
1132
-            }
1133
-            $model_query_params['limit'] = implode(',', $sanitized_limit);
1134
-        } else {
1135
-            $model_query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
1136
-        }
1137
-        if (isset($query_parameters['caps'])) {
1138
-            $model_query_params['caps'] = $this->validate_context($query_parameters['caps']);
1139
-        } else {
1140
-            $model_query_params['caps'] = \EEM_Base::caps_read;
1141
-        }
1142
-        if (isset($query_parameters['default_where_conditions'])) {
1143
-            $model_query_params['default_where_conditions'] = $this->validate_default_query_params($query_parameters['default_where_conditions']);
1144
-        }
1145
-        return apply_filters('FHEE__Read__create_model_query_params', $model_query_params, $query_parameters, $model);
1146
-    }
1147
-
1148
-
1149
-
1150
-    /**
1151
-     * Changes the REST-style query params for use in the models
1152
-     *
1153
-     * @deprecated
1154
-     * @param \EEM_Base $model
1155
-     * @param array     $query_params sub-array from @see EEM_Base::get_all()
1156
-     * @return array
1157
-     */
1158
-    public function prepare_rest_query_params_key_for_models($model, $query_params)
1159
-    {
1160
-        $model_ready_query_params = array();
1161
-        foreach ($query_params as $key => $value) {
1162
-            if (is_array($value)) {
1163
-                $model_ready_query_params[$key] = $this->prepare_rest_query_params_key_for_models($model, $value);
1164
-            } else {
1165
-                $model_ready_query_params[$key] = $value;
1166
-            }
1167
-        }
1168
-        return $model_ready_query_params;
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * @deprecated
1175
-     * @param $model
1176
-     * @param $query_params
1177
-     * @return array
1178
-     */
1179
-    public function prepare_rest_query_params_values_for_models($model, $query_params)
1180
-    {
1181
-        $model_ready_query_params = array();
1182
-        foreach ($query_params as $key => $value) {
1183
-            if (is_array($value)) {
1184
-                $model_ready_query_params[$key] = $this->prepare_rest_query_params_values_for_models($model, $value);
1185
-            } else {
1186
-                $model_ready_query_params[$key] = $value;
1187
-            }
1188
-        }
1189
-        return $model_ready_query_params;
1190
-    }
1191
-
1192
-
1193
-
1194
-    /**
1195
-     * Explodes the string on commas, and only returns items with $prefix followed by a period.
1196
-     * If no prefix is specified, returns items with no period.
1197
-     *
1198
-     * @param string|array $string_to_explode eg "jibba,jabba, blah, blaabla" or array('jibba', 'jabba' )
1199
-     * @param string       $prefix            "Event" or "foobar"
1200
-     * @return array $string_to_exploded exploded on COMMAS, and if a prefix was specified
1201
-     *                                        we only return strings starting with that and a period; if no prefix was
1202
-     *                                        specified we return all items containing NO periods
1203
-     */
1204
-    public function explode_and_get_items_prefixed_with($string_to_explode, $prefix)
1205
-    {
1206
-        if (is_string($string_to_explode)) {
1207
-            $exploded_contents = explode(',', $string_to_explode);
1208
-        } else if (is_array($string_to_explode)) {
1209
-            $exploded_contents = $string_to_explode;
1210
-        } else {
1211
-            $exploded_contents = array();
1212
-        }
1213
-        //if the string was empty, we want an empty array
1214
-        $exploded_contents = array_filter($exploded_contents);
1215
-        $contents_with_prefix = array();
1216
-        foreach ($exploded_contents as $item) {
1217
-            $item = trim($item);
1218
-            //if no prefix was provided, so we look for items with no "." in them
1219
-            if (! $prefix) {
1220
-                //does this item have a period?
1221
-                if (strpos($item, '.') === false) {
1222
-                    //if not, then its what we're looking for
1223
-                    $contents_with_prefix[] = $item;
1224
-                }
1225
-            } else if (strpos($item, $prefix . '.') === 0) {
1226
-                //this item has the prefix and a period, grab it
1227
-                $contents_with_prefix[] = substr(
1228
-                    $item,
1229
-                    strpos($item, $prefix . '.') + strlen($prefix . '.')
1230
-                );
1231
-            } else if ($item === $prefix) {
1232
-                //this item is JUST the prefix
1233
-                //so let's grab everything after, which is a blank string
1234
-                $contents_with_prefix[] = '';
1235
-            }
1236
-        }
1237
-        return $contents_with_prefix;
1238
-    }
1239
-
1240
-
1241
-
1242
-    /**
1243
-     * @deprecated since 4.8.36.rc.001 You should instead use Read::explode_and_get_items_prefixed_with.
1244
-     * Deprecated because its return values were really quite confusing- sometimes it returned
1245
-     * an empty array (when the include string was blank or '*') or sometimes it returned
1246
-     * array('*') (when you provided a model and a model of that kind was found).
1247
-     * Parses the $include_string so we fetch all the field names relating to THIS model
1248
-     * (ie have NO period in them), or for the provided model (ie start with the model
1249
-     * name and then a period).
1250
-     * @param string $include_string @see Read:handle_request_get_all
1251
-     * @param string $model_name
1252
-     * @return array of fields for this model. If $model_name is provided, then
1253
-     *                               the fields for that model, with the model's name removed from each.
1254
-     *                               If $include_string was blank or '*' returns an empty array
1255
-     */
1256
-    public function extract_includes_for_this_model($include_string, $model_name = null)
1257
-    {
1258
-        if (is_array($include_string)) {
1259
-            $include_string = implode(',', $include_string);
1260
-        }
1261
-        if ($include_string === '*' || $include_string === '') {
1262
-            return array();
1263
-        }
1264
-        $includes = explode(',', $include_string);
1265
-        $extracted_fields_to_include = array();
1266
-        if ($model_name) {
1267
-            foreach ($includes as $field_to_include) {
1268
-                $field_to_include = trim($field_to_include);
1269
-                if (strpos($field_to_include, $model_name . '.') === 0) {
1270
-                    //found the model name at the exact start
1271
-                    $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1272
-                    $extracted_fields_to_include[] = $field_sans_model_name;
1273
-                } elseif ($field_to_include == $model_name) {
1274
-                    $extracted_fields_to_include[] = '*';
1275
-                }
1276
-            }
1277
-        } else {
1278
-            //look for ones with no period
1279
-            foreach ($includes as $field_to_include) {
1280
-                $field_to_include = trim($field_to_include);
1281
-                if (
1282
-                    strpos($field_to_include, '.') === false
1283
-                    && ! $this->get_model_version_info()->is_model_name_in_this_version($field_to_include)
1284
-                ) {
1285
-                    $extracted_fields_to_include[] = $field_to_include;
1286
-                }
1287
-            }
1288
-        }
1289
-        return $extracted_fields_to_include;
1290
-    }
30
+	/**
31
+	 * @var Calculated_Model_Fields
32
+	 */
33
+	protected $_fields_calculator;
34
+
35
+
36
+
37
+	/**
38
+	 * Read constructor.
39
+	 */
40
+	public function __construct()
41
+	{
42
+		parent::__construct();
43
+		$this->_fields_calculator = new Calculated_Model_Fields();
44
+	}
45
+
46
+
47
+
48
+	/**
49
+	 * Handles requests to get all (or a filtered subset) of entities for a particular model
50
+	 *
51
+	 * @param \WP_REST_Request $request
52
+	 * @return \WP_REST_Response|\WP_Error
53
+	 */
54
+	public static function handle_request_get_all(\WP_REST_Request $request)
55
+	{
56
+		$controller = new Read();
57
+		try {
58
+			$matches = $controller->parse_route(
59
+				$request->get_route(),
60
+				'~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)~',
61
+				array('version', 'model')
62
+			);
63
+			$controller->set_requested_version($matches['version']);
64
+			$model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
65
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
66
+				return $controller->send_response(
67
+					new \WP_Error(
68
+						'endpoint_parsing_error',
69
+						sprintf(
70
+							__('There is no model for endpoint %s. Please contact event espresso support',
71
+								'event_espresso'),
72
+							$model_name_singular
73
+						)
74
+					)
75
+				);
76
+			}
77
+			return $controller->send_response(
78
+				$controller->get_entities_from_model(
79
+					$controller->get_model_version_info()->load_model($model_name_singular),
80
+					$request
81
+				)
82
+			);
83
+		} catch (\Exception $e) {
84
+			return $controller->send_response($e);
85
+		}
86
+	}
87
+
88
+
89
+
90
+	/**
91
+	 * Prepares and returns schema for any OPTIONS request.
92
+	 *
93
+	 * @param string $model_name Something like `Event` or `Registration`
94
+	 * @param string $version    The API endpoint version being used.
95
+	 * @return array
96
+	 */
97
+	public static function handle_schema_request($model_name, $version)
98
+	{
99
+		$controller = new Read();
100
+		try {
101
+			$controller->set_requested_version($version);
102
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name)) {
103
+				return array();
104
+			}
105
+			//get the model for this version
106
+			$model = $controller->get_model_version_info()->load_model($model_name);
107
+			$model_schema = new JsonModelSchema($model);
108
+			return $model_schema->getModelSchemaForRelations(
109
+				$controller->get_model_version_info()->relation_settings($model),
110
+				$controller->_customize_schema_for_rest_response(
111
+					$model,
112
+					$model_schema->getModelSchemaForFields(
113
+						$controller->get_model_version_info()->fields_on_model_in_this_version($model),
114
+						$model_schema->getInitialSchemaStructure()
115
+					)
116
+				)
117
+			);
118
+		} catch (\Exception $e) {
119
+			return array();
120
+		}
121
+	}
122
+
123
+
124
+
125
+	/**
126
+	 * This loops through each field in the given schema for the model and does the following:
127
+	 * - add any extra fields that are REST API specific and related to existing fields.
128
+	 * - transform default values into the correct format for a REST API response.
129
+	 *
130
+	 * @param \EEM_Base $model
131
+	 * @param array     $schema
132
+	 * @return array  The final schema.
133
+	 */
134
+	protected function _customize_schema_for_rest_response(\EEM_Base $model, array $schema)
135
+	{
136
+		foreach ($this->get_model_version_info()->fields_on_model_in_this_version($model) as $field_name => $field) {
137
+			$schema = $this->_translate_defaults_for_rest_response(
138
+				$field_name,
139
+				$field,
140
+				$this->_maybe_add_extra_fields_to_schema($field_name, $field, $schema)
141
+			);
142
+		}
143
+		return $schema;
144
+	}
145
+
146
+
147
+
148
+	/**
149
+	 * This is used to ensure that the 'default' value set in the schema response is formatted correctly for the REST
150
+	 * response.
151
+	 *
152
+	 * @param                      $field_name
153
+	 * @param \EE_Model_Field_Base $field
154
+	 * @param array                $schema
155
+	 * @return array
156
+	 */
157
+	protected function _translate_defaults_for_rest_response($field_name, \EE_Model_Field_Base $field, array $schema)
158
+	{
159
+		if (isset($schema['properties'][$field_name]['default'])) {
160
+			if (is_array($schema['properties'][$field_name]['default'])) {
161
+				foreach ($schema['properties'][$field_name]['default'] as $default_key => $default_value) {
162
+					if ($default_key === 'raw') {
163
+						$schema['properties'][$field_name]['default'][$default_key] = Model_Data_Translator::prepare_field_value_for_json(
164
+							$field,
165
+							$default_value,
166
+							$this->get_model_version_info()->requested_version()
167
+						);
168
+					}
169
+				}
170
+			} else {
171
+				$schema['properties'][$field_name]['default'] = Model_Data_Translator::prepare_field_value_for_json(
172
+					$field,
173
+					$schema['properties'][$field_name]['default'],
174
+					$this->get_model_version_info()->requested_version()
175
+				);
176
+			}
177
+		}
178
+		return $schema;
179
+	}
180
+
181
+
182
+
183
+	/**
184
+	 * Adds additional fields to the schema
185
+	 * The REST API returns a GMT value field for each datetime field in the resource.  Thus the description about this
186
+	 * needs to be added to the schema.
187
+	 *
188
+	 * @param                      $field_name
189
+	 * @param \EE_Model_Field_Base $field
190
+	 * @param array                $schema
191
+	 * @return array
192
+	 */
193
+	protected function _maybe_add_extra_fields_to_schema($field_name, \EE_Model_Field_Base $field, array $schema)
194
+	{
195
+		if ($field instanceof EE_Datetime_Field) {
196
+			$schema['properties'][$field_name . '_gmt'] = $field->getSchema();
197
+			//modify the description
198
+			$schema['properties'][$field_name . '_gmt']['description'] = sprintf(
199
+				esc_html__('%s - the value for this field is in GMT.', 'event_espresso'),
200
+				$field->get_nicename()
201
+			);
202
+		}
203
+		return $schema;
204
+	}
205
+
206
+
207
+
208
+	/**
209
+	 * Used to figure out the route from the request when a `WP_REST_Request` object is not available
210
+	 *
211
+	 * @return string
212
+	 */
213
+	protected function get_route_from_request()
214
+	{
215
+		if (isset($GLOBALS['wp'])
216
+			&& $GLOBALS['wp'] instanceof \WP
217
+			&& isset($GLOBALS['wp']->query_vars['rest_route'])
218
+		) {
219
+			return $GLOBALS['wp']->query_vars['rest_route'];
220
+		} else {
221
+			return isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/';
222
+		}
223
+	}
224
+
225
+
226
+
227
+	/**
228
+	 * Gets a single entity related to the model indicated in the path and its id
229
+	 *
230
+	 * @param \WP_REST_Request $request
231
+	 * @return \WP_REST_Response|\WP_Error
232
+	 */
233
+	public static function handle_request_get_one(\WP_REST_Request $request)
234
+	{
235
+		$controller = new Read();
236
+		try {
237
+			$matches = $controller->parse_route(
238
+				$request->get_route(),
239
+				'~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)~',
240
+				array('version', 'model', 'id'));
241
+			$controller->set_requested_version($matches['version']);
242
+			$model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
243
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
244
+				return $controller->send_response(
245
+					new \WP_Error(
246
+						'endpoint_parsing_error',
247
+						sprintf(
248
+							__('There is no model for endpoint %s. Please contact event espresso support',
249
+								'event_espresso'),
250
+							$model_name_singular
251
+						)
252
+					)
253
+				);
254
+			}
255
+			return $controller->send_response(
256
+				$controller->get_entity_from_model(
257
+					$controller->get_model_version_info()->load_model($model_name_singular),
258
+					$request
259
+				)
260
+			);
261
+		} catch (\Exception $e) {
262
+			return $controller->send_response($e);
263
+		}
264
+	}
265
+
266
+
267
+
268
+	/**
269
+	 * Gets all the related entities (or if its a belongs-to relation just the one)
270
+	 * to the item with the given id
271
+	 *
272
+	 * @param \WP_REST_Request $request
273
+	 * @return \WP_REST_Response|\WP_Error
274
+	 */
275
+	public static function handle_request_get_related(\WP_REST_Request $request)
276
+	{
277
+		$controller = new Read();
278
+		try {
279
+			$matches = $controller->parse_route(
280
+				$request->get_route(),
281
+				'~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)/(.*)~',
282
+				array('version', 'model', 'id', 'related_model')
283
+			);
284
+			$controller->set_requested_version($matches['version']);
285
+			$main_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
286
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($main_model_name_singular)) {
287
+				return $controller->send_response(
288
+					new \WP_Error(
289
+						'endpoint_parsing_error',
290
+						sprintf(
291
+							__('There is no model for endpoint %s. Please contact event espresso support',
292
+								'event_espresso'),
293
+							$main_model_name_singular
294
+						)
295
+					)
296
+				);
297
+			}
298
+			$main_model = $controller->get_model_version_info()->load_model($main_model_name_singular);
299
+			//assume the related model name is plural and try to find the model's name
300
+			$related_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['related_model']);
301
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
302
+				//so the word didn't singularize well. Maybe that's just because it's a singular word?
303
+				$related_model_name_singular = \EEH_Inflector::humanize($matches['related_model']);
304
+			}
305
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
306
+				return $controller->send_response(
307
+					new \WP_Error(
308
+						'endpoint_parsing_error',
309
+						sprintf(
310
+							__('There is no model for endpoint %s. Please contact event espresso support',
311
+								'event_espresso'),
312
+							$related_model_name_singular
313
+						)
314
+					)
315
+				);
316
+			}
317
+			return $controller->send_response(
318
+				$controller->get_entities_from_relation(
319
+					$request->get_param('id'),
320
+					$main_model->related_settings_for($related_model_name_singular),
321
+					$request
322
+				)
323
+			);
324
+		} catch (\Exception $e) {
325
+			return $controller->send_response($e);
326
+		}
327
+	}
328
+
329
+
330
+
331
+	/**
332
+	 * Gets a collection for the given model and filters
333
+	 *
334
+	 * @param \EEM_Base        $model
335
+	 * @param \WP_REST_Request $request
336
+	 * @return array|\WP_Error
337
+	 */
338
+	public function get_entities_from_model($model, $request)
339
+	{
340
+		$query_params = $this->create_model_query_params($model, $request->get_params());
341
+		if (! Capabilities::current_user_has_partial_access_to($model, $query_params['caps'])) {
342
+			$model_name_plural = \EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
343
+			return new \WP_Error(
344
+				sprintf('rest_%s_cannot_list', $model_name_plural),
345
+				sprintf(
346
+					__('Sorry, you are not allowed to list %1$s. Missing permissions: %2$s', 'event_espresso'),
347
+					$model_name_plural,
348
+					Capabilities::get_missing_permissions_string($model, $query_params['caps'])
349
+				),
350
+				array('status' => 403)
351
+			);
352
+		}
353
+		if (! $request->get_header('no_rest_headers')) {
354
+			$this->_set_headers_from_query_params($model, $query_params);
355
+		}
356
+		/** @type array $results */
357
+		$results = $model->get_all_wpdb_results($query_params);
358
+		$nice_results = array();
359
+		foreach ($results as $result) {
360
+			$nice_results[] = $this->create_entity_from_wpdb_result(
361
+				$model,
362
+				$result,
363
+				$request
364
+			);
365
+		}
366
+		return $nice_results;
367
+	}
368
+
369
+
370
+
371
+	/**
372
+	 * @param array                   $primary_model_query_params query params for finding the item from which
373
+	 *                                                            relations will be based
374
+	 * @param \EE_Model_Relation_Base $relation
375
+	 * @param \WP_REST_Request        $request
376
+	 * @return \WP_Error|array
377
+	 */
378
+	protected function _get_entities_from_relation($primary_model_query_params, $relation, $request)
379
+	{
380
+		$context = $this->validate_context($request->get_param('caps'));
381
+		$model = $relation->get_this_model();
382
+		$related_model = $relation->get_other_model();
383
+		if (! isset($primary_model_query_params[0])) {
384
+			$primary_model_query_params[0] = array();
385
+		}
386
+		//check if they can access the 1st model object
387
+		$primary_model_query_params = array(
388
+			0       => $primary_model_query_params[0],
389
+			'limit' => 1,
390
+		);
391
+		if ($model instanceof \EEM_Soft_Delete_Base) {
392
+			$primary_model_query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($primary_model_query_params);
393
+		}
394
+		$restricted_query_params = $primary_model_query_params;
395
+		$restricted_query_params['caps'] = $context;
396
+		$this->_set_debug_info('main model query params', $restricted_query_params);
397
+		$this->_set_debug_info('missing caps', Capabilities::get_missing_permissions_string($related_model, $context));
398
+		if (
399
+		! (
400
+			Capabilities::current_user_has_partial_access_to($related_model, $context)
401
+			&& $model->exists($restricted_query_params)
402
+		)
403
+		) {
404
+			if ($relation instanceof \EE_Belongs_To_Relation) {
405
+				$related_model_name_maybe_plural = strtolower($related_model->get_this_model_name());
406
+			} else {
407
+				$related_model_name_maybe_plural = \EEH_Inflector::pluralize_and_lower($related_model->get_this_model_name());
408
+			}
409
+			return new \WP_Error(
410
+				sprintf('rest_%s_cannot_list', $related_model_name_maybe_plural),
411
+				sprintf(
412
+					__('Sorry, you are not allowed to list %1$s related to %2$s. Missing permissions: %3$s',
413
+						'event_espresso'),
414
+					$related_model_name_maybe_plural,
415
+					$relation->get_this_model()->get_this_model_name(),
416
+					implode(
417
+						',',
418
+						array_keys(
419
+							Capabilities::get_missing_permissions($related_model, $context)
420
+						)
421
+					)
422
+				),
423
+				array('status' => 403)
424
+			);
425
+		}
426
+		$query_params = $this->create_model_query_params($relation->get_other_model(), $request->get_params());
427
+		foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) {
428
+			$query_params[0][$relation->get_this_model()->get_this_model_name()
429
+							 . '.'
430
+							 . $where_condition_key] = $where_condition_value;
431
+		}
432
+		$query_params['default_where_conditions'] = 'none';
433
+		$query_params['caps'] = $context;
434
+		if (! $request->get_header('no_rest_headers')) {
435
+			$this->_set_headers_from_query_params($relation->get_other_model(), $query_params);
436
+		}
437
+		/** @type array $results */
438
+		$results = $relation->get_other_model()->get_all_wpdb_results($query_params);
439
+		$nice_results = array();
440
+		foreach ($results as $result) {
441
+			$nice_result = $this->create_entity_from_wpdb_result(
442
+				$relation->get_other_model(),
443
+				$result,
444
+				$request
445
+			);
446
+			if ($relation instanceof \EE_HABTM_Relation) {
447
+				//put the unusual stuff (properties from the HABTM relation) first, and make sure
448
+				//if there are conflicts we prefer the properties from the main model
449
+				$join_model_result = $this->create_entity_from_wpdb_result(
450
+					$relation->get_join_model(),
451
+					$result,
452
+					$request
453
+				);
454
+				$joined_result = array_merge($nice_result, $join_model_result);
455
+				//but keep the meta stuff from the main model
456
+				if (isset($nice_result['meta'])) {
457
+					$joined_result['meta'] = $nice_result['meta'];
458
+				}
459
+				$nice_result = $joined_result;
460
+			}
461
+			$nice_results[] = $nice_result;
462
+		}
463
+		if ($relation instanceof \EE_Belongs_To_Relation) {
464
+			return array_shift($nice_results);
465
+		} else {
466
+			return $nice_results;
467
+		}
468
+	}
469
+
470
+
471
+
472
+	/**
473
+	 * Gets the collection for given relation object
474
+	 * The same as Read::get_entities_from_model(), except if the relation
475
+	 * is a HABTM relation, in which case it merges any non-foreign-key fields from
476
+	 * the join-model-object into the results
477
+	 *
478
+	 * @param string                  $id the ID of the thing we are fetching related stuff from
479
+	 * @param \EE_Model_Relation_Base $relation
480
+	 * @param \WP_REST_Request        $request
481
+	 * @return array|\WP_Error
482
+	 * @throws \EE_Error
483
+	 */
484
+	public function get_entities_from_relation($id, $relation, $request)
485
+	{
486
+		if (! $relation->get_this_model()->has_primary_key_field()) {
487
+			throw new \EE_Error(
488
+				sprintf(
489
+					__('Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
490
+						'event_espresso'),
491
+					$relation->get_this_model()->get_this_model_name()
492
+				)
493
+			);
494
+		}
495
+		return $this->_get_entities_from_relation(
496
+			array(
497
+				array(
498
+					$relation->get_this_model()->primary_key_name() => $id,
499
+				),
500
+			),
501
+			$relation,
502
+			$request
503
+		);
504
+	}
505
+
506
+
507
+
508
+	/**
509
+	 * Sets the headers that are based on the model and query params,
510
+	 * like the total records. This should only be called on the original request
511
+	 * from the client, not on subsequent internal
512
+	 *
513
+	 * @param \EEM_Base $model
514
+	 * @param array     $query_params
515
+	 * @return void
516
+	 */
517
+	protected function _set_headers_from_query_params($model, $query_params)
518
+	{
519
+		$this->_set_debug_info('model query params', $query_params);
520
+		$this->_set_debug_info('missing caps',
521
+			Capabilities::get_missing_permissions_string($model, $query_params['caps']));
522
+		//normally the limit to a 2-part array, where the 2nd item is the limit
523
+		if (! isset($query_params['limit'])) {
524
+			$query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
525
+		}
526
+		if (is_array($query_params['limit'])) {
527
+			$limit_parts = $query_params['limit'];
528
+		} else {
529
+			$limit_parts = explode(',', $query_params['limit']);
530
+			if (count($limit_parts) == 1) {
531
+				$limit_parts = array(0, $limit_parts[0]);
532
+			}
533
+		}
534
+		//remove the group by and having parts of the query, as those will
535
+		//make the sql query return an array of values, instead of just a single value
536
+		unset($query_params['group_by'], $query_params['having'], $query_params['limit']);
537
+		$count = $model->count($query_params, null, true);
538
+		$pages = $count / $limit_parts[1];
539
+		$this->_set_response_header('Total', $count, false);
540
+		$this->_set_response_header('PageSize', $limit_parts[1], false);
541
+		$this->_set_response_header('TotalPages', ceil($pages), false);
542
+	}
543
+
544
+
545
+
546
+	/**
547
+	 * Changes database results into REST API entities
548
+	 *
549
+	 * @param \EEM_Base        $model
550
+	 * @param array            $db_row     like results from $wpdb->get_results()
551
+	 * @param \WP_REST_Request $rest_request
552
+	 * @param string           $deprecated no longer used
553
+	 * @return array ready for being converted into json for sending to client
554
+	 */
555
+	public function create_entity_from_wpdb_result($model, $db_row, $rest_request, $deprecated = null)
556
+	{
557
+		if (! $rest_request instanceof \WP_REST_Request) {
558
+			//ok so this was called in the old style, where the 3rd arg was
559
+			//$include, and the 4th arg was $context
560
+			//now setup the request just to avoid fatal errors, although we won't be able
561
+			//to truly make use of it because it's kinda devoid of info
562
+			$rest_request = new \WP_REST_Request();
563
+			$rest_request->set_param('include', $rest_request);
564
+			$rest_request->set_param('caps', $deprecated);
565
+		}
566
+		if ($rest_request->get_param('caps') == null) {
567
+			$rest_request->set_param('caps', \EEM_Base::caps_read);
568
+		}
569
+		$entity_array = $this->_create_bare_entity_from_wpdb_results($model, $db_row);
570
+		$entity_array = $this->_add_extra_fields($model, $db_row, $entity_array);
571
+		$entity_array['_links'] = $this->_get_entity_links($model, $db_row, $entity_array);
572
+		$entity_array['_calculated_fields'] = $this->_get_entity_calculations($model, $db_row, $rest_request);
573
+		$entity_array = apply_filters('FHEE__Read__create_entity_from_wpdb_results__entity_before_including_requested_models',
574
+			$entity_array, $model, $rest_request->get_param('caps'), $rest_request, $this);
575
+		$entity_array = $this->_include_requested_models($model, $rest_request, $entity_array, $db_row);
576
+		$entity_array = apply_filters(
577
+			'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal',
578
+			$entity_array,
579
+			$model,
580
+			$rest_request->get_param('caps'),
581
+			$rest_request,
582
+			$this
583
+		);
584
+		$result_without_inaccessible_fields = Capabilities::filter_out_inaccessible_entity_fields(
585
+			$entity_array,
586
+			$model,
587
+			$rest_request->get_param('caps'),
588
+			$this->get_model_version_info(),
589
+			$model->get_index_primary_key_string(
590
+				$model->deduce_fields_n_values_from_cols_n_values($db_row)
591
+			)
592
+		);
593
+		$this->_set_debug_info(
594
+			'inaccessible fields',
595
+			array_keys(array_diff_key($entity_array, $result_without_inaccessible_fields))
596
+		);
597
+		return apply_filters(
598
+			'FHEE__Read__create_entity_from_wpdb_results__entity_return',
599
+			$result_without_inaccessible_fields,
600
+			$model,
601
+			$rest_request->get_param('caps')
602
+		);
603
+	}
604
+
605
+
606
+
607
+	/**
608
+	 * Creates a REST entity array (JSON object we're going to return in the response, but
609
+	 * for now still a PHP array, but soon enough we'll call json_encode on it, don't worry),
610
+	 * from $wpdb->get_row( $sql, ARRAY_A)
611
+	 *
612
+	 * @param \EEM_Base $model
613
+	 * @param array     $db_row
614
+	 * @return array entity mostly ready for converting to JSON and sending in the response
615
+	 */
616
+	protected function _create_bare_entity_from_wpdb_results(\EEM_Base $model, $db_row)
617
+	{
618
+		$result = $model->deduce_fields_n_values_from_cols_n_values($db_row);
619
+		$result = array_intersect_key($result,
620
+			$this->get_model_version_info()->fields_on_model_in_this_version($model));
621
+		//if this is a CPT, we need to set the global $post to it,
622
+		//otherwise shortcodes etc won't work properly while rendering it
623
+		if ($model instanceof \EEM_CPT_Base) {
624
+			$do_chevy_shuffle = true;
625
+		} else {
626
+			$do_chevy_shuffle = false;
627
+		}
628
+		if ($do_chevy_shuffle) {
629
+			global $post;
630
+			$old_post = $post;
631
+			$post = get_post($result[$model->primary_key_name()]);
632
+			$model_object_classname = 'EE_' . $model->get_this_model_name();
633
+			$post->{$model_object_classname} = \EE_Registry::instance()->load_class(
634
+				$model_object_classname,
635
+				$result,
636
+				false,
637
+				false
638
+				);
639
+		}
640
+		foreach ($result as $field_name => $raw_field_value) {
641
+			$field_obj = $model->field_settings_for($field_name);
642
+			$field_value = $field_obj->prepare_for_set_from_db($raw_field_value);
643
+			if ($this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_ignored())) {
644
+				unset($result[$field_name]);
645
+			} elseif (
646
+			$this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_that_have_rendered_format())
647
+			) {
648
+				$result[$field_name] = array(
649
+					'raw'      => $field_obj->prepare_for_get($field_value),
650
+					'rendered' => $field_obj->prepare_for_pretty_echoing($field_value),
651
+				);
652
+			} elseif (
653
+			$this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_that_have_pretty_format())
654
+			) {
655
+				$result[$field_name] = array(
656
+					'raw'    => $field_obj->prepare_for_get($field_value),
657
+					'pretty' => $field_obj->prepare_for_pretty_echoing($field_value),
658
+				);
659
+			} elseif ($field_obj instanceof \EE_Datetime_Field) {
660
+				if ($field_value instanceof \DateTime) {
661
+					$timezone = $field_value->getTimezone();
662
+					$field_value->setTimezone(new \DateTimeZone('UTC'));
663
+					$result[$field_name . '_gmt'] = Model_Data_Translator::prepare_field_value_for_json(
664
+						$field_obj,
665
+						$field_value,
666
+						$this->get_model_version_info()->requested_version()
667
+					);
668
+					$field_value->setTimezone($timezone);
669
+					$result[$field_name] = Model_Data_Translator::prepare_field_value_for_json(
670
+						$field_obj,
671
+						$field_value,
672
+						$this->get_model_version_info()->requested_version()
673
+					);
674
+				}
675
+			} else {
676
+				$result[$field_name] = Model_Data_Translator::prepare_field_value_for_json(
677
+					$field_obj,
678
+					$field_obj->prepare_for_get($field_value),
679
+					$this->get_model_version_info()->requested_version()
680
+				);
681
+			}
682
+		}
683
+		if ($do_chevy_shuffle) {
684
+			$post = $old_post;
685
+		}
686
+		return $result;
687
+	}
688
+
689
+
690
+
691
+	/**
692
+	 * Adds a few extra fields to the entity response
693
+	 *
694
+	 * @param \EEM_Base $model
695
+	 * @param array     $db_row
696
+	 * @param array     $entity_array
697
+	 * @return array modified entity
698
+	 */
699
+	protected function _add_extra_fields(\EEM_Base $model, $db_row, $entity_array)
700
+	{
701
+		if ($model instanceof \EEM_CPT_Base) {
702
+			$entity_array['link'] = get_permalink($db_row[$model->get_primary_key_field()->get_qualified_column()]);
703
+		}
704
+		return $entity_array;
705
+	}
706
+
707
+
708
+
709
+	/**
710
+	 * Gets links we want to add to the response
711
+	 *
712
+	 * @global \WP_REST_Server $wp_rest_server
713
+	 * @param \EEM_Base        $model
714
+	 * @param array            $db_row
715
+	 * @param array            $entity_array
716
+	 * @return array the _links item in the entity
717
+	 */
718
+	protected function _get_entity_links($model, $db_row, $entity_array)
719
+	{
720
+		//add basic links
721
+		$links = array();
722
+		if ($model->has_primary_key_field()) {
723
+			$links['self'] = array(
724
+				array(
725
+					'href' => $this->get_versioned_link_to(
726
+						\EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
727
+						. '/'
728
+						. $entity_array[$model->primary_key_name()]
729
+					),
730
+				),
731
+			);
732
+		}
733
+		$links['collection'] = array(
734
+			array(
735
+				'href' => $this->get_versioned_link_to(
736
+					\EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
737
+				),
738
+			),
739
+		);
740
+		//add links to related models
741
+		if ($model->has_primary_key_field()) {
742
+			foreach ($this->get_model_version_info()->relation_settings($model) as $relation_name => $relation_obj) {
743
+				$related_model_part = Read::get_related_entity_name($relation_name, $relation_obj);
744
+				$links[\EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
745
+					array(
746
+						'href'   => $this->get_versioned_link_to(
747
+							\EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
748
+							. '/'
749
+							. $entity_array[$model->primary_key_name()]
750
+							. '/'
751
+							. $related_model_part
752
+						),
753
+						'single' => $relation_obj instanceof \EE_Belongs_To_Relation ? true : false,
754
+					),
755
+				);
756
+			}
757
+		}
758
+		return $links;
759
+	}
760
+
761
+
762
+
763
+	/**
764
+	 * Adds the included models indicated in the request to the entity provided
765
+	 *
766
+	 * @param \EEM_Base        $model
767
+	 * @param \WP_REST_Request $rest_request
768
+	 * @param array            $entity_array
769
+	 * @param array            $db_row
770
+	 * @return array the modified entity
771
+	 */
772
+	protected function _include_requested_models(
773
+		\EEM_Base $model,
774
+		\WP_REST_Request $rest_request,
775
+		$entity_array,
776
+		$db_row = array()
777
+	) {
778
+		//if $db_row not included, hope the entity array has what we need
779
+		if (! $db_row) {
780
+			$db_row = $entity_array;
781
+		}
782
+		$includes_for_this_model = $this->explode_and_get_items_prefixed_with($rest_request->get_param('include'), '');
783
+		$includes_for_this_model = $this->_remove_model_names_from_array($includes_for_this_model);
784
+		//if they passed in * or didn't specify any includes, return everything
785
+		if (! in_array('*', $includes_for_this_model)
786
+			&& ! empty($includes_for_this_model)
787
+		) {
788
+			if ($model->has_primary_key_field()) {
789
+				//always include the primary key. ya just gotta know that at least
790
+				$includes_for_this_model[] = $model->primary_key_name();
791
+			}
792
+			if ($this->explode_and_get_items_prefixed_with($rest_request->get_param('calculate'), '')) {
793
+				$includes_for_this_model[] = '_calculated_fields';
794
+			}
795
+			$entity_array = array_intersect_key($entity_array, array_flip($includes_for_this_model));
796
+		}
797
+		$relation_settings = $this->get_model_version_info()->relation_settings($model);
798
+		foreach ($relation_settings as $relation_name => $relation_obj) {
799
+			$related_fields_to_include = $this->explode_and_get_items_prefixed_with(
800
+				$rest_request->get_param('include'),
801
+				$relation_name
802
+			);
803
+			$related_fields_to_calculate = $this->explode_and_get_items_prefixed_with(
804
+				$rest_request->get_param('calculate'),
805
+				$relation_name
806
+			);
807
+			//did they specify they wanted to include a related model, or
808
+			//specific fields from a related model?
809
+			//or did they specify to calculate a field from a related model?
810
+			if ($related_fields_to_include || $related_fields_to_calculate) {
811
+				//if so, we should include at least some part of the related model
812
+				$pretend_related_request = new \WP_REST_Request();
813
+				$pretend_related_request->set_query_params(
814
+					array(
815
+						'caps'      => $rest_request->get_param('caps'),
816
+						'include'   => $related_fields_to_include,
817
+						'calculate' => $related_fields_to_calculate,
818
+					)
819
+				);
820
+				$pretend_related_request->add_header('no_rest_headers', true);
821
+				$primary_model_query_params = $model->alter_query_params_to_restrict_by_ID(
822
+					$model->get_index_primary_key_string(
823
+						$model->deduce_fields_n_values_from_cols_n_values($db_row)
824
+					)
825
+				);
826
+				$related_results = $this->_get_entities_from_relation(
827
+					$primary_model_query_params,
828
+					$relation_obj,
829
+					$pretend_related_request
830
+				);
831
+				$entity_array[Read::get_related_entity_name($relation_name, $relation_obj)] = $related_results
832
+																							  instanceof
833
+																							  \WP_Error
834
+					? null
835
+					: $related_results;
836
+			}
837
+		}
838
+		return $entity_array;
839
+	}
840
+
841
+
842
+
843
+	/**
844
+	 * Returns a new array with all the names of models removed. Eg
845
+	 * array( 'Event', 'Datetime.*', 'foobar' ) would become array( 'Datetime.*', 'foobar' )
846
+	 *
847
+	 * @param array $arr
848
+	 * @return array
849
+	 */
850
+	private function _remove_model_names_from_array($arr)
851
+	{
852
+		return array_diff($arr, array_keys(\EE_Registry::instance()->non_abstract_db_models));
853
+	}
854
+
855
+
856
+
857
+	/**
858
+	 * Gets the calculated fields for the response
859
+	 *
860
+	 * @param \EEM_Base        $model
861
+	 * @param array            $wpdb_row
862
+	 * @param \WP_REST_Request $rest_request
863
+	 * @return \stdClass the _calculations item in the entity
864
+	 */
865
+	protected function _get_entity_calculations($model, $wpdb_row, $rest_request)
866
+	{
867
+		$calculated_fields = $this->explode_and_get_items_prefixed_with(
868
+			$rest_request->get_param('calculate'),
869
+			''
870
+		);
871
+		//note: setting calculate=* doesn't do anything
872
+		$calculated_fields_to_return = new \stdClass();
873
+		foreach ($calculated_fields as $field_to_calculate) {
874
+			try {
875
+				$calculated_fields_to_return->$field_to_calculate = Model_Data_Translator::prepare_field_value_for_json(
876
+					null,
877
+					$this->_fields_calculator->retrieve_calculated_field_value(
878
+						$model,
879
+						$field_to_calculate,
880
+						$wpdb_row,
881
+						$rest_request,
882
+						$this
883
+					),
884
+					$this->get_model_version_info()->requested_version()
885
+				);
886
+			} catch (Rest_Exception $e) {
887
+				//if we don't have permission to read it, just leave it out. but let devs know about the problem
888
+				$this->_set_response_header(
889
+					'Notices-Field-Calculation-Errors['
890
+					. $e->get_string_code()
891
+					. ']['
892
+					. $model->get_this_model_name()
893
+					. ']['
894
+					. $field_to_calculate
895
+					. ']',
896
+					$e->getMessage(),
897
+					true
898
+				);
899
+			}
900
+		}
901
+		return $calculated_fields_to_return;
902
+	}
903
+
904
+
905
+
906
+	/**
907
+	 * Gets the full URL to the resource, taking the requested version into account
908
+	 *
909
+	 * @param string $link_part_after_version_and_slash eg "events/10/datetimes"
910
+	 * @return string url eg "http://mysite.com/wp-json/ee/v4.6/events/10/datetimes"
911
+	 */
912
+	public function get_versioned_link_to($link_part_after_version_and_slash)
913
+	{
914
+		return rest_url(
915
+			\EED_Core_Rest_Api::ee_api_namespace
916
+			. $this->get_model_version_info()->requested_version()
917
+			. '/'
918
+			. $link_part_after_version_and_slash
919
+		);
920
+	}
921
+
922
+
923
+
924
+	/**
925
+	 * Gets the correct lowercase name for the relation in the API according
926
+	 * to the relation's type
927
+	 *
928
+	 * @param string                  $relation_name
929
+	 * @param \EE_Model_Relation_Base $relation_obj
930
+	 * @return string
931
+	 */
932
+	public static function get_related_entity_name($relation_name, $relation_obj)
933
+	{
934
+		if ($relation_obj instanceof \EE_Belongs_To_Relation) {
935
+			return strtolower($relation_name);
936
+		} else {
937
+			return \EEH_Inflector::pluralize_and_lower($relation_name);
938
+		}
939
+	}
940
+
941
+
942
+
943
+	/**
944
+	 * Gets the one model object with the specified id for the specified model
945
+	 *
946
+	 * @param \EEM_Base        $model
947
+	 * @param \WP_REST_Request $request
948
+	 * @return array|\WP_Error
949
+	 */
950
+	public function get_entity_from_model($model, $request)
951
+	{
952
+		$query_params = array(array($model->primary_key_name() => $request->get_param('id')), 'limit' => 1);
953
+		if ($model instanceof \EEM_Soft_Delete_Base) {
954
+			$query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($query_params);
955
+		}
956
+		$restricted_query_params = $query_params;
957
+		$restricted_query_params['caps'] = $this->validate_context($request->get_param('caps'));
958
+		$this->_set_debug_info('model query params', $restricted_query_params);
959
+		$model_rows = $model->get_all_wpdb_results($restricted_query_params);
960
+		if (! empty ($model_rows)) {
961
+			return $this->create_entity_from_wpdb_result(
962
+				$model,
963
+				array_shift($model_rows),
964
+				$request);
965
+		} else {
966
+			//ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
967
+			$lowercase_model_name = strtolower($model->get_this_model_name());
968
+			$model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
969
+			if (! empty($model_rows_found_sans_restrictions)) {
970
+				//you got shafted- it existed but we didn't want to tell you!
971
+				return new \WP_Error(
972
+					'rest_user_cannot_read',
973
+					sprintf(
974
+						__('Sorry, you cannot read this %1$s. Missing permissions are: %2$s', 'event_espresso'),
975
+						strtolower($model->get_this_model_name()),
976
+						Capabilities::get_missing_permissions_string(
977
+							$model,
978
+							$this->validate_context($request->get_param('caps')))
979
+					),
980
+					array('status' => 403)
981
+				);
982
+			} else {
983
+				//it's not you. It just doesn't exist
984
+				return new \WP_Error(
985
+					sprintf('rest_%s_invalid_id', $lowercase_model_name),
986
+					sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
987
+					array('status' => 404)
988
+				);
989
+			}
990
+		}
991
+	}
992
+
993
+
994
+
995
+	/**
996
+	 * If a context is provided which isn't valid, maybe it was added in a future
997
+	 * version so just treat it as a default read
998
+	 *
999
+	 * @param string $context
1000
+	 * @return string array key of EEM_Base::cap_contexts_to_cap_action_map()
1001
+	 */
1002
+	public function validate_context($context)
1003
+	{
1004
+		if (! $context) {
1005
+			$context = \EEM_Base::caps_read;
1006
+		}
1007
+		$valid_contexts = \EEM_Base::valid_cap_contexts();
1008
+		if (in_array($context, $valid_contexts)) {
1009
+			return $context;
1010
+		} else {
1011
+			return \EEM_Base::caps_read;
1012
+		}
1013
+	}
1014
+
1015
+
1016
+
1017
+	/**
1018
+	 * Verifies the passed in value is an allowable default where conditions value.
1019
+	 *
1020
+	 * @param $default_query_params
1021
+	 * @return string
1022
+	 */
1023
+	public function validate_default_query_params($default_query_params)
1024
+	{
1025
+		$valid_default_where_conditions_for_api_calls = array(
1026
+			\EEM_Base::default_where_conditions_all,
1027
+			\EEM_Base::default_where_conditions_minimum_all,
1028
+			\EEM_Base::default_where_conditions_minimum_others,
1029
+		);
1030
+		if (! $default_query_params) {
1031
+			$default_query_params = \EEM_Base::default_where_conditions_all;
1032
+		}
1033
+		if (
1034
+		in_array(
1035
+			$default_query_params,
1036
+			$valid_default_where_conditions_for_api_calls,
1037
+			true
1038
+		)
1039
+		) {
1040
+			return $default_query_params;
1041
+		} else {
1042
+			return \EEM_Base::default_where_conditions_all;
1043
+		}
1044
+	}
1045
+
1046
+
1047
+
1048
+	/**
1049
+	 * Translates API filter get parameter into $query_params array used by EEM_Base::get_all().
1050
+	 * Note: right now the query parameter keys for fields (and related fields)
1051
+	 * can be left as-is, but it's quite possible this will change someday.
1052
+	 * Also, this method's contents might be candidate for moving to Model_Data_Translator
1053
+	 *
1054
+	 * @param \EEM_Base $model
1055
+	 * @param array     $query_parameters from $_GET parameter @see Read:handle_request_get_all
1056
+	 * @return array like what EEM_Base::get_all() expects or FALSE to indicate
1057
+	 *                                    that absolutely no results should be returned
1058
+	 * @throws \EE_Error
1059
+	 */
1060
+	public function create_model_query_params($model, $query_parameters)
1061
+	{
1062
+		$model_query_params = array();
1063
+		if (isset($query_parameters['where'])) {
1064
+			$model_query_params[0] = Model_Data_Translator::prepare_conditions_query_params_for_models(
1065
+				$query_parameters['where'],
1066
+				$model,
1067
+				$this->get_model_version_info()->requested_version()
1068
+			);
1069
+		}
1070
+		if (isset($query_parameters['order_by'])) {
1071
+			$order_by = $query_parameters['order_by'];
1072
+		} elseif (isset($query_parameters['orderby'])) {
1073
+			$order_by = $query_parameters['orderby'];
1074
+		} else {
1075
+			$order_by = null;
1076
+		}
1077
+		if ($order_by !== null) {
1078
+			if (is_array($order_by)) {
1079
+				$order_by = Model_Data_Translator::prepare_field_names_in_array_keys_from_json($order_by);
1080
+			} else {
1081
+				//it's a single item
1082
+				$order_by = Model_Data_Translator::prepare_field_name_from_json($order_by);
1083
+			}
1084
+			$model_query_params['order_by'] = $order_by;
1085
+		}
1086
+		if (isset($query_parameters['group_by'])) {
1087
+			$group_by = $query_parameters['group_by'];
1088
+		} elseif (isset($query_parameters['groupby'])) {
1089
+			$group_by = $query_parameters['groupby'];
1090
+		} else {
1091
+			$group_by = array_keys($model->get_combined_primary_key_fields());
1092
+		}
1093
+		//make sure they're all real names
1094
+		if (is_array($group_by)) {
1095
+			$group_by = Model_Data_Translator::prepare_field_names_from_json($group_by);
1096
+		}
1097
+		if ($group_by !== null) {
1098
+			$model_query_params['group_by'] = $group_by;
1099
+		}
1100
+		if (isset($query_parameters['having'])) {
1101
+			$model_query_params['having'] = Model_Data_Translator::prepare_conditions_query_params_for_models(
1102
+				$query_parameters['having'],
1103
+				$model,
1104
+				$this->get_model_version_info()->requested_version()
1105
+			);
1106
+		}
1107
+		if (isset($query_parameters['order'])) {
1108
+			$model_query_params['order'] = $query_parameters['order'];
1109
+		}
1110
+		if (isset($query_parameters['mine'])) {
1111
+			$model_query_params = $model->alter_query_params_to_only_include_mine($model_query_params);
1112
+		}
1113
+		if (isset($query_parameters['limit'])) {
1114
+			//limit should be either a string like '23' or '23,43', or an array with two items in it
1115
+			if (! is_array($query_parameters['limit'])) {
1116
+				$limit_array = explode(',', (string)$query_parameters['limit']);
1117
+			} else {
1118
+				$limit_array = $query_parameters['limit'];
1119
+			}
1120
+			$sanitized_limit = array();
1121
+			foreach ($limit_array as $key => $limit_part) {
1122
+				if ($this->_debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1123
+					throw new \EE_Error(
1124
+						sprintf(
1125
+							__('An invalid limit filter was provided. It was: %s. If the EE4 JSON REST API weren\'t in debug mode, this message would not appear.',
1126
+								'event_espresso'),
1127
+							wp_json_encode($query_parameters['limit'])
1128
+						)
1129
+					);
1130
+				}
1131
+				$sanitized_limit[] = (int)$limit_part;
1132
+			}
1133
+			$model_query_params['limit'] = implode(',', $sanitized_limit);
1134
+		} else {
1135
+			$model_query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
1136
+		}
1137
+		if (isset($query_parameters['caps'])) {
1138
+			$model_query_params['caps'] = $this->validate_context($query_parameters['caps']);
1139
+		} else {
1140
+			$model_query_params['caps'] = \EEM_Base::caps_read;
1141
+		}
1142
+		if (isset($query_parameters['default_where_conditions'])) {
1143
+			$model_query_params['default_where_conditions'] = $this->validate_default_query_params($query_parameters['default_where_conditions']);
1144
+		}
1145
+		return apply_filters('FHEE__Read__create_model_query_params', $model_query_params, $query_parameters, $model);
1146
+	}
1147
+
1148
+
1149
+
1150
+	/**
1151
+	 * Changes the REST-style query params for use in the models
1152
+	 *
1153
+	 * @deprecated
1154
+	 * @param \EEM_Base $model
1155
+	 * @param array     $query_params sub-array from @see EEM_Base::get_all()
1156
+	 * @return array
1157
+	 */
1158
+	public function prepare_rest_query_params_key_for_models($model, $query_params)
1159
+	{
1160
+		$model_ready_query_params = array();
1161
+		foreach ($query_params as $key => $value) {
1162
+			if (is_array($value)) {
1163
+				$model_ready_query_params[$key] = $this->prepare_rest_query_params_key_for_models($model, $value);
1164
+			} else {
1165
+				$model_ready_query_params[$key] = $value;
1166
+			}
1167
+		}
1168
+		return $model_ready_query_params;
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * @deprecated
1175
+	 * @param $model
1176
+	 * @param $query_params
1177
+	 * @return array
1178
+	 */
1179
+	public function prepare_rest_query_params_values_for_models($model, $query_params)
1180
+	{
1181
+		$model_ready_query_params = array();
1182
+		foreach ($query_params as $key => $value) {
1183
+			if (is_array($value)) {
1184
+				$model_ready_query_params[$key] = $this->prepare_rest_query_params_values_for_models($model, $value);
1185
+			} else {
1186
+				$model_ready_query_params[$key] = $value;
1187
+			}
1188
+		}
1189
+		return $model_ready_query_params;
1190
+	}
1191
+
1192
+
1193
+
1194
+	/**
1195
+	 * Explodes the string on commas, and only returns items with $prefix followed by a period.
1196
+	 * If no prefix is specified, returns items with no period.
1197
+	 *
1198
+	 * @param string|array $string_to_explode eg "jibba,jabba, blah, blaabla" or array('jibba', 'jabba' )
1199
+	 * @param string       $prefix            "Event" or "foobar"
1200
+	 * @return array $string_to_exploded exploded on COMMAS, and if a prefix was specified
1201
+	 *                                        we only return strings starting with that and a period; if no prefix was
1202
+	 *                                        specified we return all items containing NO periods
1203
+	 */
1204
+	public function explode_and_get_items_prefixed_with($string_to_explode, $prefix)
1205
+	{
1206
+		if (is_string($string_to_explode)) {
1207
+			$exploded_contents = explode(',', $string_to_explode);
1208
+		} else if (is_array($string_to_explode)) {
1209
+			$exploded_contents = $string_to_explode;
1210
+		} else {
1211
+			$exploded_contents = array();
1212
+		}
1213
+		//if the string was empty, we want an empty array
1214
+		$exploded_contents = array_filter($exploded_contents);
1215
+		$contents_with_prefix = array();
1216
+		foreach ($exploded_contents as $item) {
1217
+			$item = trim($item);
1218
+			//if no prefix was provided, so we look for items with no "." in them
1219
+			if (! $prefix) {
1220
+				//does this item have a period?
1221
+				if (strpos($item, '.') === false) {
1222
+					//if not, then its what we're looking for
1223
+					$contents_with_prefix[] = $item;
1224
+				}
1225
+			} else if (strpos($item, $prefix . '.') === 0) {
1226
+				//this item has the prefix and a period, grab it
1227
+				$contents_with_prefix[] = substr(
1228
+					$item,
1229
+					strpos($item, $prefix . '.') + strlen($prefix . '.')
1230
+				);
1231
+			} else if ($item === $prefix) {
1232
+				//this item is JUST the prefix
1233
+				//so let's grab everything after, which is a blank string
1234
+				$contents_with_prefix[] = '';
1235
+			}
1236
+		}
1237
+		return $contents_with_prefix;
1238
+	}
1239
+
1240
+
1241
+
1242
+	/**
1243
+	 * @deprecated since 4.8.36.rc.001 You should instead use Read::explode_and_get_items_prefixed_with.
1244
+	 * Deprecated because its return values were really quite confusing- sometimes it returned
1245
+	 * an empty array (when the include string was blank or '*') or sometimes it returned
1246
+	 * array('*') (when you provided a model and a model of that kind was found).
1247
+	 * Parses the $include_string so we fetch all the field names relating to THIS model
1248
+	 * (ie have NO period in them), or for the provided model (ie start with the model
1249
+	 * name and then a period).
1250
+	 * @param string $include_string @see Read:handle_request_get_all
1251
+	 * @param string $model_name
1252
+	 * @return array of fields for this model. If $model_name is provided, then
1253
+	 *                               the fields for that model, with the model's name removed from each.
1254
+	 *                               If $include_string was blank or '*' returns an empty array
1255
+	 */
1256
+	public function extract_includes_for_this_model($include_string, $model_name = null)
1257
+	{
1258
+		if (is_array($include_string)) {
1259
+			$include_string = implode(',', $include_string);
1260
+		}
1261
+		if ($include_string === '*' || $include_string === '') {
1262
+			return array();
1263
+		}
1264
+		$includes = explode(',', $include_string);
1265
+		$extracted_fields_to_include = array();
1266
+		if ($model_name) {
1267
+			foreach ($includes as $field_to_include) {
1268
+				$field_to_include = trim($field_to_include);
1269
+				if (strpos($field_to_include, $model_name . '.') === 0) {
1270
+					//found the model name at the exact start
1271
+					$field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1272
+					$extracted_fields_to_include[] = $field_sans_model_name;
1273
+				} elseif ($field_to_include == $model_name) {
1274
+					$extracted_fields_to_include[] = '*';
1275
+				}
1276
+			}
1277
+		} else {
1278
+			//look for ones with no period
1279
+			foreach ($includes as $field_to_include) {
1280
+				$field_to_include = trim($field_to_include);
1281
+				if (
1282
+					strpos($field_to_include, '.') === false
1283
+					&& ! $this->get_model_version_info()->is_model_name_in_this_version($field_to_include)
1284
+				) {
1285
+					$extracted_fields_to_include[] = $field_to_include;
1286
+				}
1287
+			}
1288
+		}
1289
+		return $extracted_fields_to_include;
1290
+	}
1291 1291
 }
1292 1292
 
1293 1293
 
Please login to merge, or discard this patch.
Spacing   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@  discard block
 block discarded – undo
8 8
 use EventEspresso\core\entities\models\JsonModelSchema;
9 9
 use EE_Datetime_Field;
10 10
 
11
-if (! defined('EVENT_ESPRESSO_VERSION')) {
11
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
12 12
     exit('No direct script access allowed');
13 13
 }
14 14
 
@@ -57,12 +57,12 @@  discard block
 block discarded – undo
57 57
         try {
58 58
             $matches = $controller->parse_route(
59 59
                 $request->get_route(),
60
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)~',
60
+                '~'.\EED_Core_Rest_Api::ee_api_namespace_for_regex.'(.*)~',
61 61
                 array('version', 'model')
62 62
             );
63 63
             $controller->set_requested_version($matches['version']);
64 64
             $model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
65
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
65
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
66 66
                 return $controller->send_response(
67 67
                     new \WP_Error(
68 68
                         'endpoint_parsing_error',
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
         $controller = new Read();
100 100
         try {
101 101
             $controller->set_requested_version($version);
102
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name)) {
102
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($model_name)) {
103 103
                 return array();
104 104
             }
105 105
             //get the model for this version
@@ -193,9 +193,9 @@  discard block
 block discarded – undo
193 193
     protected function _maybe_add_extra_fields_to_schema($field_name, \EE_Model_Field_Base $field, array $schema)
194 194
     {
195 195
         if ($field instanceof EE_Datetime_Field) {
196
-            $schema['properties'][$field_name . '_gmt'] = $field->getSchema();
196
+            $schema['properties'][$field_name.'_gmt'] = $field->getSchema();
197 197
             //modify the description
198
-            $schema['properties'][$field_name . '_gmt']['description'] = sprintf(
198
+            $schema['properties'][$field_name.'_gmt']['description'] = sprintf(
199 199
                 esc_html__('%s - the value for this field is in GMT.', 'event_espresso'),
200 200
                 $field->get_nicename()
201 201
             );
@@ -236,11 +236,11 @@  discard block
 block discarded – undo
236 236
         try {
237 237
             $matches = $controller->parse_route(
238 238
                 $request->get_route(),
239
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)~',
239
+                '~'.\EED_Core_Rest_Api::ee_api_namespace_for_regex.'(.*)/(.*)~',
240 240
                 array('version', 'model', 'id'));
241 241
             $controller->set_requested_version($matches['version']);
242 242
             $model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
243
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
243
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
244 244
                 return $controller->send_response(
245 245
                     new \WP_Error(
246 246
                         'endpoint_parsing_error',
@@ -278,12 +278,12 @@  discard block
 block discarded – undo
278 278
         try {
279 279
             $matches = $controller->parse_route(
280 280
                 $request->get_route(),
281
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)/(.*)~',
281
+                '~'.\EED_Core_Rest_Api::ee_api_namespace_for_regex.'(.*)/(.*)/(.*)~',
282 282
                 array('version', 'model', 'id', 'related_model')
283 283
             );
284 284
             $controller->set_requested_version($matches['version']);
285 285
             $main_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
286
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($main_model_name_singular)) {
286
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($main_model_name_singular)) {
287 287
                 return $controller->send_response(
288 288
                     new \WP_Error(
289 289
                         'endpoint_parsing_error',
@@ -298,11 +298,11 @@  discard block
 block discarded – undo
298 298
             $main_model = $controller->get_model_version_info()->load_model($main_model_name_singular);
299 299
             //assume the related model name is plural and try to find the model's name
300 300
             $related_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['related_model']);
301
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
301
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
302 302
                 //so the word didn't singularize well. Maybe that's just because it's a singular word?
303 303
                 $related_model_name_singular = \EEH_Inflector::humanize($matches['related_model']);
304 304
             }
305
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
305
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
306 306
                 return $controller->send_response(
307 307
                     new \WP_Error(
308 308
                         'endpoint_parsing_error',
@@ -338,7 +338,7 @@  discard block
 block discarded – undo
338 338
     public function get_entities_from_model($model, $request)
339 339
     {
340 340
         $query_params = $this->create_model_query_params($model, $request->get_params());
341
-        if (! Capabilities::current_user_has_partial_access_to($model, $query_params['caps'])) {
341
+        if ( ! Capabilities::current_user_has_partial_access_to($model, $query_params['caps'])) {
342 342
             $model_name_plural = \EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
343 343
             return new \WP_Error(
344 344
                 sprintf('rest_%s_cannot_list', $model_name_plural),
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
                 array('status' => 403)
351 351
             );
352 352
         }
353
-        if (! $request->get_header('no_rest_headers')) {
353
+        if ( ! $request->get_header('no_rest_headers')) {
354 354
             $this->_set_headers_from_query_params($model, $query_params);
355 355
         }
356 356
         /** @type array $results */
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
         $context = $this->validate_context($request->get_param('caps'));
381 381
         $model = $relation->get_this_model();
382 382
         $related_model = $relation->get_other_model();
383
-        if (! isset($primary_model_query_params[0])) {
383
+        if ( ! isset($primary_model_query_params[0])) {
384 384
             $primary_model_query_params[0] = array();
385 385
         }
386 386
         //check if they can access the 1st model object
@@ -431,7 +431,7 @@  discard block
 block discarded – undo
431 431
         }
432 432
         $query_params['default_where_conditions'] = 'none';
433 433
         $query_params['caps'] = $context;
434
-        if (! $request->get_header('no_rest_headers')) {
434
+        if ( ! $request->get_header('no_rest_headers')) {
435 435
             $this->_set_headers_from_query_params($relation->get_other_model(), $query_params);
436 436
         }
437 437
         /** @type array $results */
@@ -483,7 +483,7 @@  discard block
 block discarded – undo
483 483
      */
484 484
     public function get_entities_from_relation($id, $relation, $request)
485 485
     {
486
-        if (! $relation->get_this_model()->has_primary_key_field()) {
486
+        if ( ! $relation->get_this_model()->has_primary_key_field()) {
487 487
             throw new \EE_Error(
488 488
                 sprintf(
489 489
                     __('Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
@@ -520,7 +520,7 @@  discard block
 block discarded – undo
520 520
         $this->_set_debug_info('missing caps',
521 521
             Capabilities::get_missing_permissions_string($model, $query_params['caps']));
522 522
         //normally the limit to a 2-part array, where the 2nd item is the limit
523
-        if (! isset($query_params['limit'])) {
523
+        if ( ! isset($query_params['limit'])) {
524 524
             $query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
525 525
         }
526 526
         if (is_array($query_params['limit'])) {
@@ -554,7 +554,7 @@  discard block
 block discarded – undo
554 554
      */
555 555
     public function create_entity_from_wpdb_result($model, $db_row, $rest_request, $deprecated = null)
556 556
     {
557
-        if (! $rest_request instanceof \WP_REST_Request) {
557
+        if ( ! $rest_request instanceof \WP_REST_Request) {
558 558
             //ok so this was called in the old style, where the 3rd arg was
559 559
             //$include, and the 4th arg was $context
560 560
             //now setup the request just to avoid fatal errors, although we won't be able
@@ -629,7 +629,7 @@  discard block
 block discarded – undo
629 629
             global $post;
630 630
             $old_post = $post;
631 631
             $post = get_post($result[$model->primary_key_name()]);
632
-            $model_object_classname = 'EE_' . $model->get_this_model_name();
632
+            $model_object_classname = 'EE_'.$model->get_this_model_name();
633 633
             $post->{$model_object_classname} = \EE_Registry::instance()->load_class(
634 634
                 $model_object_classname,
635 635
                 $result,
@@ -660,7 +660,7 @@  discard block
 block discarded – undo
660 660
                 if ($field_value instanceof \DateTime) {
661 661
                     $timezone = $field_value->getTimezone();
662 662
                     $field_value->setTimezone(new \DateTimeZone('UTC'));
663
-                    $result[$field_name . '_gmt'] = Model_Data_Translator::prepare_field_value_for_json(
663
+                    $result[$field_name.'_gmt'] = Model_Data_Translator::prepare_field_value_for_json(
664 664
                         $field_obj,
665 665
                         $field_value,
666 666
                         $this->get_model_version_info()->requested_version()
@@ -741,7 +741,7 @@  discard block
 block discarded – undo
741 741
         if ($model->has_primary_key_field()) {
742 742
             foreach ($this->get_model_version_info()->relation_settings($model) as $relation_name => $relation_obj) {
743 743
                 $related_model_part = Read::get_related_entity_name($relation_name, $relation_obj);
744
-                $links[\EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
744
+                $links[\EED_Core_Rest_Api::ee_api_link_namespace.$related_model_part] = array(
745 745
                     array(
746 746
                         'href'   => $this->get_versioned_link_to(
747 747
                             \EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
@@ -776,13 +776,13 @@  discard block
 block discarded – undo
776 776
         $db_row = array()
777 777
     ) {
778 778
         //if $db_row not included, hope the entity array has what we need
779
-        if (! $db_row) {
779
+        if ( ! $db_row) {
780 780
             $db_row = $entity_array;
781 781
         }
782 782
         $includes_for_this_model = $this->explode_and_get_items_prefixed_with($rest_request->get_param('include'), '');
783 783
         $includes_for_this_model = $this->_remove_model_names_from_array($includes_for_this_model);
784 784
         //if they passed in * or didn't specify any includes, return everything
785
-        if (! in_array('*', $includes_for_this_model)
785
+        if ( ! in_array('*', $includes_for_this_model)
786 786
             && ! empty($includes_for_this_model)
787 787
         ) {
788 788
             if ($model->has_primary_key_field()) {
@@ -957,7 +957,7 @@  discard block
 block discarded – undo
957 957
         $restricted_query_params['caps'] = $this->validate_context($request->get_param('caps'));
958 958
         $this->_set_debug_info('model query params', $restricted_query_params);
959 959
         $model_rows = $model->get_all_wpdb_results($restricted_query_params);
960
-        if (! empty ($model_rows)) {
960
+        if ( ! empty ($model_rows)) {
961 961
             return $this->create_entity_from_wpdb_result(
962 962
                 $model,
963 963
                 array_shift($model_rows),
@@ -966,7 +966,7 @@  discard block
 block discarded – undo
966 966
             //ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
967 967
             $lowercase_model_name = strtolower($model->get_this_model_name());
968 968
             $model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
969
-            if (! empty($model_rows_found_sans_restrictions)) {
969
+            if ( ! empty($model_rows_found_sans_restrictions)) {
970 970
                 //you got shafted- it existed but we didn't want to tell you!
971 971
                 return new \WP_Error(
972 972
                     'rest_user_cannot_read',
@@ -1001,7 +1001,7 @@  discard block
 block discarded – undo
1001 1001
      */
1002 1002
     public function validate_context($context)
1003 1003
     {
1004
-        if (! $context) {
1004
+        if ( ! $context) {
1005 1005
             $context = \EEM_Base::caps_read;
1006 1006
         }
1007 1007
         $valid_contexts = \EEM_Base::valid_cap_contexts();
@@ -1027,7 +1027,7 @@  discard block
 block discarded – undo
1027 1027
             \EEM_Base::default_where_conditions_minimum_all,
1028 1028
             \EEM_Base::default_where_conditions_minimum_others,
1029 1029
         );
1030
-        if (! $default_query_params) {
1030
+        if ( ! $default_query_params) {
1031 1031
             $default_query_params = \EEM_Base::default_where_conditions_all;
1032 1032
         }
1033 1033
         if (
@@ -1112,14 +1112,14 @@  discard block
 block discarded – undo
1112 1112
         }
1113 1113
         if (isset($query_parameters['limit'])) {
1114 1114
             //limit should be either a string like '23' or '23,43', or an array with two items in it
1115
-            if (! is_array($query_parameters['limit'])) {
1116
-                $limit_array = explode(',', (string)$query_parameters['limit']);
1115
+            if ( ! is_array($query_parameters['limit'])) {
1116
+                $limit_array = explode(',', (string) $query_parameters['limit']);
1117 1117
             } else {
1118 1118
                 $limit_array = $query_parameters['limit'];
1119 1119
             }
1120 1120
             $sanitized_limit = array();
1121 1121
             foreach ($limit_array as $key => $limit_part) {
1122
-                if ($this->_debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1122
+                if ($this->_debug_mode && ( ! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1123 1123
                     throw new \EE_Error(
1124 1124
                         sprintf(
1125 1125
                             __('An invalid limit filter was provided. It was: %s. If the EE4 JSON REST API weren\'t in debug mode, this message would not appear.',
@@ -1128,7 +1128,7 @@  discard block
 block discarded – undo
1128 1128
                         )
1129 1129
                     );
1130 1130
                 }
1131
-                $sanitized_limit[] = (int)$limit_part;
1131
+                $sanitized_limit[] = (int) $limit_part;
1132 1132
             }
1133 1133
             $model_query_params['limit'] = implode(',', $sanitized_limit);
1134 1134
         } else {
@@ -1216,17 +1216,17 @@  discard block
 block discarded – undo
1216 1216
         foreach ($exploded_contents as $item) {
1217 1217
             $item = trim($item);
1218 1218
             //if no prefix was provided, so we look for items with no "." in them
1219
-            if (! $prefix) {
1219
+            if ( ! $prefix) {
1220 1220
                 //does this item have a period?
1221 1221
                 if (strpos($item, '.') === false) {
1222 1222
                     //if not, then its what we're looking for
1223 1223
                     $contents_with_prefix[] = $item;
1224 1224
                 }
1225
-            } else if (strpos($item, $prefix . '.') === 0) {
1225
+            } else if (strpos($item, $prefix.'.') === 0) {
1226 1226
                 //this item has the prefix and a period, grab it
1227 1227
                 $contents_with_prefix[] = substr(
1228 1228
                     $item,
1229
-                    strpos($item, $prefix . '.') + strlen($prefix . '.')
1229
+                    strpos($item, $prefix.'.') + strlen($prefix.'.')
1230 1230
                 );
1231 1231
             } else if ($item === $prefix) {
1232 1232
                 //this item is JUST the prefix
@@ -1266,9 +1266,9 @@  discard block
 block discarded – undo
1266 1266
         if ($model_name) {
1267 1267
             foreach ($includes as $field_to_include) {
1268 1268
                 $field_to_include = trim($field_to_include);
1269
-                if (strpos($field_to_include, $model_name . '.') === 0) {
1269
+                if (strpos($field_to_include, $model_name.'.') === 0) {
1270 1270
                     //found the model name at the exact start
1271
-                    $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1271
+                    $field_sans_model_name = str_replace($model_name.'.', '', $field_to_include);
1272 1272
                     $extracted_fields_to_include[] = $field_sans_model_name;
1273 1273
                 } elseif ($field_to_include == $model_name) {
1274 1274
                     $extracted_fields_to_include[] = '*';
Please login to merge, or discard this patch.