Completed
Branch BUG-9625-better-us-phone-valid... (e0ce21)
by
unknown
1074:20 queued 1061:19
created

EEM_Base   F

Complexity

Total Complexity 605

Size/Duplication

Total Lines 4533
Duplicated Lines 5.29 %

Coupling/Cohesion

Components 4
Dependencies 29

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 605
lcom 4
cbo 29
dl 240
loc 4533
rs 0.5217
c 1
b 0
f 1

154 Methods

Rating   Name   Duplication   Size   Complexity  
A get_all() 0 7 3
F __construct() 9 126 22
A _generate_cap_restrictions() 0 8 3
A instance() 14 14 2
A reset() 0 8 2
A status_array() 0 12 4
A alter_query_params_to_only_include_mine() 0 7 2
A wp_user_field_name() 0 17 3
A model_chain_to_wp_user() 0 3 1
A is_owned() 0 12 3
A _get_all_wpdb_results() 0 17 4
A get_all_wpdb_results() 0 3 1
B _construct_select_from_input() 0 40 6
A primary_key_name() 0 3 1
A get_one_by_ID() 0 11 2
A alter_query_params_to_restrict_by_ID() 0 12 3
A get_one() 13 13 3
A next_x() 0 3 1
A previous_x() 0 3 1
A next() 0 4 2
A previous() 0 4 2
C _get_consecutive() 0 36 8
B set_timezone() 0 15 5
B get_timezone() 0 18 5
A get_formats_for() 0 14 2
B current_time_for_query() 0 22 4
A convert_datetime_for_query() 0 13 2
A get_tables() 0 3 1
D update() 0 124 18
A get_col() 0 18 3
A get_var() 0 9 2
A _construct_update_sql() 0 15 3
A delete_permanently_by_ID() 0 8 1
A delete_by_ID() 0 8 1
A delete() 0 3 1
B delete_permanently() 0 51 6
C delete_is_blocked_by_related_models() 0 29 8
C _setup_ids_for_delete() 6 61 16
A count() 0 16 4
A sum() 0 19 4
C _do_wpdb_query() 3 30 8
C _process_wpdb_query() 0 37 8
A _verify_core_db() 14 14 1
A _verify_addons_db() 14 14 1
A _construct_2nd_half_of_select_query() 0 8 1
A show_next_x_db_queries() 0 3 1
A show_db_query_if_previously_requested() 0 6 2
A add_relationship_to() 0 4 1
A remove_relationship_to() 0 4 1
A remove_relations() 0 4 1
A get_all_related() 0 5 1
A delete_related() 0 5 1
A delete_related_permanently() 0 5 1
A count_related() 0 12 2
A sum_related() 0 16 3
A get_first_related() 0 10 2
A get_this_model_name() 0 3 1
B get_field_containing_related_model_name() 3 11 5
B insert() 0 28 4
A _satisfies_unique_indexes() 0 10 3
D get_one_conflicting() 7 25 9
A exists() 0 4 1
A exists_by_ID() 0 3 1
D _insert_into_specific_table() 0 44 9
B _prepare_value_or_use_default() 0 10 5
B _prepare_value_for_use_in_db() 0 17 6
A _get_main_table() 0 8 3
A table() 0 3 1
A second_table() 0 5 2
A get_table_obj_by_alias() 0 3 2
A _get_other_tables() 0 9 3
A _get_fields_for_table() 0 3 1
D _extract_related_models_from_query() 13 26 10
C _extract_related_models_from_sub_params_array_keys() 3 35 11
A _extract_related_models_from_sub_params_array_values() 0 12 4
F _create_model_query_info_carrier() 11 125 34
A caps_where_conditions() 0 12 2
A _extract_order() 7 7 2
B _get_default_where_conditions_for_models_in_query() 3 35 6
B _override_defaults_or_make_null_friendly() 0 21 6
A _get_default_where_conditions() 0 6 2
A _get_minimum_where_conditions() 0 6 2
A _construct_default_select_sql() 0 8 2
B _get_columns_to_select_for_this_model() 0 19 5
C _extract_related_model_info_from_query_param() 0 72 11
A _add_join_to_model() 0 21 2
A _construct_where_clause() 0 8 2
A _construct_having_clause() 0 9 2
A _get_field_on_model() 0 13 2
C _construct_condition_clause_recursive() 0 41 12
A _deduce_column_name_from_query_param() 0 14 3
A _remove_stars_and_anything_after_from_condition_query_param_key() 9 9 2
C _construct_op_and_value() 9 50 24
A _construct_between_value() 0 7 2
A _construct_in_value() 0 21 4
A _wpdb_prepare_using_field() 3 12 3
B _deduce_field_from_query_param() 0 24 4
A _get_qualified_column_for_field() 0 9 3
B _construct_limit_join_select() 0 12 6
A _construct_internal_join() 0 5 1
A _construct_internal_join_to_table_with_alias() 0 18 4
A _get_data_types() 0 9 2
A get_related_model_obj() 0 9 2
A relation_settings() 0 3 1
A belongs_to_relations() 0 9 3
A related_settings_for() 10 14 2
A field_settings_for() 7 7 2
A has_field() 0 8 2
A has_relation() 0 8 2
A is_primary_key_field() 0 3 2
B get_primary_key_field() 0 14 5
A has_primary_key_field() 0 11 3
A get_a_field_of_type() 0 8 3
B get_foreign_key_to() 3 16 6
A get_table_for_alias() 0 4 1
D field_settings() 22 26 9
C _create_objects() 3 68 13
A create_default_object() 0 13 2
C instantiate_class_from_array_or_object() 0 41 11
A get_from_entity_map() 0 3 2
B add_to_entity_map() 0 18 5
A deduce_fields_n_values_from_cols_n_values() 0 3 1
C _deduce_fields_n_values_from_cols_n_values() 0 23 8
A _get_column_value_with_table_alias_or_not() 0 15 3
B refresh_entity_map_from_db() 0 19 6
B refresh_entity_map_with() 0 21 6
A _get_class_name() 0 3 1
A item_name() 0 7 2
A __call() 17 17 2
B ensure_is_obj() 0 20 9
A ensure_is_ID() 0 16 4
A assume_values_already_prepared_by_model_object() 0 3 1
A get_assumption_concerning_values_already_prepared_by_model_object() 0 3 1
A indexes() 0 3 1
A unique_indexes() 0 9 3
A get_combined_primary_key_fields() 0 8 3
A get_index_primary_key_string() 0 4 1
A parse_index_primary_key_string() 0 12 3
A has_all_combined_primary_key_fields() 0 9 3
B get_all_copies() 7 21 6
A get_one_copy() 13 13 3
A update_by_ID() 0 5 1
A _prepare_operator_for_sql() 5 8 3
A get_all_names() 0 8 2
C get_IDs() 0 22 7
A cap_slug() 0 3 1
B cap_restrictions() 0 15 5
A is_wp_core_model() 0 3 1
A caps_missing() 0 10 3
A cap_contexts_to_cap_action_map() 0 3 1
A cap_action_for_context() 0 17 3
A valid_cap_contexts() 0 8 1
A verify_is_valid_cap_context() 12 15 2
A _invalidate_field_caches() 0 5 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like EEM_Base often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use EEM_Base, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 *
4
 * Class EEM_Base
5
 *
6
 * Multi-table model. Especially handles joins when querying.
7
 * An important note about values dealt with in models and model objects:
8
 * values used by models exist in basically 3 different domains, which the EE_Model_Fields help convert between:
9
 * 1. Client-code values (eg, controller code may refer to a date as "March 21, 2013")
10
 * 2. Model object values (eg, after the model object has called set() on the value and saves it onto the model object, it may become a unix timestamp, eg 12312412412)
11
 * 3. Database values (eg, we may later decide to store dates as mysql dates, in which case they'd be stored as '2013-03-21 00:00:00')
12
 * Sometimes these values are the same, but often they are not. When your client code is using a model's functions, you need to be aware
13
 * which domain your data exists in. If it is client-code values (ie, it hasn't had a EE_Model_Field call prepare_for_set on it) then use the
14
 * model functions as normal. However, if you are calling the model functions with values from the model object domain (ie, the code your writing is
15
 * probably within a model object, and all the values you're dealing with have had an EE_Model_Field call prepare_for_set on them), then you'll want
16
 * to set $values_already_prepared_by_model_object to FALSE within the argument-list of the functions you call (in order to avoid re-processing those values).
17
 * If your values are already in the database values domain, you'll either way to convert them into the model object domain by creating model objects
18
 * from those raw db values (ie,using EEM_Base::_create_objects), or just use $wpdb directly.
19
 *
20
 * @package 			Event Espresso
21
 * @subpackage 	core
22
 * @author 				Michael Nelson
23
 * @since 				EE4
24
 *
25
 */
26
abstract class EEM_Base extends EE_Base{
27
28
	//admin posty
29
	//basic -> grants access to mine -> if they don't have it, select none
30
	//*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
31
	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
32
	//*_published -> grants access to published -> if they dont have it, select non-published
33
	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
34
	//publish_{thing} -> can change status TO publish; SPECIAL CASE
35
36
37
	//frontend posty
38
	//by default has access to published
39
	//basic -> grants access to mine that arent published, and all published
40
	//*_others ->grants access to others that arent private, all mine
41
	//*_private -> grants full access
42
43
	//frontend non-posty
44
	//like admin posty
45
46
	//category-y
47
	//assign -> grants access to join-table
48
	//(delete, edit)
49
50
	//payment-method-y
51
	//for each registered payment method,
52
	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
53
54
	/**
55
	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
56
	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
57
	 * They almost always WILL NOT, but it's not necessarily a requirement.
58
	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
59
	 * @var boolean
60
	 */
61
	private $_values_already_prepared_by_model_object = 0;
62
63
	/**
64
	 * when $_values_already_prepared_by_model_object equals this, we assume
65
	 * the data is just like form input that needs to have the model fields'
66
	 * prepare_for_set and prepare_for_use_in_db called on it
67
	 */
68
	const not_prepared_by_model_object = 0;
69
	/**
70
	 * when $_values_already_prepared_by_model_object equals this, we
71
	 * assume this value is coming from a model object and doesn't need to have
72
	 * prepare_for_set called on it, just prepare_for_use_in_db is used
73
	 */
74
	const prepared_by_model_object = 1;
75
	/**
76
	 * 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
	protected $plural_item = 'Items';
85
86
	/**
87
	 * @type \EE_Table_Base[] $_tables  array of EE_Table objects for defining which tables comprise this model.
88
	 */
89
	protected $_tables;
90
91
	/**
92
	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
93
	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be variable names
94
	 * on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
95
	 *
96
	 * @var \EE_Model_Field_Base[] $_fields
97
	 */
98
	protected $_fields;
99
100
	/**
101
	 * array of different kinds of relations
102
	 *
103
	 * @var \EE_Model_Relation_Base[] $_model_relations
104
	 */
105
	protected $_model_relations;
106
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
	 * @var EE_Default_Where_Conditions
126
	 */
127
	protected $_minimum_where_conditions_strategy;
128
129
	/**
130
	 * String describing how to find the "owner" of this model's objects.
131
	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
132
	 * But when there isn't, this indicates which related model, or transiently-related model,
133
	 * has the foreign key to the wp_users table.
134
	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
135
	 * related to events, and events have a foreign key to wp_users.
136
	 * On EEM_Transaction, this would be 'Transaction.Event'
137
	 * @var string
138
	 */
139
	protected $_model_chain_to_wp_user = '';
140
	/**
141
	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates don't need it (particularly CPT models)
142
	 * @var bool
143
	 */
144
	protected $_ignore_where_strategy = FALSE;
145
146
	/**
147
	 * String used in caps relating to this model. Eg, if the caps relating to this
148
	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
149
	 * @var string. If null it hasn't been initialized yet. If false then we
150
	 * have indicated capabilities don't apply to this
151
	 */
152
	protected $_caps_slug = null;
153
154
	/**
155
	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
156
	 * and next-level keys are capability names, and each's value is a
157
	 * EE_Default_Where_Condition. If the requestor requests to apply caps to the query,
158
	 * they specify which context to use (ie, frontend, backend, edit or delete)
159
	 * and then each capability in the corresponding sub-array that they're missing
160
	 * adds the where conditions onto the query.
161
	 * @var array
162
	 */
163
	protected $_cap_restrictions = array(
164
		self::caps_read => array(),
165
		self::caps_read_admin => array(),
166
		self::caps_edit => array(),
167
		self::caps_delete => array() );
168
169
	/**
170
	 * Array defining which cap restriction generators to use to create default
171
	 * cap restrictions to put in EEM_Base::_cap_restrictions.
172
	 *
173
	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
174
	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
175
	 * automatically set this to false (not just null).
176
	 * @var EE_Restriction_Generator_Base[]
177
	 */
178
	protected $_cap_restriction_generators = array();
179
180
	/**
181
	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
182
	 */
183
	const caps_read = 'read';
184
	const caps_read_admin = 'read_admin';
185
	const caps_edit = 'edit';
186
	const caps_delete = 'delete';
187
188
	/**
189
	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
190
	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
191
	 * maps to 'read' because when looking for relevant permissions we're going to use
192
	 * 'read' in teh capabilities names like 'ee_read_events' etc.
193
	 * @var array
194
	 */
195
	protected $_cap_contexts_to_cap_action_map = array(
196
		self::caps_read => 'read',
197
		self::caps_read_admin => 'read',
198
		self::caps_edit => 'edit',
199
		self::caps_delete => 'delete' );
200
201
	/**
202
	 * Timezone
203
	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming out of the created objects.  NOT all EEM_Base child classes use this property but any that use a EE_Datetime_Field data type will have access to it.
204
	 * @var string
205
	 */
206
	protected $_timezone;
207
208
	/**
209
	 * A copy of _fields, except the array keys are the model names pointed to by
210
	 * the field
211
	 * @var EE_Model_Field_Base[]
212
	 */
213
	private $_cache_foreign_key_to_fields = array();
214
215
	/**
216
	 * Cached list of all the fields on the model, indexed by their name
217
	 * @var EE_Model_Field_Base[]
218
	 */
219
	private $_cached_fields = NULL;
220
221
	/**
222
	 * Cached list of all the fields on the model, except those that are
223
	 * marked as only pertinent to the database
224
	 * @var EE_Model_Field_Base[]
225
	 */
226
	private $_cached_fields_non_db_only = NULL;
227
228
	/**
229
	 * A cached reference to the primary key for quick lookup
230
	 * @var EE_Model_Field_Base
231
	 */
232
	private $_primary_key_field = NULL;
233
234
	/**
235
	 * Flag indicating whether this model has a primary key or not
236
	 * @var boolean
237
	 */
238
	protected $_has_primary_key_field=null;
239
240
	/**
241
	 * Whether or not this model is based off a table in WP core only (CPTs should set
242
	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
243
	 * @var boolean
244
	 */
245
	protected $_wp_core_model = false;
246
247
	/**
248
	 *	List of valid operators that can be used for querying.
249
	 * The keys are all operators we'll accept, the values are the real SQL
250
	 * operators used
251
	 * @var array
252
	 */
253
	protected $_valid_operators = array(
254
		'='=>'=',
255
		'<='=>'<=',
256
		'<'=>'<',
257
		'>='=>'>=',
258
		'>'=>'>',
259
		'!='=>'!=',
260
		'LIKE'=>'LIKE',
261
		'like'=>'LIKE',
262
		'NOT_LIKE'=>'NOT LIKE',
263
		'not_like'=>'NOT LIKE',
264
		'NOT LIKE'=>'NOT LIKE',
265
		'not like'=>'NOT LIKE',
266
		'IN'=>'IN',
267
		'in'=>'IN',
268
		'NOT_IN'=>'NOT IN',
269
		'not_in'=>'NOT IN',
270
		'NOT IN'=>'NOT IN',
271
		'not in'=>'NOT IN',
272
		'between' => 'BETWEEN',
273
		'BETWEEN' => 'BETWEEN',
274
		'IS_NOT_NULL' => 'IS NOT NULL',
275
		'is_not_null' =>'IS NOT NULL',
276
		'IS NOT NULL' => 'IS NOT NULL',
277
		'is not null' => 'IS NOT NULL',
278
		'IS_NULL' => 'IS NULL',
279
		'is_null' => 'IS NULL',
280
		'IS NULL' => 'IS NULL',
281
		'is null' => 'IS NULL',
282
		'REGEXP' => 'REGEXP',
283
		'regexp' => 'REGEXP',
284
		'NOT_REGEXP' => 'NOT REGEXP',
285
		'not_regexp' => 'NOT REGEXP',
286
		'NOT REGEXP' => 'NOT REGEXP',
287
		'not regexp' => 'NOT REGEXP',
288
	);
289
290
	/**
291
	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
292
	 * @var array
293
	 */
294
	protected $_in_style_operators = array('IN', 'NOT IN');
295
296
	/**
297
	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND '12-31-2012'"
298
	 * @var array
299
	 */
300
	protected $_between_style_operators = array( 'BETWEEN' );
301
302
	/**
303
	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists on a join table.
304
	 * @var array
305
	 */
306
	protected $_null_style_operators = array( 'IS NOT NULL', 'IS NULL');
307
308
	/**
309
	 * Allowed values for $query_params['order'] for ordering in queries
310
	 * @var array
311
	 */
312
	protected $_allowed_order_values = array('asc','desc','ASC','DESC');
313
314
	/**
315
	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
316
	 * than regular field names. It is assumed that their values are an array of WHERE conditions
317
	 * @var array
318
	 */
319
	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
320
321
	/**
322
	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
323
	 * 'where', but 'where' clauses are so common that we thought we'd omit it
324
	 * @var array
325
	 */
326
	private $_allowed_query_params = array(0, 'limit','order_by','group_by','having','force_join','order','on_join_limit','default_where_conditions', 'caps');
327
328
	/**
329
	 * All the data types that can be used in $wpdb->prepare statements.
330
	 * @var array
331
	 */
332
	private $_valid_wpdb_data_types = array('%d','%s','%f');
333
334
	/**
335
	 * 	EE_Registry Object
336
	 *	@var 	object
337
	 * 	@access 	protected
338
	 */
339
	protected $EE = NULL;
340
341
342
	/**
343
	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
344
	 * @var int
345
	 */
346
	protected $_show_next_x_db_queries = 0;
347
348
	/**
349
	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
350
	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
351
	 * @var array
352
	 */
353
	protected $_custom_selections = array();
354
355
	/**
356
	 * key => value Entity Map using  ID => model object
357
	 * caches every model object we've fetched from the DB on this request
358
	 * @var EE_Base_Class[]
359
	 */
360
	protected $_entity_map;
361
362
	/**
363
	 * constant used to show EEM_Base has not yet verified the db on this http request
364
	 */
365
	const db_verified_none 		= 0;
366
	/**
367
	 * constant used to show EEM_Base has verified the EE core db on this http request,
368
	 * but not the addons' dbs
369
	 */
370
	const db_verified_core 		= 1;
371
	/**
372
	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
373
	 * the EE core db too)
374
	 */
375
	const db_verified_addons 	= 2;
376
377
	/**
378
	 * indicates whether an EEM_Base child has already re-verified the DB
379
	 * is ok (we don't want to do it repetitively). Should be set to one the constants
380
	 * looking like EEM_Base::db_verified_*
381
	 * @var int - 0 = none, 1 = core, 2 = addons
382
	 */
383
	protected static $_db_verification_level = EEM_Base::db_verified_none;
384
385
386
387
388
	/**
389
	 * About all child constructors:
390
	 * they should define the _tables, _fields and _model_relations arrays.
391
	 * Should ALWAYS be called after child constructor.
392
	 * In order to make the child constructors to be as simple as possible, this parent constructor
393
	 * finalizes constructing all the object's attributes.
394
	 * Generally, rather than requiring a child to code
395
	 * $this->_tables = array(
396
	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
397
	 *        ...);
398
	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
399
	 * each EE_Table has a function to set the table's alias after the constructor, using
400
	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
401
	 * do something similar.
402
	 *
403
	 * @param null $timezone
404
	 * @throws \EE_Error
405
	 */
406
	protected function __construct( $timezone = NULL ){
407
		// check that the model has not been loaded too soon
408
		if ( ! did_action( 'AHEE__EE_System__load_espresso_addons' )) {
409
			throw new EE_Error (
410
				sprintf(
411
					__( '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.', 'event_espresso' ),
412
					get_class( $this )
413
				)
414
			);
415
		}
416
417
		/**
418
		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
419
		 * just use EE_Register_Model_Extension
420
		 * @var EE_Table_Base[] $_tables
421
		 */
422
		$this->_tables = apply_filters( 'FHEE__'.get_class($this).'__construct__tables', $this->_tables );
423
		foreach($this->_tables as $table_alias => $table_obj){
424
			/** @var $table_obj EE_Table_Base */
425
			$table_obj->_construct_finalize_with_alias($table_alias);
426
			if( $table_obj instanceof EE_Secondary_Table ){
427
				/** @var $table_obj EE_Secondary_Table */
428
				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
429
			}
430
		}
431
		/**
432
		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
433
		 * EE_Register_Model_Extension
434
		 * @param EE_Model_Field_Base[] $_fields
435
		 */
436
		$this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields',$this->_fields);
437
		$this->_invalidate_field_caches();
438
		foreach($this->_fields as $table_alias => $fields_for_table){
439
			if ( ! array_key_exists( $table_alias, $this->_tables )){
440
				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",'event_espresso'),$table_alias,implode(",",$this->_fields)));
441
			}
442
			foreach($fields_for_table as $field_name => $field_obj){
443
				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
444
				//primary key field base has a slightly different _construct_finalize
445
				/** @var $field_obj EE_Model_Field_Base */
446
				$field_obj->_construct_finalize( $table_alias, $field_name, $this->get_this_model_name() );
447
			}
448
		}
449
450
		// everything is related to Extra_Meta
451
		if( get_class($this) != 'EEM_Extra_Meta'){
452
			//make extra meta related to everything, but don't block deleting things just
453
			//because they have related extra meta info. For now just orphan those extra meta
454
			//in the future we should automatically delete them
455
			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation( FALSE );
456
		}
457
		//and change logs
458
		if( get_class( $this) !=  'EEM_Change_Log' ) {
459
			$this->_model_relations[ 'Change_Log' ] = new EE_Has_Many_Any_Relation( FALSE );
460
		}
461
		/**
462
		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
463
		 * EE_Register_Model_Extension
464
		 * @param EE_Model_Relation_Base[] $_model_relations
465
		 */
466
		$this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',$this->_model_relations);
467
		foreach($this->_model_relations as $model_name => $relation_obj){
468
			/** @var $relation_obj EE_Model_Relation_Base */
469
			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
470
		}
471
		foreach($this->_indexes as $index_name => $index_obj){
472
			/** @var $index_obj EE_Index */
473
			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
474
		}
475
476
		$this->set_timezone($timezone);
477
		//finalize default where condition strategy, or set default
478
		if( ! $this->_default_where_conditions_strategy){
479
			//nothing was set during child constructor, so set default
480
			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
481
		}
482
		$this->_default_where_conditions_strategy->_finalize_construct($this);
483
		if( ! $this->_minimum_where_conditions_strategy){
484
			//nothing was set during child constructor, so set default
485
			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
486
		}
487
		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
488
489
		//if the cap slug hasn't been set, and we haven't set it to false on purpose
490
		//to indicate to NOT set it, set it to the logical default
491
		if( $this->_caps_slug === null ) {
492
			EE_Registry::instance()->load_helper( 'Inflector' );
493
			$this->_caps_slug = EEH_Inflector::pluralize_and_lower( $this->get_this_model_name() );
494
		}
495
		//initialize the standard cap restriction generators if none were specified by the child constructor
496
		if( $this->_cap_restriction_generators !== false ){
497
			foreach( $this->cap_contexts_to_cap_action_map() as $cap_context => $action ){
498
				if( ! isset( $this->_cap_restriction_generators[ $cap_context ] ) ) {
499
					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
500
						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
501
						new EE_Restriction_Generator_Protected(),
502
						$cap_context,
503
						$this
504
					);
505
				}
506
			}
507
		}
508
		//if there are cap restriction generators, use them to make the default cap restrictions
509
		if( $this->_cap_restriction_generators !== false ){
510
			foreach( $this->_cap_restriction_generators as $context => $generator_object ) {
511
				if( ! $generator_object ){
512
					continue;
513
				}
514 View Code Duplication
				if( ! $generator_object instanceof EE_Restriction_Generator_Base ){
515
					throw new EE_Error(
516
						sprintf(
517
							__( '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.', 'event_espresso' ),
518
							$context,
519
							$this->get_this_model_name()
520
						)
521
					);
522
				}
523
				$action = $this->cap_action_for_context( $context );
524
				if( ! $generator_object->construction_finalized() ){
525
					$generator_object->_construct_finalize( $this, $action );
526
				}
527
528
			}
529
		}
530
		do_action('AHEE__'.get_class($this).'__construct__end');
531
	}
532
533
	/**
534
	 * Generates the cap restrictions for the given context, or if they were
535
	 * already generated just gets what's cached
536
	 * @param string $context one of EEM_Base::valid_cap_contexts()
537
	 * @return EE_Default_Where_Conditions[]
538
	 */
539
	protected function _generate_cap_restrictions( $context ){
540
		if( isset( $this->_cap_restriction_generators[ $context ] ) &&
541
				$this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base ) {
542
			return $this->_cap_restriction_generators[ $context ]->generate_restrictions();
543
		}else{
544
			return array();
545
		}
546
}
547
548
549
	/**
550
	 *		This function is a singleton method used to instantiate the Espresso_model object
551
	 *
552
	 *		@access public
553
	 *		@param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any incoming timezone data that gets saved).  Note this just sends the timezone info to the date time model field objects.  Default is NULL (and will be assumed using the set timezone in the 'timezone_string' wp option)
554
	 *		@return static (as in the concrete child class)
555
	 */
556 View Code Duplication
	public static function instance( $timezone = NULL ){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
557
558
		// check if instance of Espresso_model already exists
559
		if ( ! static::$_instance instanceof static) {
560
			// instantiate Espresso_model
561
			static::$_instance = new static( $timezone );
0 ignored issues
show
Bug introduced by
It seems like $timezone defined by parameter $timezone on line 556 can also be of type string; however, EEM_Base::__construct() does only seem to accept null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
562
		}
563
564
		//we might have a timezone set, let set_timezone decide what to do with it
565
		static::$_instance->set_timezone( $timezone );
566
567
		// Espresso_model object
568
		return static::$_instance;
569
	}
570
571
572
573
	/**
574
	 * resets the model and returns it
575
	 * @param null | string $timezone
576
	 * @return static
577
	 */
578
	public static function reset(  $timezone = NULL ){
579
		if ( ! is_null( static::$_instance ) ) {
580
			static::$_instance = null;
581
582
			return self::instance( $timezone );
583
		}
584
		return null;
585
	}
586
587
	/**
588
	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
589
	 *
590
	 * @param  boolean $translated return localized strings or JUST the array.
591
	 * @return array
592
	 */
593
	 public function status_array( $translated = FALSE ) {
594
	 	if ( !array_key_exists('Status', $this->_model_relations ) )
595
	 		return array();
596
	 	$model_name = $this->get_this_model_name();
597
	 	$status_type = str_replace(' ', '_', strtolower( str_replace('_', ' ', $model_name) ) );
598
	 	$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type) ) );
599
	 	$status_array = array();
600
	 	foreach ( $stati as $status ) {
601
            $status_array[ $status->ID() ] = $status->get('STS_code');
602
        }
603
        return $translated ? EEM_Status::instance()->localized_status($status_array, FALSE, 'sentence') : $status_array;
604
    }
605
606
607
608
	/**
609
	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
610
	 * @param array $query_params {
611
	 *
612
	 *	@var array $0 (where) array {
613
	 *		eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine if user is bob')
614
			becomes
615
	 *		SQL >> "...WHERE QST_display_text = 'Are you bob?' AND QST_admin_text = 'Determine if user is bob'...")
616
	 *
617
	 *		To add WHERE conditions based on related models (and even models-related-to-related-models) prepend the model's name
618
	 *		onto the field name. Eg, EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12)));
619
	 *		becomes
620
	 *		SQL >> "SELECT * FROM wp_posts AS Event_CPT
621
	 *						LEFT JOIN wp_esp_event_meta AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID
622
	 *						LEFT JOIN wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID
623
	 *						LEFT JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID
624
	 *						LEFT JOIN wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID
625
	 *						WHERE Venue_CPT.ID = 12
626
	 *		Notice that automatically took care of joining Events to Venues (even when each of those models actually consisted of two tables).
627
	 * 	 	Also, you may chain the model relations together. Eg instead of just having "Venue.VNU_ID", you could have
628
	 *		"Registration.Attendee.ATT_ID" as a field on a query for events (because events are related to Registrations, which are related to Attendees).
629
	 *		You can take it even further with "Registration.Transaction.Payment.PAY_amount" etc.
630
	 *		To change the operator (from the default of '='), change the value to an numerically-indexed array, where the
631
	 *		first item in the list is the operator.
632
	 *		eg: array( 'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34), 'QST_wp_user' => array('in',array(1,2,7,23)))
633
	 *		becomes
634
	 *		SQL >> "...WHERE QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN (1,2,7,23)...".
635
	 * 		Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN (followed by an array with exactly 2 date strings), IS NULL, and IS NOT NULL
636
	 *
637
	 *		Values can be a string, int, or float. They can also be arrays IFF the operator is IN.
638
	 *		Also, values can actually be field names. To indicate the value is a field, simply provide a third array item (true) to the operator-value array like so:
639
	 *		eg: array( 'DTT_reg_limit' => array('>', 'DTT_sold', TRUE) )
640
	 *		becomes
641
	 *		SQL >> "...WHERE DTT_reg_limit > DTT_sold"
642
	 *		Note: you can also use related model field names like you would any other field name.
643
	 *		eg: array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE)
644
	 *		could be used if you were querying EEM_Tickets (because Datetime is directly related to tickets)
645
	 *
646
	 *		Also, by default all the where conditions are AND'd together.
647
	 *		To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together
648
	 *		eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' => 345678912))
649
	 *		becomes
650
	 *		SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp = 345678912...".
651
	 * 		Also, to negate an entire set of conditions, use 'NOT' as an array key.
652
	 *		eg: array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)
653
	 *		becomes
654
	 *		SQL >> "...where ! (TXN_total =50 AND TXN_paid =23)
655
	 *		Note: the 'glue' used to join each condition will continue to be what you last specified. IE, "AND"s by default,
656
	 *		but if you had previously specified to use ORs to join, ORs will continue to be used. So, if you specify to use an "OR"
657
	 *		to join conditions, it will continue to "stick" until you specify an AND.
658
	 *		eg array('OR'=>array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN')
659
	 *		becomes
660
	 *		SQL >> "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND STS_ID='TIN'"
661
	 *
662
	 *		They can be nested indefinitely.
663
	 *		eg: array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN'))))
664
	 *		becomes
665
	 *		SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..."
666
	 *
667
	 *		GOTCHA:
668
	 *		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.
669
	 *		eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)),
670
	 *		as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'.
671
	 *		becomes
672
	 *		SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions).
673
	 *
674
	 *		To overcome this, you can add a '*' character to the end of the field's name, followed by anything.
675
	 *		These will be removed when generating the SQL string, but allow for the array keys to be unique.
676
	 *		eg: you could rewrite the previous query as:
677
	 *		array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date))
678
	 *		which correctly becomes
679
	 *		SQL >> "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND PAY_timestamp != 1241234123"
680
	 *		This can be applied to condition operators too,
681
	 *		eg: array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
682
	 *	@var mixed $limit int|array	adds a limit to the query just like the SQL limit clause, so limits of "23", "25,50", and array(23,42) are all valid would become
683
	 *		SQL "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
684
	 *		Remember when you provide two numbers for the limit, the 1st number is the OFFSET, the 2nd is the LIMIT
685
	 *	@var array $on_join_limit allows the setting of a special select join with a internal limit so you can do paging on one-to-many multi-table-joins.
686
	 *		Send an array in the following format array('on_join_limit' => array( 'table_alias', array(1,2) ) ).
687
	 *	@var mixed $order_by name of a column to order by, or an array where keys are field names and values are either 'ASC' or 'DESC'. 'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'),
688
	 *		which would becomes SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date DESC..." respectively.
689
	 *		Like the 'where' conditions, these fields can be on related models.
690
	 *		Eg 'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is perfectly valid from any model related to 'Registration' (like Event, Attendee, Price, Datetime, etc.)
691
	 *	@var string $order	If 'order_by' is used and its value is a string (NOT an array), then 'order' specifies whether to order the field specified in 'order_by' in ascending or
692
	 *		descending order. Acceptable values are 'ASC' or 'DESC'. If, 'order_by' isn't used, but 'order' is, then it is assumed you want to order by the primary key.
693
	 *		Eg, EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC'); //(will join with the Datetime model's table(s) and order by its field DTT_EVT_start)
694
	 *		or EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
695
	 *
696
	 *	@var mixed $group_by name of field to order by, or an array of fields. Eg either 'group_by'=>'VNU_ID', or 'group_by'=>array('EVT_name','Registration.Transaction.TXN_total')
697
	 *		Note: if no $group_by is specified, and a limit is set, automatically groups by the model's primary key (or combined primary keys). This
698
	 *		avoids some weirdness that results when using limits, tons of joins, and no group by, see https://events.codebasehq.com/projects/event-espresso/tickets/9389
699
	 *
700
	 *	@var array $having	exactly like WHERE parameters array, except these conditions apply to the grouped results (whereas WHERE conditions apply to the pre-grouped results)
701
	 *
702
	 *	@var array $force_join forces a join with the models named. Should be an numerically-indexed array where values are models to be joined in the query.Eg
703
	 *		array('Attendee','Payment','Datetime'). You may join with transient models using period, eg "Registration.Transaction.Payment".
704
	 *		You will probably only want to do this in hopes of increasing efficiency, as related models which belongs to the current model
705
	 *		(ie, the current model has a foreign key to them, like how Registration belongs to Attendee) can be cached in order
706
	 *		to avoid future queries
707
	 *
708
	 *	@var string $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'. set this to 'none' to disable all default where conditions. Eg, usually soft-deleted objects are filtered-out
709
	 *		if you want to include them, set this query param to 'none'. If you want to ONLY disable THIS model's default where conditions
710
	 *		set it to 'other_models_only'. If you only want this model's default where conditions added to the query, use 'this_model_only'.
711
	 *		If you want to use all default where conditions (default), set to 'all'.
712
	 *	@var string $caps controls what capability requirements to apply to the query; ie, should we just NOT
713
	 *		apply cany capabilities/permissions/restrictions and return everything? Or should we only show the
714
	 *		current user items they should be able to view on the frontend, backend, edit, or delete?
715
	 *		can be set to 'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
716
	 * }
717
	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different from EE_Base_Class[], use _get_all_wpdb_results()and make it public again. Array keys are object IDs (if there is a primary key on the model. if not, numerically indexed)
718
	 * Some full examples:
719
	 *
720
	 * 		get 10 transactions which have Scottish attendees:
721
	 *
722
	 * 		EEM_Transaction::instance()->get_all( array(
723
	 *			array(
724
	 *				'OR'=>array(
725
	 *					'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
726
	 *					'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
727
	 *				)
728
	 * 			),
729
	 *			'limit'=>10,
730
	 *			'group_by'=>'TXN_ID'
731
	 * 		));
732
	 *
733
	 * 		get all the answers to the question titled "shirt size" for event with id 12, ordered by their answer
734
	 *
735
	 * 		EEM_Answer::instance()->get_all(array(
736
	 *			array(
737
	 *				'Question.QST_display_text'=>'shirt size',
738
	 *				'Registration.Event.EVT_ID'=>12
739
	 * 			),
740
	 *			'order_by'=>array('ANS_value'=>'ASC')
741
	 *		));
742
	 */
743
	function get_all($query_params = array()){
744
		if( isset( $query_params[ 'limit' ] )
745
			&& ! isset( $query_params[ 'group_by' ] ) ) {
746
			$query_params[ 'group_by' ] = array_keys( $this->get_combined_primary_key_fields() );
747
		}
748
		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, NULL));
749
	}
750
751
	/**
752
	 * Modifies the query parameters so we only get back model objects
753
	 * that "belong" to the current user
754
	 * @param array $query_params @see EEM_Base::get_all()
755
	 * @return array like EEM_Base::get_all
756
	 */
757
	function alter_query_params_to_only_include_mine( $query_params = array() ) {
758
		$wp_user_field_name = $this->wp_user_field_name();
759
		if( $wp_user_field_name ){
0 ignored issues
show
Bug Best Practice introduced by
The expression $wp_user_field_name of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
760
			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
761
		}
762
		return $query_params;
763
	}
764
765
	/**
766
	 * Returns the name of the field's name that points to the WP_User table
767
	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
768
	 * foreign key to the WP_User table)
769
	 * @return string|boolean string on success, boolean false when there is no
770
	 * foreign key to the WP_User table
771
	 */
772
	function wp_user_field_name() {
773
		try{
774
			if( ! empty( $this->_model_chain_to_wp_user ) ) {
775
				$models_to_follow_to_wp_users = explode( '.', $this->_model_chain_to_wp_user );
776
				$last_model_name = end( $models_to_follow_to_wp_users );
777
				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model( $last_model_name );
778
				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
779
			}else{
780
				$model_with_fk_to_wp_users = $this;
781
				$model_chain_to_wp_user = '';
782
			}
783
			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to( 'WP_User' );
784
			return $model_chain_to_wp_user . $wp_user_field->get_name();
785
		}catch( EE_Error $e ) {
786
			return false;
787
		}
788
	}
789
790
	/**
791
	 * Returns the _model_chain_to_wp_user string, which indicates which related model
792
	 * (or transiently-related model) has a foreign key to the wp_users table;
793
	 * useful for finding if model objects of this type are 'owned' by the current user.
794
	 * This is an empty string when the foreign key is on this model and when it isn't,
795
	 * but is only non-empty when this model's ownership is indicated by a RELATED model
796
	 * (or transiently-related model)
797
	 * @return string
798
	 */
799
	public function model_chain_to_wp_user(){
800
		return $this->_model_chain_to_wp_user;
801
	}
802
803
	/**
804
	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
805
	 * like how registrations don't have a foreign key to wp_users, but the
806
	 * events they are for are), or is unrelated to wp users.
807
	 * generally available
808
	 * @return boolean
809
	 */
810
	public function is_owned() {
811
		if( $this->model_chain_to_wp_user() ){
812
			return true;
813
		}else{
814
			try{
815
				$this->get_foreign_key_to( 'WP_User' );
816
				return true;
817
			}catch( EE_Error $e ){
818
				return false;
819
			}
820
		}
821
	}
822
823
824
	/**
825
	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but may want to
826
	 * preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on the model)
827
	 * @param array $query_params like EEM_Base::get_all's $query_params
828
	 * @param string $output ARRAY_A, OBJECT_K, etc. Just like
829
	 * @param mixed $columns_to_select, What columns to select. By default, we select all columns specified by the fields on the model,
0 ignored issues
show
Documentation introduced by
There is no parameter named $columns_to_select,. Did you maybe mean $columns_to_select?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
830
	 * and the models we joined to in the query. However, you can override this and set the select to "*", or a specific column name, like "ATT_ID", etc.
831
	 * If you would like to use these custom selections in WHERE, GROUP_BY, or HAVING clauses, you must instead provide an array.
832
	 * Array keys are the aliases used to refer to this selection, and values are to be numerically-indexed arrays, where 0 is the selection
833
	 * and 1 is the data type. Eg, array('count'=>array('COUNT(REG_ID)','%d'))
834
	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
835
	 */
836
	protected function  _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null){
837
		//remember the custom selections, if any
838
		if(is_array($columns_to_select)){
839
			$this->_custom_selections = $columns_to_select;
840
		}elseif(is_string($columns_to_select)){
841
			$this->_custom_selections = array($this->_custom_selections);
842
		}else{
843
			$this->_custom_selections = array();
844
		}
845
846
		$model_query_info = $this->_create_model_query_info_carrier($query_params);
847
		$select_expressions = $columns_to_select ? $this->_construct_select_from_input($columns_to_select) : $this->_construct_default_select_sql($model_query_info);
848
		$SQL ="SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
849
//		echo "sql:$SQL";
850
		$results =  $this->_do_wpdb_query( 'get_results', array($SQL, $output ) );// $wpdb->get_results($SQL, $output);
851
		return $results;
852
	}
853
854
	/**
855
	 * Gets an array of rows from the database just like $wpdb->get_results would,
856
	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
857
	 * take care of joins, field preparation etc.
858
	 *
859
*@param array $query_params like EEM_Base::get_all's $query_params
860
	 * @param string $output ARRAY_A, OBJECT_K, etc. Just like
861
	 * @param mixed $columns_to_select, What columns to select. By default, we select all columns specified by the fields on the model,
0 ignored issues
show
Documentation introduced by
There is no parameter named $columns_to_select,. Did you maybe mean $columns_to_select?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
862
	 * and the models we joined to in the query. However, you can override this and set the select to "*", or a specific column name, like "ATT_ID", etc.
863
	 * If you would like to use these custom selections in WHERE, GROUP_BY, or HAVING clauses, you must instead provide an array.
864
	 * Array keys are the aliases used to refer to this selection, and values are to be numerically-indexed arrays, where 0 is the selection
865
	 * and 1 is the data type. Eg, array('count'=>array('COUNT(REG_ID)','%d'))
866
	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
867
	 */
868
	public function  get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null){
869
		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
870
	}
871
872
873
	/**
874
	 * For creating a custom select statement
875
	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
876
	 * or an array where keys are aliases, and values are arrays where 0=>the selection SQL, and 1=>is the datatype
877
	 * @throws EE_Error
878
	 * @return string
879
	 */
880
	private function _construct_select_from_input($columns_to_select){
881
		if(is_array($columns_to_select)){
882
			$select_sql_array = array();
883
884
			foreach($columns_to_select as $alias => $selection_and_datatype){
885
				if( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])){
886
					throw new EE_Error(
887
						sprintf(
888
							__(
889
								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
890
								"event_espresso"
891
							),
892
							$selection_and_datatype,
893
							$alias
894
						)
895
					);
896
				}
897
				if( ! in_array( $selection_and_datatype[1],$this->_valid_wpdb_data_types)){
898
					throw new EE_Error(
899
						sprintf(
900
							__(
901
								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
902
								"event_espresso"
903
							),
904
							$selection_and_datatype[ 1 ],
905
							$selection_and_datatype[ 0 ],
906
							$alias,
907
							implode( ",", $this->_valid_wpdb_data_types )
908
						)
909
					);
910
				}
911
				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
912
			}
913
			$columns_to_select_string = implode(", ",$select_sql_array);
914
		}else{
915
			$columns_to_select_string = $columns_to_select;
916
		}
917
		return $columns_to_select_string;
918
919
	}
920
921
922
923
	/**
924
	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
925
	 * @return string
926
	 */
927
	function primary_key_name(){
928
		return $this->get_primary_key_field()->get_name();
929
	}
930
931
932
933
	/**
934
	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
935
	 * If there is no primary key on this model, $id is treated as primary key string
936
	 * @param mixed $id int or string, depending on the type of the model's primary key
937
	 * @return EE_Base_Class
938
	 */
939
	function get_one_by_ID($id){
940
		if( $this->get_from_entity_map( $id ) ){
941
			return $this->get_from_entity_map( $id );
942
		}
943
		return $this->get_one(
944
			$this->alter_query_params_to_restrict_by_ID(
945
				$id,
946
				array( 'default_where_conditions' => 'minimum' )
947
			)
948
		);
949
	}
950
951
	/**
952
	 * Alters query parameters to only get items with this ID are returned.
953
	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string()
954
	 * @param int $id
955
	 * @param array $query_params
956
	 * @return array of normal query params, @see EEM_Base::get_all
957
	 */
958
	public function alter_query_params_to_restrict_by_ID( $id, $query_params = array() ) {
959
		if( ! isset( $query_params[ 0 ] ) ) {
960
			$query_params[ 0 ] = array();
961
		}
962
		if( $this->has_primary_key_field ( ) ) {
963
			$query_params[ 0 ][ $this->primary_key_name() ] = $id ;
964
		}else{
965
			//no primary key, so the $id must be from the get_index_primary_key_string()
966
			$query_params[0] = array_replace_recursive( $query_params[ 0 ], $this->parse_index_primary_key_string( $id ) );
967
		}
968
		return $query_params;
969
	}
970
971
972
	/**
973
	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an array. If no item is found,
974
	 * null is returned.
975
	 * @param array $query_params like EEM_Base's $query_params variable.
976
	 * @return EE_Base_Class | NULL
977
	 */
978 View Code Duplication
	function get_one($query_params = array()){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
979
		if( ! is_array( $query_params ) ){
980
			EE_Error::doing_it_wrong('EEM_Base::get_one', sprintf( __( '$query_params should be an array, you passed a variable of type %s', 'event_espresso' ), gettype( $query_params ) ), '4.6.0' );
981
			$query_params = array();
982
		}
983
		$query_params['limit'] = 1;
984
		$items = $this->get_all($query_params);
985
		if(empty($items)){
986
			return null;
987
		}else{
988
			return array_shift($items);
989
		}
990
	}
991
992
993
994
995
	/**
996
	 * Returns the next x number of items in sequence from the given value as
997
	 * found in the database matching the given query conditions.
998
	 *
999
	 * @param mixed $current_field_value    Value used for the reference point.
1000
	 * @param null $field_to_order_by       What field is used for the
1001
	 *                                      reference point.
1002
	 * @param int $limit                    How many to return.
1003
	 * @param array $query_params           Extra conditions on the query.
1004
	 * @param null $columns_to_select       If left null, then an array of
1005
	 *                                      EE_Base_Class objects is returned,
1006
	 *                                      otherwise you can indicate just the
1007
	 *                                      columns you want returned.
1008
	 *
1009
	 * @return EE_Base_Class[]|array
1010
	 */
1011
	public function next_x( $current_field_value, $field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null ) {
1012
		return $this->_get_consecutive( $current_field_value, '>', $field_to_order_by, $limit, $query_params, $columns_to_select );
1013
	}
1014
1015
1016
1017
1018
1019
	/**
1020
	 * Returns the previous x number of items in sequence from the given value
1021
	 * as found in the database matching the given query conditions.
1022
	 *
1023
	 * @param mixed $current_field_value    Value used for the reference point.
1024
	 * @param null $field_to_order_by       What field is used for the
1025
	 *                                      reference point.
1026
	 * @param int $limit                    How many to return.
1027
	 * @param array $query_params           Extra conditions on the query.
1028
	 * @param null $columns_to_select       If left null, then an array of
1029
	 *                                      EE_Base_Class objects is returned,
1030
	 *                                      otherwise you can indicate just the
1031
	 *                                      columns you want returned.
1032
	 *
1033
	 * @return EE_Base_Class[]|array
1034
	 */
1035
	public function previous_x( $current_field_value, $field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null ) {
1036
		return $this->_get_consecutive( $current_field_value, '<', $field_to_order_by, $limit, $query_params, $columns_to_select );
1037
	}
1038
1039
1040
1041
1042
	/**
1043
	 * Returns the next item in sequence from the given value as found in the
1044
	 * database matching the given query conditions.
1045
	 *
1046
	 * @param mixed $current_field_value    Value used for the reference point.
1047
	 * @param null $field_to_order_by       What field is used for the
1048
	 *                                      reference point.
1049
	 * @param array $query_params           Extra conditions on the query.
1050
	 * @param null $columns_to_select       If left null, then an EE_Base_Class
1051
	 *                                      object is returned, otherwise you
1052
	 *                                      can indicate just the columns you
1053
	 *                                      want and a single array indexed by
1054
	 *                                      the columns will be returned.
1055
	 *
1056
	 * @return EE_Base_Class|null|array()
0 ignored issues
show
Documentation introduced by
The doc-type EE_Base_Class|null|array() could not be parsed: Expected "|" or "end of type", but got "(" at position 24. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1057
	 */
1058
	public function next( $current_field_value, $field_to_order_by = null, $query_params = array(), $columns_to_select = null ) {
1059
		$results = $this->_get_consecutive( $current_field_value, '>', $field_to_order_by, 1, $query_params, $columns_to_select );
1060
		return empty( $results ) ? null : reset( $results );
1061
	}
1062
1063
1064
1065
1066
	/**
1067
	 * Returns the previous item in sequence from the given value as found in
1068
	 * the database matching the given query conditions.
1069
	 *
1070
	 * @param mixed $current_field_value    Value used for the reference point.
1071
	 * @param null $field_to_order_by       What field is used for the
1072
	 *                                      reference point.
1073
	 * @param array $query_params           Extra conditions on the query.
1074
	 * @param null $columns_to_select       If left null, then an EE_Base_Class
1075
	 *                                      object is returned, otherwise you
1076
	 *                                      can indicate just the columns you
1077
	 *                                      want and a single array indexed by
1078
	 *                                      the columns will be returned.
1079
	 *
1080
	 * @return EE_Base_Class|null|array()
0 ignored issues
show
Documentation introduced by
The doc-type EE_Base_Class|null|array() could not be parsed: Expected "|" or "end of type", but got "(" at position 24. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1081
	 */
1082
	public function previous( $current_field_value, $field_to_order_by = null, $query_params = array(), $columns_to_select = null ) {
1083
		$results = $this->_get_consecutive( $current_field_value, '<', $field_to_order_by, 1, $query_params, $columns_to_select );
1084
		return empty( $results ) ? null : reset( $results );
1085
	}
1086
1087
1088
1089
1090
1091
	/**
1092
	 * Returns the a consecutive number of items in sequence from the given
1093
	 * value as found in the database matching the given query conditions.
1094
	 *
1095
	 * @param mixed $current_field_value    Value used for the reference point.
1096
	 * @param string $operand               What operand is used for the
1097
	 *                                      sequence.
1098
	 * @param null $field_to_order_by       What field is used for the
1099
	 *                                      reference point.
1100
	 * @param int $limit                    How many to return.
1101
	 * @param array $query_params           Extra conditions on the query.
1102
	 * @param null $columns_to_select       If left null, then an array of
1103
	 *                                      EE_Base_Class objects is returned,
1104
	 *                                      otherwise you can indicate just the
1105
	 *                                      columns you want returned.
1106
	 *
1107
	 * @return EE_Base_Class[]|array
1108
	 * @throws EE_Error
1109
	 */
1110
	protected function _get_consecutive( $current_field_value, $operand = '>', $field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null ) {
1111
		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1112
		if ( empty( $field_to_order_by ) ) {
1113
			if ( $this->has_primary_key_field() ) {
1114
				$field_to_order_by = $this->get_primary_key_field()->get_name();
1115
			} else {
1116
1117
				if ( WP_DEBUG ) {
1118
					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).', 'event_espresso' ) );
1119
				}
1120
				EE_Error::add_error( __('There was an error with the query.', 'event_espresso') );
1121
				return array();
1122
			}
1123
		}
1124
1125
		if( ! is_array( $query_params ) ){
1126
			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive', sprintf( __( '$query_params should be an array, you passed a variable of type %s', 'event_espresso' ), gettype( $query_params ) ), '4.6.0' );
1127
			$query_params = array();
1128
		}
1129
1130
		//let's add the where query param for consecutive look up.
1131
		$query_params[0][ $field_to_order_by ] = array( $operand, $current_field_value );
1132
		$query_params['limit'] = $limit;
1133
1134
		//set direction
1135
		$incoming_orderby = isset( $query_params['order_by'] ) ? $query_params['order_by'] : array();
1136
		$query_params['order_by'] = $operand == '>' ? array( $field_to_order_by => 'ASC' ) + $incoming_orderby : array( $field_to_order_by => 'DESC') + $incoming_orderby;
1137
1138
		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1139
		if ( empty( $columns_to_select ) ) {
1140
			return $this->get_all( $query_params );
1141
		} else {
1142
			//getting just the fields
1143
			return $this->_get_all_wpdb_results( $query_params, ARRAY_A, $columns_to_select );
1144
		}
1145
	}
1146
1147
1148
1149
1150
	/**
1151
	 * This sets the _timezone property after model object has been instantiated.
1152
	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1153
	 */
1154
	public function set_timezone( $timezone ) {
1155
		if ( $timezone !== null ) {
1156
			$this->_timezone = $timezone;
1157
		}
1158
		//note we need to loop through relations and set the timezone on those objects as well.
1159
		foreach ( $this->_model_relations as $relation ) {
1160
			$relation->set_timezone( $timezone );
1161
		}
1162
		//and finally we do the same for any datetime fields
1163
		foreach ( $this->_fields as $field ) {
1164
			if ( $field instanceof EE_Datetime_Field ) {
1165
				$field->set_timezone( $timezone );
1166
			}
1167
		}
1168
	}
1169
1170
1171
1172
	/**
1173
	 * This just returns whatever is set for the current timezone.
1174
	 *
1175
	 * @access public
1176
	 * @return string
1177
	 */
1178
	public function get_timezone() {
1179
		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1180
		if ( empty( $this->_timezone ) ) {
1181
			foreach( $this->_fields as $field ) {
1182
				if ( $field instanceof EE_Datetime_Field ) {
1183
					$this->set_timezone($field->get_timezone());
1184
					break;
1185
				}
1186
			}
1187
		}
1188
1189
		//if timezone STILL empty then return the default timezone for the site.
1190
		if ( empty( $this->_timezone ) ) {
1191
			EE_Registry::instance()->load_helper( 'DTT_Helper' );
1192
			$this->set_timezone( EEH_DTT_Helper::get_timezone() );
1193
		}
1194
		return $this->_timezone;
1195
	}
1196
1197
1198
1199
	/**
1200
	 * This returns the date formats set for the given field name and also ensures that
1201
	 * $this->_timezone property is set correctly.
1202
	 *
1203
	 * @since 4.6.x
1204
	 * @param string $field_name The name of the field the formats are being retrieved for.
1205
	 * @param bool   $pretty          Whether to return the pretty formats (true) or not (false).
1206
	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1207
	 *
1208
	 * @return array formats in an array with the date format first, and the time format last.
1209
	 */
1210
	public function get_formats_for( $field_name, $pretty = false ) {
1211
		$field_settings = $this->field_settings_for( $field_name );
1212
1213
		//if not a valid EE_Datetime_Field then throw error
1214
		if ( ! $field_settings instanceof EE_Datetime_Field ) {
1215
			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.', 'event_espresso' ), $field_name ) );
1216
		}
1217
1218
		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1219
		//the field.
1220
		$this->_timezone = $field_settings->get_timezone();
1221
1222
		return array( $field_settings->get_date_format( $pretty ), $field_settings->get_time_format( $pretty ) );
1223
	}
1224
1225
1226
1227
	/**
1228
	 * This returns the current time in a format setup for a query on this model.
1229
	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1230
	 * it will return:
1231
	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for NOW
1232
	 *  - or a unixtimestamp (equivalent to time())
1233
	 *
1234
	 * @since 4.6.x
1235
	 * @param string $field_name The field the current time is needed for.
1236
	 * @param bool   $timestamp  True means to return a unix timestamp. Otherwise a
1237
	 *                           		 formatted string matching the set format for the field in the set timezone will
1238
	 *                           		 be returned.
1239
	 * @param string $what         Whether to return the string in just the time format, the date format, or both.
1240
	 *
1241
	 * @throws EE_Error   	If the given field_name is not of the EE_Datetime_Field type.
1242
	 *
1243
	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1244
	 *                    	     exception is triggered.
1245
	 */
1246
	public function current_time_for_query( $field_name, $timestamp = false, $what = 'both' ) {
1247
		$formats = $this->get_formats_for( $field_name );
1248
1249
		$DateTime = new DateTime( "now", new DateTimeZone( $this->_timezone ) );
1250
1251
		if ( $timestamp ) {
1252
			return $DateTime->format( 'U' );
1253
		}
1254
1255
		//not returning timestamp, so return formatted string in timezone.
1256
		switch( $what ) {
1257
			case 'time' :
1258
				return $DateTime->format( $formats[1] );
1259
				break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1260
			case 'date' :
1261
				return $DateTime->format( $formats[0] );
1262
				break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1263
			default :
1264
				return $DateTime->format( implode( ' ', $formats ) );
1265
				break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1266
		}
1267
	}
1268
1269
1270
1271
1272
1273
	/**
1274
	 * This receives a timestring for a given field and ensures that it is setup to match what the internal settings
1275
	 * for the model are.  Returns a DateTime object.
1276
	 *
1277
	 * Note: a gotcha for when you send in unixtimestamp.  Remember a unixtimestamp is already timezone agnostic,
1278
	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is ignored.
1279
	 *
1280
	 * @param string $field_name The field being setup.
1281
	 * @param string $timestring   The date timestring being used.
1282
	 * @param string $incoming_format        The format for the time string.
1283
	 * @param string $timezone   By default, it is assumed the incoming timestring is in timezone for
1284
	 *                           		the blog.  If this is not the case, then it can be specified here.  If incoming format is
1285
	 *                           		'U', this is ignored.
1286
	 * @return DateTime
1287
	 */
1288
	public function convert_datetime_for_query( $field_name, $timestring, $incoming_format, $timezone = '' ) {
1289
1290
		//just using this to ensure the timezone is set correctly internally
1291
		$this->get_formats_for( $field_name );
1292
1293
		//load EEH_DTT_Helper
1294
		EE_Registry::instance()->load_helper( 'DTT_Helper' );
1295
		$set_timezone = empty( $timezone ) ? EEH_DTT_Helper::get_timezone() : $timezone;
1296
1297
		$incomingDateTime = date_create_from_format( $incoming_format, $timestring, new DateTimeZone( $set_timezone ) );
1298
1299
		return $incomingDateTime->setTimeZone( new DateTimeZone( $this->_timezone ) );
1300
	}
1301
1302
1303
1304
1305
	/**
1306
	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1307
	 * @return EE_Table_Base[]
1308
	 */
1309
	function get_tables(){
1310
		return $this->_tables;
1311
	}
1312
1313
1314
1315
	/**
1316
	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1317
	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1318
	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for each row (in the primary table) we're trying to update; if not,
1319
	 * it inserts an entry in the secondary table.
1320
	 * Eg: if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a model object with EVT_ID = 1
1321
	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but there is no entry in wp_esp_event for this entry in wp_posts.
1322
	 * So, this update script will insert a row into wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in $fields_n_values,
1323
	 * the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which are not specified)
1324
	 * @param array $fields_n_values keys are model fields (exactly like keys in EEM_Base::_fields, NOT db columns!), values are strings, ints, floats, and maybe arrays if they are to be serialized.
1325
	 * Basically, the values are what you'd expect to be values on the model, NOT necessarily what's in the DB. For example, if we wanted to update only the TXN_details on any Transactions where its ID=34,
1326
	 * we'd use this method as follows:
1327
	 * EEM_Transaction::instance()->update(
1328
	 *		array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1329
	 *		array(array('TXN_ID'=>34)));
1330
	 * @param array $query_params very much like EEM_Base::get_all's $query_params
1331
	 * in client code into what's expected to be stored on each field. Eg, consider updating Question's QST_admin_label field is of type Simple_HTML. If you use this function to update
1332
	 * that field to $new_value = (note replace 8's with appropriate opening and closing tags in the following example)"8script8alert('I hack all');8/script88b8boom baby8/b8", then if you set $values_already_prepared_by_model_object to TRUE,
1333
	 * it is assumed that you've already called EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the malicious javascript. However, if $values_already_prepared_by_model_object
1334
	 * is left as FALSE, then EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it, and every other field, before insertion. We provide this parameter because
1335
	 * model objects perform their prepare_for_set function on all their values, and so don't need to be called again (and in many cases, shouldn't be called again. Eg: if we
1336
	 * escape HTML characters in the prepare_for_set method...)
1337
	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1338
	 * in this model's entity map according to $fields_n_values that match $query_params. This
1339
	 * obviously has some overhead, so you can disable it by setting this to FALSE, but
1340
	 * be aware that model objects being used could get out-of-sync with the database
1341
	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num rows affected which *could* include 0 which DOES NOT mean the query was bad)
1342
	 */
1343
	function update($fields_n_values, $query_params, $keep_model_objs_in_sync = TRUE){
1344
		if( ! is_array( $query_params ) ){
1345
			EE_Error::doing_it_wrong('EEM_Base::update', sprintf( __( '$query_params should be an array, you passed a variable of type %s', 'event_espresso' ), gettype( $query_params ) ), '4.6.0' );
1346
			$query_params = array();
1347
		}
1348
		/**
1349
		 * Action called before a model update call has been made.
1350
		 *
1351
		 * @param EEM_Base $model
1352
		 * @param array $fields_n_values the updated fields and their new values
1353
		 * @param array $query_params @see EEM_Base::get_all()
1354
		 */
1355
		do_action( 'AHEE__EEM_Base__update__begin',$this, $fields_n_values, $query_params );
1356
		/**
1357
		 * Filters the fields about to be updated given the query parameters. You can provide the
1358
		 * $query_params to $this->get_all() to find exactly which records will be updated
1359
		 * @param array $fields_n_values fields and their new values
1360
		 * @param EEM_Base $model the model being queried
1361
		 * @param array $query_params see EEM_Base::get_all()
1362
		 */
1363
		$fields_n_values = apply_filters( 'FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this, $query_params );
1364
		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1365
		//to do that, for each table, verify that it's PK isn't null.
1366
		$tables= $this->get_tables();
1367
1368
		//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
1369
		//NOTE: we should make this code more efficient by NOT querying twice
1370
		//before the real update, but that needs to first go through ALPHA testing
1371
		//as it's dangerous. says Mike August 8 2014
1372
1373
			//we want to make sure the default_where strategy is ignored
1374
			$this->_ignore_where_strategy = TRUE;
1375
			$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1376
			foreach( $wpdb_select_results as $wpdb_result ){
1377
				// type cast stdClass as array
1378
				$wpdb_result = (array)$wpdb_result;
1379
				//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1380
				if( $this->has_primary_key_field() ){
1381
					$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1382
				}else{
1383
					//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)
1384
					$main_table_pk_value = null;
1385
				}
1386
				//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
1387
				//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
1388
				if(count($tables) > 1){
1389
					//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1390
					//in that table, and so we'll want to insert one
1391
					foreach($tables as $table_obj){
1392
						$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1393
						//if there is no private key for this table on the results, it means there's no entry
1394
						//in this table, right? so insert a row in the current table, using any fields available
1395
						if( ! ( array_key_exists( $this_table_pk_column, $wpdb_result) && $wpdb_result[ $this_table_pk_column ] )){
1396
							$success = $this->_insert_into_specific_table($table_obj, $fields_n_values, $main_table_pk_value);
1397
							//if we died here, report the error
1398
							if( ! $success ) {
1399
								return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by EEM_Base::update of type integer.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
1400
							}
1401
						}
1402
					}
1403
				}
1404
1405
//				//and now check that if we have cached any models by that ID on the model, that
1406
//				//they also get updated properly
1407
//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1408
//				if( $model_object ){
1409
//					foreach( $fields_n_values as $field => $value ){
1410
//						$model_object->set($field, $value);
1411
			//let's make sure default_where strategy is followed now
1412
			$this->_ignore_where_strategy = FALSE;
1413
		}
1414
		//if we want to keep model objects in sync, AND
1415
		//if this wasn't called from a model object (to update itself)
1416
		//then we want to make sure we keep all the existing
1417
		//model objects in sync with the db
1418
		if( $keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object ){
1419
			if( $this->has_primary_key_field() ){
1420
				$model_objs_affected_ids = $this->get_col( $query_params );
1421
			}else{
1422
				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1423
				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A );
1424
				$model_objs_affected_ids = array();
1425
				foreach( $models_affected_key_columns as $row ){
1426
					$combined_index_key = $this->get_index_primary_key_string( $row );
1427
					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1428
				}
1429
1430
			}
1431
1432
			if( ! $model_objs_affected_ids ){
0 ignored issues
show
Bug Best Practice introduced by
The expression $model_objs_affected_ids of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1433
				//wait wait wait- if nothing was affected let's stop here
1434
				return 0;
1435
			}
1436
			foreach( $model_objs_affected_ids as $id ){
1437
				$model_obj_in_entity_map = $this->get_from_entity_map( $id );
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $model_obj_in_entity_map is correct as $this->get_from_entity_map($id) (which targets EEM_Base::get_from_entity_map()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1438
				if( $model_obj_in_entity_map ){
1439
					foreach( $fields_n_values as $field => $new_value ){
1440
						$model_obj_in_entity_map->set( $field, $new_value );
1441
					}
1442
				}
1443
			}
1444
			//if there is a primary key on this model, we can now do a slight optimization
1445
			if( $this->has_primary_key_field() ){
1446
				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1447
				$query_params = array(
1448
					array( $this->primary_key_name() => array( 'IN', $model_objs_affected_ids ) ),
1449
					'limit' => count( $model_objs_affected_ids ), 'default_where_conditions' => 'none' );
1450
			}
1451
		}
1452
1453
		$model_query_info = $this->_create_model_query_info_carrier( $query_params );
1454
		$SQL = "UPDATE ".$model_query_info->get_full_join_sql()." SET ".$this->_construct_update_sql($fields_n_values).$model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1455
		$rows_affected = $this->_do_wpdb_query('query', array( $SQL ) );
1456
		/**
1457
		 * Action called after a model update call has been made.
1458
		 *
1459
		 * @param EEM_Base $model
1460
		 * @param array $fields_n_values the updated fields and their new values
1461
		 * @param array $query_params @see EEM_Base::get_all()
1462
		 * @param int $rows_affected
1463
		 */
1464
		do_action( 'AHEE__EEM_Base__update__end',$this, $fields_n_values, $query_params, $rows_affected );
1465
		return $rows_affected;//how many supposedly got updated
1466
	}
1467
1468
	/**
1469
	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1470
	 * are teh values of the field specified (or by default the primary key field)
1471
	 * that matched the query params. Note that you should pass the name of the
1472
	 * model FIELD, not the database table's column name.
1473
	 * @param array $query_params @see EEM_Base::get_all()
1474
	 * @param string $field_to_select
1475
	 * @return array just like $wpdb->get_col()
1476
	 */
1477
	public function get_col( $query_params  = array(), $field_to_select = NULL ){
1478
1479
		if( $field_to_select ){
0 ignored issues
show
Bug Best Practice introduced by
The expression $field_to_select of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1480
			$field = $this->field_settings_for( $field_to_select );
1481
		}elseif( $this->has_primary_key_field ( ) ){
1482
			$field = $this->get_primary_key_field();
1483
		}else{
1484
			//no primary key, just grab the first column
1485
			$field = reset( $this->field_settings());
0 ignored issues
show
Bug introduced by
$this->field_settings() cannot be passed to reset() as the parameter $array expects a reference.
Loading history...
1486
		}
1487
1488
1489
		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1490
		$select_expressions = $field->get_qualified_column();
1491
		$SQL ="SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1492
		$results =  $this->_do_wpdb_query('get_col', array( $SQL ) );
1493
		return $results;
1494
	}
1495
1496
	/**
1497
	 * Returns a single column value for a single row from the database
1498
	 * @param array $query_params @see EEM_Base::get_all()
1499
	 * @param string $field_to_select @see EEM_Base::get_col()
1500
	 * @return string
1501
	 */
1502
	public function get_var( $query_params = array(), $field_to_select = NULL ) {
1503
		$query_params[ 'limit' ] = 1;
1504
		$col = $this->get_col( $query_params, $field_to_select );
1505
		if( ! empty( $col ) ) {
1506
			return reset( $col );
1507
		}else{
1508
			return NULL;
1509
		}
1510
	}
1511
1512
1513
1514
	/**
1515
	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party time?', Question.desc='what do you think?',..."
1516
	 * Values are filtered through wpdb->prepare to avoid against SQL injection, but currently no further filtering is done
1517
	 * @global $wpdb
1518
	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should be updated to in the DB
1519
	 * @return string of SQL
1520
	 */
1521
	function _construct_update_sql($fields_n_values){
1522
		/** @type WPDB $wpdb */
1523
		global $wpdb;
1524
		$cols_n_values = array();
1525
		foreach($fields_n_values as $field_name => $value){
1526
			$field_obj = $this->field_settings_for($field_name);
1527
			//if the value is NULL, we want to assign the value to that.
1528
			//wpdb->prepare doesn't really handle that properly
1529
			$prepared_value = $this->_prepare_value_or_use_default( $field_obj, $fields_n_values );
1530
			$value_sql = $prepared_value===NULL ? 'NULL' : $wpdb->prepare( $field_obj->get_wpdb_data_type(), $prepared_value );
1531
			$cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1532
		}
1533
		return implode(",",$cols_n_values);
1534
1535
	}
1536
1537
	/**
1538
	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1539
	 * Performs a HARD delete, meaning the database row should always be removed,
1540
	 * not just have a flag field on it switched
1541
	 * Wrapper for EEM_Base::delete_permanently()
1542
	 * @param mixed $id
1543
	 * @return boolean whether the row got deleted or not
1544
	 */
1545
	public function delete_permanently_by_ID( $id ) {
1546
		return $this->delete_permanently(
1547
			array(
1548
				array( $this->get_primary_key_field()->get_name() => $id ),
1549
				'limit' 	=> 1
1550
			)
1551
		);
1552
	}
1553
1554
1555
1556
	/**
1557
	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1558
	 * Wrapper for EEM_Base::delete()
1559
	 * @param mixed $id
1560
	 * @return boolean whether the row got deleted or not
1561
	 */
1562
	public function delete_by_ID( $id ){
1563
		return $this->delete(
1564
			array(
1565
				array( $this->get_primary_key_field()->get_name() => $id ),
1566
				'limit' 	=> 1
1567
			)
1568
		);
1569
	}
1570
1571
	/**
1572
	 * Identical to delete_permanently, but does a "soft" delete if possible,
1573
	 * meaning if the model has a field that indicates its been "trashed" or
1574
	 * "soft deleted", we will just set that instead of actually deleting the rows.
1575
	 * @param array $query_params
1576
	 * @param boolean $allow_blocking
1577
	 * @return @see EEM_Base::delete_permanently
0 ignored issues
show
Documentation introduced by
The doc-type @see could not be parsed: Unknown type name "@see" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1578
	 */
1579
	function delete($query_params,$allow_blocking = true){
1580
		return $this->delete_permanently($query_params, $allow_blocking);
1581
	}
1582
1583
1584
1585
	/**
1586
	 * Deletes the model objects that meet the query params. Note: this method is overridden
1587
	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1588
	 * as archived, not actually deleted
1589
	 * @param array $query_params very much like EEM_Base::get_all's $query_params
1590
	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1591
	 * that blocks it (ie, there' sno other data that depends on this data); if false, deletes regardless of other objects
1592
	 * which may depend on it. Its generally advisable to always leave this as TRUE, otherwise you could easily corrupt your DB
1593
	 * @return int how many rows got deleted
1594
	 */
1595
	function delete_permanently($query_params,$allow_blocking = true){
1596
		/**
1597
		 * Action called just before performing a real deletion query. You can use the
1598
		 * model and its $query_params to find exactly which items will be deleted
1599
		 * @param EEM_Base $model
1600
		 * @param array $query_params @see EEM_Base::get_all()
1601
		 * @param boolean $allow_blocking whether or not to allow related model objects
1602
		 * to block (prevent) this deletion
1603
		 */
1604
		do_action( 'AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking );
1605
		//some MySQL databases may be running safe mode, which may restrict
1606
		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1607
		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1608
		//to delete them
1609
		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1610
		$deletion_where = $this->_setup_ids_for_delete( $items_for_deletion, $allow_blocking);
1611
		if($deletion_where){
1612
			//echo "objects for deletion:";var_dump($objects_for_deletion);
1613
			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1614
			$table_aliases = array();
1615
			foreach(array_keys($this->_tables) as $table_alias){
1616
				$table_aliases[] = $table_alias;
1617
			}
1618
			$SQL = "DELETE ".implode(", ",$table_aliases)." FROM ".$model_query_info->get_full_join_sql()." WHERE ".$deletion_where;
1619
1620
			//		/echo "delete sql:$SQL";
1621
			$rows_deleted = $this->_do_wpdb_query( 'query', array( $SQL ) );
1622
		}else{
1623
			$rows_deleted = 0;
1624
		}
1625
1626
		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1627
		if( $this->has_primary_key_field() ){
1628
			foreach($items_for_deletion as $item_for_deletion_row ){
1629
				$pk_value = $item_for_deletion_row[ $this->get_primary_key_field()->get_qualified_column() ];
1630
				if( isset( $this->_entity_map[ $pk_value ] ) ){
1631
					unset( $this->_entity_map[ $pk_value ] );
1632
				}
1633
			}
1634
		}
1635
1636
		/**
1637
		 * Action called just after performing a real deletion query. Although at this point the
1638
		 * items should have been deleted
1639
		 * @param EEM_Base $model
1640
		 * @param array $query_params @see EEM_Base::get_all()
1641
		 * @param int $rows_deleted
1642
		 */
1643
		do_action( 'AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted );
1644
		return $rows_deleted;//how many supposedly got deleted
1645
	}
1646
1647
1648
1649
	/**
1650
	 * Checks all the relations that throw error messages when there are blocking related objects
1651
	 * for related model objects. If there are any related model objects on those relations,
1652
	 * adds an EE_Error, and return true
1653
	 * @param EE_Base_Class|int $this_model_obj_or_id
1654
	 * @param EE_Base_Class $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which should be ignored when
1655
	 * determining whether there are related model objects which block this model object's deletion. Useful
1656
	 * if you know A is related to B and are considering deleting A, but want to see if A has any other objects
1657
	 * blocking its deletion before removing the relation between A and B
1658
	 * @return boolean
1659
	 */
1660
	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null){
1661
		//first, if $ignore_this_model_obj was supplied, get its model
1662
		if($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class){
1663
			$ignored_model = $ignore_this_model_obj->get_model();
1664
		}else{
1665
			$ignored_model = null;
1666
		}
1667
		//now check all the relations of $this_model_obj_or_id and see if there
1668
		//are any related model objects blocking it?
1669
		$is_blocked = false;
1670
		foreach($this->_model_relations as $relation_name => $relation_obj){
1671
			if( $relation_obj->block_delete_if_related_models_exist()){
1672
				//if $ignore_this_model_obj was supplied, then for the query
1673
				//on that model needs to be told to ignore $ignore_this_model_obj
1674
				if($ignored_model && $relation_name == $ignored_model->get_this_model_name()){
0 ignored issues
show
Bug introduced by
The method get_this_model_name cannot be called on $ignored_model (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1675
					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id,array(
1676
					array($ignored_model->get_primary_key_field()->get_name() => array('!=',$ignore_this_model_obj->ID()))));
0 ignored issues
show
Bug introduced by
The method get_primary_key_field cannot be called on $ignored_model (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
Bug introduced by
It seems like $ignore_this_model_obj is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
1677
				}else{
1678
					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1679
				}
1680
1681
				if($related_model_objects){
0 ignored issues
show
Bug Best Practice introduced by
The expression $related_model_objects of type EE_Base_Class[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1682
					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1683
					$is_blocked = true;
1684
				}
1685
			}
1686
		}
1687
		return $is_blocked;
1688
	}
1689
1690
1691
1692
	/**
1693
	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as well.
1694
	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1695
	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model info
1696
	 * that blocks it (ie, there' sno other data that depends on this data); if false, deletes regardless of other objects
1697
	 * which may depend on it. Its generally advisable to always leave this as TRUE, otherwise you could easily corrupt your DB
1698
	 * @throws EE_Error
1699
	 * @return string    everything that comes after the WHERE statement.
1700
	 */
1701
	protected function _setup_ids_for_delete( $objects_for_deletion, $allow_blocking = true) {
1702
		if($this->has_primary_key_field()){
1703
			$primary_table = $this->_get_main_table();
1704
			$other_tables = $this->_get_other_tables();
1705
			$deletes = $query = array();
1706
			foreach ( $objects_for_deletion as $delete_object ) {
1707
				//before we mark this object for deletion,
1708
				//make sure there's no related objects blocking its deletion (if we're checking)
1709
				if( $allow_blocking && $this->delete_is_blocked_by_related_models($delete_object[$primary_table->get_fully_qualified_pk_column()]) ){
1710
					continue;
1711
				}
1712
1713
				//primary table deletes
1714
				if ( isset( $delete_object[$primary_table->get_fully_qualified_pk_column()] ) )
1715
					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
1716
1717
				//other tables
1718
				if ( !empty( $other_tables ) ) {
1719
					foreach ( $other_tables as $ot ) {
1720
1721
						//first check if we've got the foreign key column here.
1722 View Code Duplication
						if ( isset( $delete_object[$ot->get_fully_qualified_fk_column()] ) )
1723
							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
1724
1725
						//wait! it's entirely possible that we'll have a the primary key for this table in here if it's a foreign key for one of the other secondary tables
1726 View Code Duplication
						if ( isset( $delete_object[$ot->get_fully_qualified_pk_column()] ) )
1727
							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1728
1729
						//finally, it is possible that the fk for this table is found in the fully qualified pk column for the fk table, so let's see if that's there!
1730 View Code Duplication
						if ( isset( $delete_object[$ot->get_fully_qualified_pk_on_fk_table()]) )
1731
							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1732
					}
1733
				}
1734
			}
1735
1736
			//we should have deletes now, so let's just go through and setup the where statement
1737
			foreach ( $deletes as $column => $values ) {
1738
				//make sure we have unique $values;
1739
				$values = array_unique($values);
1740
				$query[] = $column . ' IN(' . implode(",",$values) . ')';
1741
			}
1742
1743
			return !empty($query) ? implode(' AND ', $query ) : '';
1744
		}elseif(count($this->get_combined_primary_key_fields()) > 1){
1745
			$ways_to_identify_a_row = array();
1746
			$fields = $this->get_combined_primary_key_fields();
1747
			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
1748
			foreach($objects_for_deletion as  $delete_object){
1749
				$values_for_each_cpk_for_a_row = array();
1750
				foreach($fields as $cpk_field){
1751
					$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()."=".$delete_object[$cpk_field->get_qualified_column()];
1752
				}
1753
				$ways_to_identify_a_row[] = "(".implode(" AND ",$values_for_each_cpk_for_a_row).")";
1754
			}
1755
			return implode(" OR ",$ways_to_identify_a_row);
1756
		}else{
1757
			//so there's no primary key and no combined key...
1758
			//sorry, can't help you
1759
			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key", "event_espresso"),get_class($this)));
1760
		}
1761
	}
1762
1763
1764
1765
	/**
1766
	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
1767
	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's column
1768
	 * @param array $query_params like EEM_Base::get_all's
1769
	 * @param string $field_to_count field on model to count by (not column name)
1770
	 * @param bool 	 $distinct if we want to only count the distinct values for the column then you can trigger that by the setting $distinct to TRUE;
1771
	 * @return int
1772
	 */
1773
	function count($query_params =array(),$field_to_count = NULL, $distinct = FALSE){
1774
		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1775
		if($field_to_count){
0 ignored issues
show
Bug Best Practice introduced by
The expression $field_to_count of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1776
			$field_obj = $this->field_settings_for($field_to_count);
1777
			$column_to_count = $field_obj->get_qualified_column();
1778
		}elseif($this->has_primary_key_field ()){
1779
			$pk_field_obj = $this->get_primary_key_field();
1780
			$column_to_count = $pk_field_obj->get_qualified_column();
1781
		}else{//there's no primary key
1782
			$column_to_count = '*';
1783
		}
1784
1785
		$column_to_count = $distinct ? "DISTINCT (" . $column_to_count . " )" : $column_to_count;
1786
		$SQL ="SELECT COUNT(".$column_to_count.")" . $this->_construct_2nd_half_of_select_query($model_query_info);
1787
		return (int)$this->_do_wpdb_query( 'get_var', array( $SQL) );
1788
	}
1789
1790
	/**
1791
	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
1792
	 *
1793
	 * @param array $query_params like EEM_Base::get_all
1794
	 * @param string $field_to_sum name of field (array key in $_fields array)
1795
	 * @return float
1796
	 */
1797
	function sum($query_params, $field_to_sum = NULL){
1798
		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1799
1800
		if($field_to_sum){
0 ignored issues
show
Bug Best Practice introduced by
The expression $field_to_sum of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1801
			$field_obj = $this->field_settings_for($field_to_sum);
1802
1803
		}else{
1804
			$field_obj = $this->get_primary_key_field();
1805
		}
1806
		$column_to_count = $field_obj->get_qualified_column();
1807
1808
		$SQL ="SELECT SUM(".$column_to_count.")" . $this->_construct_2nd_half_of_select_query($model_query_info);
1809
		$return_value = $this->_do_wpdb_query('get_var',array( $SQL ) );
1810
		if($field_obj->get_wpdb_data_type() == '%d' || $field_obj->get_wpdb_data_type() == '%s' ){
1811
			return (float)$return_value;
1812
		}else{//must be %f
1813
			return (float)$return_value;
1814
		}
1815
	}
1816
1817
1818
1819
	/**
1820
	 * Just calls the specified method on $wpdb with the given arguments
1821
	 * Consolidates a little extra error handling code
1822
	 * @param string $wpdb_method
1823
	 * @param array  $arguments_to_provide
1824
	 * @throws EE_Error
1825
	 * @global wpdb $wpdb
1826
	 * @return mixed
1827
	 */
1828
	protected function _do_wpdb_query( $wpdb_method, $arguments_to_provide ){
1829
		//if we're in maintenance mode level 2, DON'T run any queries
1830
		//because level 2 indicates the database needs updating and
1831
		//is probably out of sync with the code
1832
		if( ! EE_Maintenance_Mode::instance()->models_can_query()){
1833
			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.", "event_espresso")));
1834
		}
1835
		/** @type WPDB $wpdb */
1836
		global $wpdb;
1837 View Code Duplication
		if( ! method_exists( $wpdb, $wpdb_method ) ){
1838
			throw new EE_Error( sprintf( __( 'There is no method named "%s" on Wordpress\' $wpdb object','event_espresso' ), $wpdb_method ) );
1839
		}
1840
		if( WP_DEBUG ){
1841
			$old_show_errors_value = $wpdb->show_errors;
1842
			$wpdb->show_errors( FALSE );
1843
		}
1844
		$result = $this->_process_wpdb_query( $wpdb_method, $arguments_to_provide );
1845
		$this->show_db_query_if_previously_requested( $wpdb->last_query );
1846
		if( WP_DEBUG ){
1847
			$wpdb->show_errors( $old_show_errors_value );
0 ignored issues
show
Bug introduced by
The variable $old_show_errors_value does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1848
			if( ! empty( $wpdb->last_error ) ){
1849
				throw new EE_Error( sprintf( __( 'WPDB Error: "%s"', 'event_espresso' ), $wpdb->last_error ) );
1850
			}elseif( $result === false ){
1851
				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"', 'event_espresso' ), $wpdb_method, var_export( $arguments_to_provide, true ) ) );
1852
			}
1853
		}elseif( $result === false ) {
1854
			EE_Error::add_error( sprintf( __( 'A database error has occurred. Turn on WP_DEBUG for more information.', 'event_espresso' )), __FILE__, __FUNCTION__, __LINE__);
1855
		}
1856
		return $result;
1857
	}
1858
1859
1860
1861
	/**
1862
	 * Attempts to run the indicated WPDB method with the provided arguments,
1863
	 * and if there's an error tries to verify the DB is correct. Uses
1864
	 * the static property EEM_Base::$_db_verification_level to determine whether
1865
	 * we should try to fix the EE core db, the addons, or just give up
1866
	 * @param string $wpdb_method
1867
	 * @param array $arguments_to_provide
1868
	 * @return mixed
1869
	 */
1870
	private function _process_wpdb_query( $wpdb_method, $arguments_to_provide ) {
1871
		/** @type WPDB $wpdb */
1872
		global $wpdb;
1873
		$wpdb->last_error = null;
1874
		$result = call_user_func_array( array( $wpdb, $wpdb_method ), $arguments_to_provide );
1875
		// was there an error running the query? but we don't care on new activations
1876
		// (we're going to setup the DB anyway on new activations)
1877
		if ( ( $result === false || ! empty( $wpdb->last_error ) )
1878
			&& EE_System::instance()->detect_req_type() != EE_System::req_type_new_activation
1879
		) {
1880
			switch ( EEM_Base::$_db_verification_level ) {
1881
1882
				case EEM_Base::db_verified_none :
1883
					// let's double-check core's DB
1884
					$error_message = $this->_verify_core_db( $wpdb_method, $arguments_to_provide );
1885
					break;
1886
1887
				case EEM_Base::db_verified_core :
1888
					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
1889
					$error_message = $this->_verify_addons_db( $wpdb_method, $arguments_to_provide );
1890
					break;
1891
1892
				case EEM_Base::db_verified_addons :
1893
					// ummmm... you in trouble
1894
					return $result;
1895
					break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1896
			}
1897
			if ( ! empty( $error_message ) ) {
1898
				EE_Log::instance()->log( __FILE__, __FUNCTION__, $error_message, 'error' );
1899
				trigger_error( $error_message );
1900
			}
1901
			return $this->_process_wpdb_query( $wpdb_method, $arguments_to_provide );
1902
1903
		}
1904
1905
		return $result;
1906
	}
1907
1908
1909
1910
	/**
1911
	 * Verifies the EE core database is up-to-date and records that we've done it on
1912
	 * EEM_Base::$_db_verification_level
1913
	 * @param string $wpdb_method
1914
	 * @param array $arguments_to_provide
1915
	 * @return string
1916
	 */
1917 View Code Duplication
	private function _verify_core_db( $wpdb_method, $arguments_to_provide ){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1918
		/** @type WPDB $wpdb */
1919
		global $wpdb;
1920
		//ok remember that we've already attempted fixing the core db, in case the problem persists
1921
		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
1922
		$error_message = sprintf(
1923
			__( 'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB', 'event_espresso' ),
1924
			$wpdb->last_error,
1925
			$wpdb_method,
1926
			json_encode( $arguments_to_provide )
1927
		);
1928
		EE_System::instance()->initialize_db_if_no_migrations_required( false, true );
1929
		return $error_message;
1930
	}
1931
1932
1933
1934
	/**
1935
	 * Verifies the EE addons' database is up-to-date and records that we've done it on
1936
	 * EEM_Base::$_db_verification_level
1937
	 * @param $wpdb_method
1938
	 * @param $arguments_to_provide
1939
	 * @return string
1940
	 */
1941 View Code Duplication
	private function _verify_addons_db( $wpdb_method, $arguments_to_provide ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1942
		/** @type WPDB $wpdb */
1943
		global $wpdb;
1944
		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
1945
		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
1946
		$error_message = sprintf(
1947
			__( 'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB', 'event_espresso' ),
1948
			$wpdb->last_error,
1949
			$wpdb_method,
1950
			json_encode( $arguments_to_provide )
1951
		);
1952
		EE_System::instance()->initialize_addons();
1953
		return $error_message;
1954
	}
1955
1956
1957
1958
	/**
1959
	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
1960
	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
1961
	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING ..."
1962
	 * @param EE_Model_Query_Info_Carrier $model_query_info
1963
	 * @return string
1964
	 */
1965
	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info){
1966
		return " FROM ".$model_query_info->get_full_join_sql().
1967
				$model_query_info->get_where_sql().
1968
				$model_query_info->get_group_by_sql().
1969
				$model_query_info->get_having_sql().
1970
				$model_query_info->get_order_by_sql().
1971
				$model_query_info->get_limit_sql();
1972
	}
1973
1974
	/**
1975
	 * Set to easily debug the next X queries ran from this model.
1976
	 * @param int $count
1977
	 */
1978
	function show_next_x_db_queries($count = 1){
1979
		$this->_show_next_x_db_queries = $count;
1980
	}
1981
1982
1983
1984
	/**
1985
	 * @param $sql_query
1986
	 */
1987
	function show_db_query_if_previously_requested($sql_query){
1988
		if($this->_show_next_x_db_queries > 0){
1989
			echo $sql_query;
1990
			$this->_show_next_x_db_queries--;
1991
		}
1992
	}
1993
1994
	/**
1995
	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
1996
	 * There are the 3 cases:
1997
	 *
1998
	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If $otherModelObject has no ID, it is first saved.
1999
	 *
2000
	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj has no ID, it is first saved.
2001
	 *
2002
	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2003
	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the join table
2004
	 *
2005
	 * @param EE_Base_Class/int $thisModelObject
0 ignored issues
show
Documentation introduced by
The doc-type EE_Base_Class/int could not be parsed: Unknown type name "EE_Base_Class/int" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
Bug introduced by
There is no parameter named $thisModelObject. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
2006
	 * @param EE_Base_Class/int $id_or_obj EE_base_Class or ID of other Model Object
0 ignored issues
show
Documentation introduced by
The doc-type EE_Base_Class/int could not be parsed: Unknown type name "EE_Base_Class/int" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
2007
	 * @param string $relationName, key in EEM_Base::_relations
0 ignored issues
show
Documentation introduced by
There is no parameter named $relationName,. Did you maybe mean $relationName?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
2008
	 * an attendee to a group, you also want to specify which role they will have in that group. So you would use this parameter to specify array('role-column-name'=>'role-id')
2009
	 * @param array   $extra_join_model_fields_n_values This allows you to enter further query params for the relation to for relation to methods that allow you to further specify extra columns to join by (such as HABTM).  Keep in mind that the only acceptable query_params is strict "col" => "value" pairs because these will be inserted in any new rows created as well.
2010
	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2011
	 */
2012
	public function add_relationship_to($id_or_obj,$other_model_id_or_obj, $relationName, $extra_join_model_fields_n_values = array()){
2013
		$relation_obj = $this->related_settings_for($relationName);
2014
		return $relation_obj->add_relation_to( $id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
0 ignored issues
show
Unused Code introduced by
The call to EE_Model_Relation_Base::add_relation_to() has too many arguments starting with $extra_join_model_fields_n_values.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2015
	}
2016
2017
	/**
2018
	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2019
	 * There are the 3 cases:
2020
	 *
2021
	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an error
2022
	 *
2023
	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws an error
2024
	 *
2025
	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2026
	 *
2027
	 * @param EE_Base_Class/int $id_or_obj
0 ignored issues
show
Documentation introduced by
The doc-type EE_Base_Class/int could not be parsed: Unknown type name "EE_Base_Class/int" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
2028
	 * @param EE_Base_Class/int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
0 ignored issues
show
Documentation introduced by
The doc-type EE_Base_Class/int could not be parsed: Unknown type name "EE_Base_Class/int" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
2029
	 * @param string $relationName key in EEM_Base::_relations
2030
	 * @return boolean of success
2031
	 * @param array   $where_query This allows you to enter further query params for the relation to for relation to methods that allow you to further specify extra columns to join by (such as HABTM).  Keep in mind that the only acceptable query_params is strict "col" => "value" pairs because these will be inserted in any new rows created as well.
2032
	 */
2033
	public function remove_relationship_to($id_or_obj,  $other_model_id_or_obj, $relationName, $where_query= array() ){
2034
		$relation_obj = $this->related_settings_for($relationName);
2035
		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query );
0 ignored issues
show
Unused Code introduced by
The call to EE_Model_Relation_Base::remove_relation_to() has too many arguments starting with $where_query.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2036
	}
2037
2038
2039
2040
	/**
2041
	 *
2042
	 * @param mixed  $id_or_obj
2043
	 * @param string $relationName
2044
	 * @param array  $where_query_params
2045
	 * @param EE_Base_Class[] objects to which relations were removed
2046
	 * @return \EE_Base_Class[]
2047
	 */
2048
	public function remove_relations($id_or_obj,$relationName,$where_query_params = array()){
2049
		$relation_obj = $this->related_settings_for($relationName);
2050
		return $relation_obj->remove_relations($id_or_obj, $where_query_params );
2051
	}
2052
2053
2054
	/**
2055
	 * Gets all the related items of the specified $model_name, using $query_params.
2056
	 * Note: by default, we remove the "default query params"
2057
	 * because we want to get even deleted items etc.
2058
	 * @param mixed $id_or_obj EE_Base_Class child or its ID
2059
	 * @param string $model_name like 'Event', 'Registration', etc. always singular
2060
	 * @param array $query_params like EEM_Base::get_all
2061
	 * @return EE_Base_Class[]
2062
	 */
2063
	function get_all_related($id_or_obj, $model_name, $query_params = null){
2064
		$model_obj = $this->ensure_is_obj($id_or_obj);
2065
		$relation_settings = $this->related_settings_for($model_name);
2066
		return $relation_settings->get_all_related($model_obj,$query_params);
0 ignored issues
show
Bug introduced by
It seems like $query_params defined by parameter $query_params on line 2063 can also be of type null; however, EE_Model_Relation_Base::get_all_related() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
2067
	}
2068
2069
	/**
2070
	 * Deletes all the model objects across the relation indicated by $model_name
2071
	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2072
	 * However, if the model objects can't be deleted because of blocking related model objects, then
2073
	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2074
	 * @param EE_Base_Class|int|string $id_or_obj
2075
	 * @param string $model_name
2076
	 * @param array $query_params
2077
	 * @return int how many deleted
2078
	 */
2079
	public function delete_related($id_or_obj,$model_name, $query_params = array()){
2080
		$model_obj = $this->ensure_is_obj($id_or_obj);
2081
		$relation_settings = $this->related_settings_for($model_name);
2082
		return $relation_settings->delete_all_related($model_obj,$query_params);
2083
	}
2084
2085
	/**
2086
	 * Hard deletes all the model objects across the relation indicated by $model_name
2087
	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2088
	 * the model objects can't be hard deleted because of blocking related model objects,
2089
	 * just does a soft-delete on them instead.
2090
	 * @param EE_Base_Class|int|string $id_or_obj
2091
	 * @param string $model_name
2092
	 * @param array $query_params
2093
	 * @return int how many deleted
2094
	 */
2095
	public function delete_related_permanently($id_or_obj,$model_name, $query_params = array()){
2096
		$model_obj = $this->ensure_is_obj($id_or_obj);
2097
		$relation_settings = $this->related_settings_for($model_name);
2098
		return $relation_settings->delete_related_permanently($model_obj,$query_params);
2099
	}
2100
2101
	/**
2102
	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2103
	 * unless otherwise specified in the $query_params
2104
	 * @param int/EE_Base_Class $id_or_obj
0 ignored issues
show
Documentation introduced by
The doc-type int/EE_Base_Class could not be parsed: Unknown type name "int/EE_Base_Class" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
2105
	 * @param string $model_name like 'Event', or 'Registration'
2106
	 * @param array $query_params like EEM_Base::get_all's
2107
	 * @param string $field_to_count name of field to count by. By default, uses primary key
2108
	 * @param bool 	 $distinct if we want to only count the distinct values for the column then you can trigger that by the setting $distinct to TRUE;
2109
	 * @return int
2110
	 */
2111
	function count_related($id_or_obj,$model_name,$query_params = array(),$field_to_count = null, $distinct = FALSE){
2112
		$related_model = $this->get_related_model_obj($model_name);
2113
		//we're just going to use the query params on the related model's normal get_all query,
2114
		//except add a condition to say to match the current mod
2115
		if( ! isset($query_params['default_where_conditions'])){
2116
			$query_params['default_where_conditions']='none';
2117
		}
2118
		$this_model_name = $this->get_this_model_name();
2119
		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2120
		$query_params[0][$this_model_name.".".$this_pk_field_name]=$id_or_obj;
2121
		return $related_model->count($query_params,$field_to_count,$distinct);
2122
	}
2123
2124
2125
2126
	/**
2127
	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2128
	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2129
	 * @param int/EE_Base_Class $id_or_obj
0 ignored issues
show
Documentation introduced by
The doc-type int/EE_Base_Class could not be parsed: Unknown type name "int/EE_Base_Class" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
2130
	 * @param string $model_name like 'Event', or 'Registration'
2131
	 * @param array $query_params like EEM_Base::get_all's
2132
	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2133
	 * @return float
2134
	 */
2135
	function sum_related($id_or_obj,$model_name,$query_params,$field_to_sum = null){
2136
		$related_model = $this->get_related_model_obj($model_name);
2137
		if( ! is_array( $query_params ) ){
2138
			EE_Error::doing_it_wrong('EEM_Base::sum_related', sprintf( __( '$query_params should be an array, you passed a variable of type %s', 'event_espresso' ), gettype( $query_params ) ), '4.6.0' );
2139
			$query_params = array();
2140
		}
2141
		//we're just going to use the query params on the related model's normal get_all query,
2142
		//except add a condition to say to match the current mod
2143
		if( ! isset($query_params['default_where_conditions'])){
2144
			$query_params['default_where_conditions']='none';
2145
		}
2146
		$this_model_name = $this->get_this_model_name();
2147
		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2148
		$query_params[0][$this_model_name.".".$this_pk_field_name]=$id_or_obj;
2149
		return $related_model->sum($query_params,$field_to_sum);
2150
	}
2151
2152
2153
2154
	/**
2155
	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given $modelObject
2156
	 * @param int | EE_Base_Class  $id_or_obj EE_Base_Class child or its ID
2157
	 * @param string $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2158
	 * @param array $query_params like EEM_Base::get_all's
2159
	 * @return EE_Base_Class
2160
	 */
2161
	public function get_first_related( EE_Base_Class $id_or_obj, $other_model_name, $query_params ){
2162
		$query_params['limit']=1;
2163
		$results = $this->get_all_related($id_or_obj,$other_model_name,$query_params);
2164
		if( $results ){
0 ignored issues
show
Bug Best Practice introduced by
The expression $results of type EE_Base_Class[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2165
			return array_shift($results);
2166
		}else{
2167
			return null;
2168
		}
2169
2170
	}
2171
2172
	/**
2173
	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2174
	 * @return string
2175
	 */
2176
	function get_this_model_name(){
2177
		return str_replace("EEM_","",get_class($this));
2178
	}
2179
2180
	/**
2181
	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2182
	 * @return EE_Any_Foreign_Model_Name_Field
2183
	 * @throws EE_Error
2184
	 */
2185
	public function get_field_containing_related_model_name(){
2186
		foreach($this->field_settings(true) as $field){
2187
			if($field instanceof EE_Any_Foreign_Model_Name_Field){
2188
				$field_with_model_name = $field;
2189
			}
2190
		}
2191 View Code Duplication
		if( !isset($field_with_model_name) || !$field_with_model_name ){
2192
			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"), $this->get_this_model_name() ));
2193
		}
2194
		return $field_with_model_name;
2195
	}
2196
2197
2198
2199
	/**
2200
	 * Inserts a new entry into the database, for each table.
2201
	 *
2202
	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2203
	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2204
	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2205
	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2206
	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2207
	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2208
	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if $values_already_prepared_by_model_object is false,
2209
	 * in the model object's domain if $values_already_prepared_by_model_object is true. See comment about this at the top of EEM_Base)
2210
	 * @return int new primary key on main table that got inserted
2211
	 * @throws EE_Error
2212
	 */
2213
	function insert($field_n_values){
2214
		/**
2215
		 * Filters the fields and their values before inserting an item using the models
2216
		 * @param array $fields_n_values keys are the fields and values are their new values
2217
		 * @param EEM_Base $model the model used
2218
		 */
2219
		$field_n_values = apply_filters( 'FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this );
2220
		if($this->_satisfies_unique_indexes($field_n_values)){
2221
			$main_table = $this->_get_main_table();
2222
			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2223
			if( $new_id !== false ) {
2224
				foreach($this->_get_other_tables() as $other_table){
2225
					$this->_insert_into_specific_table($other_table, $field_n_values,$new_id);
2226
				}
2227
			}
2228
			/**
2229
			 * Done just after attempting to insert a new model object
2230
			 *
2231
			 * @param EEM_Base $model used
2232
			 * @param array $fields_n_values fields and their values
2233
			 * @param int|string the ID of the newly-inserted model object
2234
			 */
2235
			do_action( 'AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id );
2236
			return $new_id;
2237
		}else{
2238
			return FALSE;
2239
		}
2240
	}
2241
2242
2243
2244
	/**
2245
	 * Checks that the result would satisfy the unique indexes on this model
2246
	 * @param array   $field_n_values
2247
	 * @param string $action
2248
	 * @return boolean
2249
	 */
2250
	protected function _satisfies_unique_indexes($field_n_values,$action = 'insert'){
2251
		foreach($this->unique_indexes() as $index_name => $index){
2252
			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2253
			if($this->exists(array($uniqueness_where_params))){
2254
				EE_Error::add_error(sprintf(__("Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.", "event_espresso"),$action,$this->_get_class_name(),$index_name,implode(",",$index->field_names()),http_build_query($uniqueness_where_params)), __FILE__, __FUNCTION__, __LINE__ );
2255
				return false;
2256
			}
2257
		}
2258
		return true;
2259
	}
2260
2261
2262
2263
	/**
2264
	 * Checks the database for an item that conflicts (ie, if this item were
2265
	 * saved to the DB would break some uniqueness requirement, like a primary key
2266
	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2267
	 * can be either an EE_Base_Class or an array of fields n values
2268
	 * @param EE_Base_Class|array|int|string $obj_or_fields_array
2269
	 * @param boolean $include_primary_key whether to use the model object's primary key when looking for conflicts
2270
	 * (ie, if false, we ignore the model object's primary key when finding "conflicts".
2271
	 * If true, it's also considered). Only works for INT primary key- STRING primary keys cannot be ignored
2272
	 * @throws EE_Error
2273
	 * @return EE_Base_Class
2274
	 */
2275
	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true ){
2276 View Code Duplication
		if($obj_or_fields_array instanceof EE_Base_Class){
2277
			$fields_n_values = $obj_or_fields_array->model_field_array();
2278
		}elseif( is_array($obj_or_fields_array)){
2279
			$fields_n_values = $obj_or_fields_array;
2280
		}else{
2281
			throw new EE_Error(sprintf(__("%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d", "event_espresso"),get_class($this),$obj_or_fields_array));
2282
		}
2283
		$query_params = array();
2284
		if( $this->has_primary_key_field() &&
2285
				( $include_primary_key || $this->get_primary_key_field() instanceof EE_Primary_Key_String_Field) &&
2286
				isset($fields_n_values[$this->primary_key_name()])){
2287
			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2288
		}
2289
		foreach($this->unique_indexes() as $unique_index_name=>$unique_index){
2290
			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2291
			$query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2292
		}
2293
		//if there is nothing to base this search on, then we shouldn't find anything
2294
		if( empty( $query_params ) ){
2295
			return array();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array(); (array) is incompatible with the return type documented by EEM_Base::get_one_conflicting of type EE_Base_Class|null.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
2296
		}else{
2297
			return $this->get_one($query_params);
2298
		}
2299
	}
2300
2301
	/**
2302
	 * Like count, but is optimized and returns a boolean instead of an int
2303
	 * @param array $query_params
2304
	 * @return boolean
2305
	 */
2306
	function exists($query_params){
2307
		$query_params['limit'] = 1;
2308
		return $this->count($query_params) > 0;
2309
	}
2310
2311
	/**
2312
	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2313
	 * @param int|string $id
2314
	 * @return boolean
2315
	 */
2316
	function exists_by_ID($id){
2317
		return $this->exists(array('default_where_conditions'=>'none', array($this->primary_key_name() => $id)));
2318
	}
2319
2320
2321
2322
	/**
2323
	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2324
	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2325
	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2326
	 * on the main table)
2327
	 * This is protected rather than private because private is not accessible to any child methods and there MAY be cases where we want to call it directly rather than via insert().
2328
	 * @access   protected
2329
	 * @param EE_Table_Base $table
2330
	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or float
2331
	 * @param int  $new_id 	for now we assume only int keys
2332
	 * @throws EE_Error
2333
	 * @global WPDB $wpdb only used to get the $wpdb->insert_id after performing an insert
2334
	 * @return int ID of new row inserted, or FALSE on failure
2335
	 */
2336
	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0 ){
2337
		global $wpdb;
2338
		$insertion_col_n_values = array();
2339
		$format_for_insertion = array();
2340
		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2341
		foreach($fields_on_table as $field_name => $field_obj){
0 ignored issues
show
Bug introduced by
The expression $fields_on_table of type object<EE_Model_Field_Base> is not traversable.
Loading history...
2342
			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2343
			if($field_obj->is_auto_increment()){
2344
				continue;
2345
			}
2346
			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2347
			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2348
			if( $prepared_value !== NULL ){
2349
				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2350
				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2351
			}
2352
		}
2353
2354
		if($table instanceof EE_Secondary_Table && $new_id){
2355
			//its not the main table, so we should have already saved the main table's PK which we just inserted
2356
			//so add the fk to the main table as a column
2357
			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2358
			$format_for_insertion[]='%d';//yes right now we're only allowing these foreign keys to be INTs
2359
		}
2360
		//insert the new entry
2361
		$result = $this->_do_wpdb_query( 'insert', array( $table->get_table_name(), $insertion_col_n_values, $format_for_insertion ) );
2362
		if( $result === false ) {
2363
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by EEM_Base::_insert_into_specific_table of type integer.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
2364
		}
2365
		//ok, now what do we return for the ID of the newly-inserted thing?
2366
		if($this->has_primary_key_field()){
2367
			if($this->get_primary_key_field()->is_auto_increment()){
2368
				return $wpdb->insert_id;
2369
			}else{
2370
				//it's not an auto-increment primary key, so
2371
				//it must have been supplied
2372
				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2373
			}
2374
		}else{
2375
			//we can't return a  primary key because there is none. instead return
2376
			//a unique string indicating this model
2377
			return $this->get_index_primary_key_string($fields_n_values);
2378
		}
2379
	}
2380
2381
	/**
2382
	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2383
	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2384
	 * and there is no default, we pass it along. WPDB will take care of it)
2385
	 * @param EE_Model_Field_Base $field_obj
2386
	 * @param array $fields_n_values
2387
	 * @return mixed string|int|float depending on what the table column will be expecting
2388
	 */
2389
	protected function _prepare_value_or_use_default( $field_obj, $fields_n_values ){
2390
		//if this field doesn't allow nullable, don't allow it
2391
		if( ! $field_obj->is_nullable() && (
2392
				! isset( $fields_n_values[ $field_obj->get_name() ] ) ||
2393
				$fields_n_values[ $field_obj->get_name() ] === NULL ) ){
2394
			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
2395
		}
2396
		$unprepared_value = isset( $fields_n_values[ $field_obj->get_name() ] ) ? $fields_n_values[ $field_obj->get_name() ] : NULL;
2397
		return $this->_prepare_value_for_use_in_db( $unprepared_value, $field_obj);
2398
	}
2399
2400
2401
	/**
2402
	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's prepare_for_use_in_db method on the value,
2403
	 * and depending on $value_already_prepare_by_model_obj, may also call the field's prepare_for_set() method.
2404
	 * @param mixed $value value in the client code domain if $value_already_prepared_by_model_object is false, otherwise a value
2405
	 * in the model object's domain (see lengthy comment at top of file)
2406
	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume $value is a custom selection
2407
	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2408
	 */
2409
	private function _prepare_value_for_use_in_db($value, $field){
2410
		if($field && $field instanceof EE_Model_Field_Base){
2411
			switch( $this->_values_already_prepared_by_model_object ){
2412
				/** @noinspection PhpMissingBreakStatementInspection */
2413
				case self::not_prepared_by_model_object:
2414
					$value = $field->prepare_for_set($value);
2415
					//purposefully left out "return"
2416
				case self::prepared_by_model_object:
2417
					$value = $field->prepare_for_use_in_db($value);
2418
				case self::prepared_for_use_in_db:
2419
					//leave the value alone
2420
			}
2421
			return $value;
2422
		}else{
2423
			return $value;
2424
		}
2425
	}
2426
2427
	/**
2428
	 * Returns the main table on this model
2429
	 * @return EE_Primary_Table
2430
	 * @throws EE_Error
2431
	 */
2432
	protected function _get_main_table(){
2433
		foreach($this->_tables as $table){
2434
			if($table instanceof EE_Primary_Table){
2435
				return $table;
2436
			}
2437
		}
2438
		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor','event_espresso'),get_class($this)));
2439
	}
2440
2441
	/**
2442
	 * table
2443
	 * returns EE_Primary_Table table name
2444
	 * @return string
2445
	 */
2446
	public function table() {
2447
		return $this->_get_main_table()->get_table_name();
2448
	}
2449
2450
	/**
2451
	 * table
2452
	 * returns first EE_Secondary_Table table name
2453
	 * @return string
2454
	 */
2455
	public function second_table() {
2456
		// grab second table from tables array
2457
		$second_table = end( $this->_tables );
2458
		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : NULL;
2459
	}
2460
2461
2462
2463
	/**
2464
	 * get_table_obj_by_alias
2465
	 * returns table name given it's alias
2466
	 *
2467
	 * @param string $table_alias
2468
	 * @return EE_Primary_Table | EE_Secondary_Table
2469
	 */
2470
	public function get_table_obj_by_alias( $table_alias = '' ) {
2471
		return isset( $this->_tables[ $table_alias ] ) ? $this->_tables[ $table_alias ] : NULL;
2472
	}
2473
2474
2475
2476
	/**
2477
	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
2478
	 * @return EE_Secondary_Table[]
2479
	 */
2480
	protected function _get_other_tables(){
2481
		$other_tables =array();
2482
		foreach($this->_tables as $table_alias => $table){
2483
			if($table instanceof EE_Secondary_Table){
2484
				$other_tables[$table_alias] = $table;
2485
			}
2486
		}
2487
		return $other_tables;
2488
	}
2489
2490
	/**
2491
	 * Finds all the fields that correspond to the given table
2492
	 * @param string $table_alias, array key in EEM_Base::_tables
0 ignored issues
show
Documentation introduced by
There is no parameter named $table_alias,. Did you maybe mean $table_alias?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
2493
	 * @return EE_Model_Field_Base[]
2494
	 */
2495
	function _get_fields_for_table($table_alias){
2496
		return $this->_fields[$table_alias];
2497
	}
2498
2499
	/**
2500
	 * Recurses through all the where parameters, and finds all the related models we'll need
2501
	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't need any
2502
	 * related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related Registration model.
2503
	 * If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the related Registration, Transaction, and Payment models.
2504
	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
2505
	 * @return EE_Model_Query_Info_Carrier
2506
	 */
2507
	function _extract_related_models_from_query($query_params){
2508
		$query_info_carrier = new EE_Model_Query_Info_Carrier();
2509
		if(array_key_exists(0,$query_params)){
2510
			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier,0);
2511
		}
2512 View Code Duplication
		if(array_key_exists('group_by', $query_params)){
2513
			if(is_array($query_params['group_by'])){
2514
				$this->_extract_related_models_from_sub_params_array_values($query_params['group_by'],$query_info_carrier,'group_by');
2515
			}elseif( ! empty ( $query_params['group_by'] )){
2516
				$this->_extract_related_model_info_from_query_param( $query_params['group_by'],$query_info_carrier,'group_by');
2517
			}
2518
		}
2519
		if(array_key_exists('having',$query_params)){
2520
			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier,'having');
2521
		}
2522 View Code Duplication
		if(array_key_exists('order_by', $query_params)){
2523
			if ( is_array( $query_params['order_by'] ) )
2524
				$this->_extract_related_models_from_sub_params_array_keys($query_params['order_by'],$query_info_carrier,'order_by');
2525
			elseif( ! empty( $query_params['order_by'] ))
2526
				$this->_extract_related_model_info_from_query_param( $query_params['order_by'], $query_info_carrier,'order_by');
2527
		}
2528
		if(array_key_exists('force_join', $query_params)){
2529
			$this->_extract_related_models_from_sub_params_array_values($query_params['force_join'],$query_info_carrier,'force_join');
2530
		}
2531
		return $query_info_carrier;
2532
	}
2533
2534
	/**
2535
	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
2536
	 * @param array $sub_query_params like EEM_Base::get_all's $query_params[0] or $query_params['having']
2537
	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
2538
	 * @param string                      $query_param_type one of $this->_allowed_query_params
2539
	 * @throws EE_Error
2540
	 * @return \EE_Model_Query_Info_Carrier
2541
	 */
2542
	private function _extract_related_models_from_sub_params_array_keys($sub_query_params, EE_Model_Query_Info_Carrier $model_query_info_carrier,$query_param_type){
2543
		if (!empty($sub_query_params)){
2544
			$sub_query_params = (array) $sub_query_params;
2545
			foreach($sub_query_params as $param => $possibly_array_of_params){
2546
				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
2547
				$this->_extract_related_model_info_from_query_param( $param, $model_query_info_carrier,$query_param_type);
2548
2549
				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
2550
				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
2551
				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
2552
				//of array('Registration.TXN_ID'=>23)
2553
				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
2554
				if(in_array($query_param_sans_stars, $this->_logic_query_param_keys,true)){
2555
					if (! is_array($possibly_array_of_params)){
2556
						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'))", "event_espresso"),
2557
							$param,$possibly_array_of_params));
2558
					}else{
2559
						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params, $model_query_info_carrier,$query_param_type);
2560
					}
2561
				}elseif($query_param_type === 0 //ie WHERE
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of $query_param_type (string) and 0 (integer) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
2562
						&& is_array($possibly_array_of_params)
2563
						&& isset($possibly_array_of_params[2])
2564
						&& $possibly_array_of_params[2] == true){
2565
					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
2566
					//indicating that $possible_array_of_params[1] is actually a field name,
2567
					//from which we should extract query parameters!
2568 View Code Duplication
					if(! isset($possibly_array_of_params[0]) || ! isset($possibly_array_of_params[1])){
2569
						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s", "event_espresso"),$query_param_type,implode(",",$possibly_array_of_params)));
2570
					}
2571
					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1], $model_query_info_carrier, $query_param_type);
2572
				}
2573
			}
2574
		}
2575
		return $model_query_info_carrier;
2576
	}
2577
2578
2579
	/**
2580
	 * For extracting related models from forced_joins, where the array values contain the info about what
2581
	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
2582
	 * @param array $sub_query_params like EEM_Base::get_all's $query_params[0] or $query_params['having']
2583
	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
2584
	 * @param string                      $query_param_type one of $this->_allowed_query_params
2585
	 * @throws EE_Error
2586
	 * @return \EE_Model_Query_Info_Carrier
2587
	 */
2588
	private function _extract_related_models_from_sub_params_array_values($sub_query_params, EE_Model_Query_Info_Carrier $model_query_info_carrier,$query_param_type){
2589
		if (!empty($sub_query_params)){
2590
			if(!is_array($sub_query_params)){
2591
				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),$sub_query_params));
2592
			}
2593
			foreach($sub_query_params as $param){
2594
				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
2595
				$this->_extract_related_model_info_from_query_param( $param, $model_query_info_carrier, $query_param_type);
2596
			}
2597
		}
2598
		return $model_query_info_carrier;
2599
	}
2600
2601
2602
2603
	/**
2604
	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
2605
	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
2606
	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
2607
	 * but use them in a different order. Eg, we need to know what models we are querying
2608
	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on other
2609
	 * models before we can finalize the where clause SQL.
2610
	 * @param array $query_params
2611
	 * @throws EE_Error
2612
	 * @return EE_Model_Query_Info_Carrier
2613
	 */
2614
	function _create_model_query_info_carrier($query_params){
2615
		if( ! is_array( $query_params ) ){
2616
			EE_Error::doing_it_wrong('EEM_Base::_create_model_query_info_carrier', sprintf( __( '$query_params should be an array, you passed a variable of type %s', 'event_espresso' ), gettype( $query_params ) ), '4.6.0' );
2617
			$query_params = array();
2618
		}
2619
		if( isset( $query_params[0] ) ) {
2620
			$where_query_params = $query_params[0];
2621
		}else{
2622
			$where_query_params = array();
2623
		}
2624
		//first check if we should alter the query to account for caps or not
2625
		//because the caps might require us to do extra joins
2626
		if( isset( $query_params[ 'caps' ] ) && $query_params[ 'caps' ] != 'none' ) {
2627
			$query_params[0] = $where_query_params = array_replace_recursive( $where_query_params, $this->caps_where_conditions( $query_params[ 'caps' ] ) );
2628
		}
2629
		$query_object = $this->_extract_related_models_from_query($query_params);
2630
2631
		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
2632
		foreach($where_query_params as $key => $value){
2633
			if(is_int($key)){
2634
				throw new EE_Error(sprintf(__("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.", "event_espresso"),$key, var_export( $value, true ), var_export( $query_params, true ), get_class($this)));
2635
			}
2636
		}
2637
		if( array_key_exists( 'default_where_conditions',$query_params) && ! empty( $query_params['default_where_conditions'] )){
2638
			$use_default_where_conditions = $query_params['default_where_conditions'];
2639
		}else{
2640
			$use_default_where_conditions = 'all';
2641
		}
2642
		$where_query_params = array_merge($this->_get_default_where_conditions_for_models_in_query($query_object,$use_default_where_conditions,$where_query_params), $where_query_params );
2643
		$query_object->set_where_sql( $this->_construct_where_clause($where_query_params));
2644
2645
2646
		//if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.  So we need to setup a subquery and use that for the main join.  Note for now this only works on the primary table for the model.  So for instance, you could set the limit array like this:
2647
		//array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
2648
		if ( array_key_exists('on_join_limit', $query_params ) && ! empty( $query_params['on_join_limit'] )) {
2649
			$query_object->set_main_model_join_sql( $this->_construct_limit_join_select( $query_params['on_join_limit'][0], $query_params['on_join_limit'][1] ) );
2650
		}
2651
2652
2653
		//set limit
2654
		if(array_key_exists('limit',$query_params)){
2655
			if(is_array($query_params['limit'])){
2656
				if( ! isset($query_params['limit'][0]) || ! isset($query_params['limit'][1])){
2657
					$e = sprintf(__("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)", "event_espresso"),  http_build_query($query_params['limit']));
2658
					throw new EE_Error($e."|".$e);
2659
				}
2660
				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
2661
				$query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
2662
			}elseif( ! empty ( $query_params['limit'] )){
2663
				$query_object->set_limit_sql((" LIMIT ".$query_params['limit']));
2664
			}
2665
		}
2666
		//set order by
2667
		if(array_key_exists('order_by',$query_params)){
2668
			if(is_array($query_params['order_by'])){
2669
				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
2670
				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
2671
				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
2672
				if(array_key_exists('order', $query_params)){
2673
					throw new EE_Error(sprintf(__("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 ", "event_espresso"),
2674
							get_class($this),implode(", ",array_keys($query_params['order_by'])),implode(", ",$query_params['order_by']),$query_params['order']));
2675
				}
2676
				 $this->_extract_related_models_from_sub_params_array_keys($query_params['order_by'],$query_object,'order_by');
2677
				//assume it's an array of fields to order by
2678
				$order_array = array();
2679
				foreach($query_params['order_by'] as $field_name_to_order_by => $order){
2680
					$order = $this->_extract_order($order);
2681
					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
0 ignored issues
show
Documentation introduced by
$field_name_to_order_by is of type integer|string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2682
				}
2683
				$query_object->set_order_by_sql(" ORDER BY ".implode(",",$order_array));
2684
			}elseif( ! empty ( $query_params['order_by'] )){
2685
				$this->_extract_related_model_info_from_query_param($query_params['order_by'],$query_object,'order',$query_params['order_by']);
2686
				if(isset($query_params['order'])){
2687
					$order = $this->_extract_order($query_params['order']);
2688
				}else{
2689
					$order = 'DESC';
2690
				}
2691
				$query_object->set_order_by_sql(" ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order);
2692
			}
2693
		}
2694
2695
		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
2696
		if( ! array_key_exists('order_by',$query_params) && array_key_exists('order',$query_params) && ! empty( $query_params['order'] )){
2697
			$pk_field = $this->get_primary_key_field();
2698
			$order = $this->_extract_order($query_params['order']);
2699
			$query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
2700
		}
2701
2702
		//set group by
2703
		if(array_key_exists('group_by',$query_params)){
2704
			if(is_array($query_params['group_by'])){
2705
				//it's an array, so assume we'll be grouping by a bunch of stuff
2706
				$group_by_array = array();
2707
				foreach($query_params['group_by'] as $field_name_to_group_by){
2708
					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
2709
				}
2710
				$query_object->set_group_by_sql(" GROUP BY ".implode(", ",$group_by_array));
2711
			}elseif( ! empty ( $query_params['group_by'] )){
2712
				$query_object->set_group_by_sql(" GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by']));
2713
			}
2714
		}
2715
		//set having
2716
		if(array_key_exists('having',$query_params) && $query_params['having']){
2717
			$query_object->set_having_sql( $this->_construct_having_clause($query_params['having']));
2718
		}
2719
2720
		//now, just verify they didn't pass anything wack
2721
		foreach($query_params as $query_key => $query_value){
2722 View Code Duplication
			if( ! in_array($query_key,$this->_allowed_query_params,true)){
2723
				throw new EE_Error(
2724
					sprintf(
2725
						__("You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",'event_espresso'),
2726
						$query_key,
2727
						get_class($this),
2728
//						print_r( $this->_allowed_query_params, TRUE )
2729
						implode( ',', $this->_allowed_query_params )
2730
					)
2731
				);
2732
			}
2733
		}
2734
		$main_model_join_sql = $query_object->get_main_model_join_sql();
2735
		if ( empty( $main_model_join_sql ) )
2736
			$query_object->set_main_model_join_sql($this->_construct_internal_join());
2737
		return $query_object;
2738
	}
2739
2740
	/**
2741
	 * Gets the where conditions that should be imposed on the query based on the
2742
	 * context (eg reading frontend, backend, edit or delete).
2743
	 * @param string $context one of EEM_Base::valid_cap_contexts()
2744
	 * @return array like EEM_Base::get_all() 's $query_params[0]
2745
	 */
2746
	public function caps_where_conditions( $context = self::caps_read ) {
2747
		EEM_Base::verify_is_valid_cap_context( $context );
2748
		$cap_where_conditions = array();
2749
		$cap_restrictions = $this->caps_missing( $context );
2750
		/**
2751
		 * @var $cap_restrictions EE_Default_Where_Conditions[]
2752
		 */
2753
		foreach( $cap_restrictions as $cap => $restriction_if_no_cap ) {
2754
				$cap_where_conditions = array_replace_recursive( $cap_where_conditions, $restriction_if_no_cap->get_default_where_conditions() );
2755
		}
2756
		return apply_filters( 'FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context, $cap_restrictions );
2757
	}
2758
2759
	/**
2760
	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
2761
	 * otherwise throws an exception
2762
	 * @param string $should_be_order_string
2763
	 * @return string either ASC, asc, DESC or desc
2764
	 * @throws EE_Error
2765
	 */
2766 View Code Duplication
	private function _extract_order($should_be_order_string){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2767
		if(in_array($should_be_order_string, $this->_allowed_order_values)){
2768
			return $should_be_order_string;
2769
		}else{
2770
			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ", "event_espresso"),get_class($this),$should_be_order_string));
2771
		}
2772
	}
2773
2774
2775
2776
	/**
2777
	 * Looks at all the models which are included in this query, and asks each
2778
	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
2779
	 * so they can be merged
2780
	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
2781
	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.  'none' means NO default where conditions will be used AT ALL during this query.
2782
	 * 'other_models_only' means default where conditions from other models will be used, but not for this primary model. 'all', the default, means
2783
	 * default where conditions will apply as normal
2784
	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
2785
	 * @throws EE_Error
2786
	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
2787
	 */
2788
	private function _get_default_where_conditions_for_models_in_query(EE_Model_Query_Info_Carrier $query_info_carrier,$use_default_where_conditions = 'all',$where_query_params = array()){
2789
		$allowed_used_default_where_conditions_values = array(
2790
				'all',
2791
				'this_model_only',
2792
				'other_models_only',
2793
				'minimum',
2794
				'none'
2795
			);
2796 View Code Duplication
		if( ! in_array($use_default_where_conditions,$allowed_used_default_where_conditions_values)){
2797
			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s", "event_espresso"),$use_default_where_conditions,implode(", ",$allowed_used_default_where_conditions_values)));
2798
		}
2799
		if( in_array($use_default_where_conditions, array('all','this_model_only')) ){
2800
			$universal_query_params = $this->_get_default_where_conditions();
2801
		}elseif( in_array( $use_default_where_conditions, array( 'minimum' ) ) ) {
2802
			$universal_query_params = $this->_get_minimum_where_conditions();
2803
		}else{
2804
			$universal_query_params = array();
2805
		}
2806
2807
		if(in_array($use_default_where_conditions,array('all','other_models_only'))){
2808
			foreach($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name){
2809
				$related_model = $this->get_related_model_obj($model_name);
2810
				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
2811
2812
				$universal_query_params = array_merge($universal_query_params,
2813
						$this->_override_defaults_or_make_null_friendly(
2814
								$related_model_universal_where_params,
2815
								$where_query_params,
2816
								$related_model,
2817
								$model_relation_path)
2818
						);
2819
			}
2820
		}
2821
		return $universal_query_params;
2822
	}
2823
2824
	/**
2825
	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
2826
	 * then we also add a special where condition which allows for that model's primary key
2827
	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
2828
	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
2829
	 * @param array $default_where_conditions
2830
	 * @param array $provided_where_conditions
2831
	 * @param EEM_Base $model
2832
	 * @param string $model_relation_path like 'Transaction.Payment.'
2833
	 * @return array like EEM_Base::get_all's $query_params[0]
2834
	 */
2835
	private function _override_defaults_or_make_null_friendly($default_where_conditions,$provided_where_conditions,$model,$model_relation_path){
2836
		$null_friendly_where_conditions = array();
2837
		$none_overridden = true;
2838
		$or_condition_key_for_defaults = 'OR*'.get_class($model);
2839
2840
		foreach($default_where_conditions as $key => $val){
2841
			if( isset($provided_where_conditions[$key])){
2842
				$none_overridden = false;
2843
			}else{
2844
				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
2845
			}
2846
		}
2847
		if( $none_overridden && $default_where_conditions){
0 ignored issues
show
Bug Best Practice introduced by
The expression $default_where_conditions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2848
			if($model->has_primary_key_field()){
2849
				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path.".".$model->primary_key_name()] = array('IS NULL');
2850
			}else{
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
2851
				//@todo NO PK, use other defaults
2852
			}
2853
		}
2854
		return $null_friendly_where_conditions;
2855
	}
2856
2857
	/**
2858
	 * Uses the _default_where_conditions_strategy set during __construct() to get
2859
	 * default where conditions on all get_all, update, and delete queries done by this model.
2860
	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
2861
	 * NOT array('Event_CPT.post_type'=>'esp_event').
2862
	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
2863
	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
2864
	 */
2865
	private function _get_default_where_conditions($model_relation_path = null){
2866
		if ( $this->_ignore_where_strategy )
2867
			return array();
2868
2869
		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
2870
	}
2871
	/**
2872
	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
2873
	 * minimum where conditions on all get_all, update, and delete queries done by this model.
2874
	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
2875
	 * NOT array('Event_CPT.post_type'=>'esp_event').
2876
	 * Similar to _get_default_where_conditions
2877
	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
2878
	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
2879
	 */
2880
	protected function _get_minimum_where_conditions($model_relation_path = null){
2881
		if ( $this->_ignore_where_strategy )
2882
			return array();
2883
2884
		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
2885
	}
2886
	/**
2887
	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
2888
	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
2889
	 * @param EE_Model_Query_Info_Carrier $model_query_info
2890
	 * @return string
2891
	 */
2892
	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info){
2893
		$selects = $this->_get_columns_to_select_for_this_model();
2894
		foreach($model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included){
2895
			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
2896
			$selects = array_merge($selects, $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain));
2897
		}
2898
		return implode(", ",$selects);
2899
	}
2900
2901
	/**
2902
	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
2903
	 * So that's going to be the columns for all the fields on the model
2904
	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
2905
	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
2906
	 */
2907
	public function _get_columns_to_select_for_this_model($model_relation_chain = ''){
2908
		$fields = $this->field_settings();
2909
		$selects = array();
2910
		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain, $this->get_this_model_name());
2911
		foreach($fields as $field_obj){
2912
			$selects[] = $table_alias_with_model_relation_chain_prefix . $field_obj->get_table_alias().".".$field_obj->get_table_column()." AS '".$table_alias_with_model_relation_chain_prefix.$field_obj->get_table_alias().".".$field_obj->get_table_column()."'";
2913
		}
2914
		//make sure we are also getting the PKs of each table
2915
		$tables = $this->get_tables();
2916
		if(count($tables) > 1){
2917
			foreach($tables as $table_obj){
2918
				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix . $table_obj->get_fully_qualified_pk_column();
2919
				if( ! in_array($qualified_pk_column,$selects)){
2920
					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
2921
				}
2922
			}
2923
		}
2924
		return $selects;
2925
	}
2926
2927
2928
2929
	/**
2930
	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
2931
	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
2932
	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the SQL
2933
	 * for joining, and the data types
2934
	 * @param null|string 	$original_query_param
2935
	 * @param string $query_param like Registration.Transaction.TXN_ID
2936
	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
2937
	 * @param 	string $query_param_type like Registration.Transaction.TXN_ID
2938
	 * or 'PAY_ID'. Otherwise, we don't expect there to be a column name. We only want model names, eg 'Event.Venue' or 'Registration's
2939
	 * @param string $original_query_param what it originally was (eg Registration.Transaction.TXN_ID). If null, we assume it matches $query_param
2940
	 * @throws EE_Error
2941
	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
2942
	 */
2943
	private function _extract_related_model_info_from_query_param( $query_param, EE_Model_Query_Info_Carrier $passed_in_query_info, $query_param_type, $original_query_param = NULL ){
2944
		if($original_query_param == NULL){
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $original_query_param of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
2945
			$original_query_param = $query_param;
2946
		}
2947
		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
2948
		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
2949
		$allow_logic_query_params = in_array($query_param_type,array('where','having'));
2950
		$allow_fields = in_array($query_param_type,array('where','having','order_by','group_by','order'));
2951
		//check to see if we have a field on this model
2952
		$this_model_fields = $this->field_settings(true);
2953
		if(array_key_exists($query_param,$this_model_fields)){
2954
			if($allow_fields){
2955
				return;
2956
			}else{
2957
				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", "event_espresso"),
2958
						$query_param,get_class($this),$query_param_type,$original_query_param));
2959
			}
2960
		}
2961
		//check if this is a special logic query param
2962
		elseif(in_array($query_param, $this->_logic_query_param_keys, TRUE)){
2963
			if($allow_logic_query_params){
2964
				return;
2965
			}else{
2966
				throw new EE_Error(
2967
					sprintf(
2968
						__( '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', 'event_espresso' ),
2969
						implode( '", "', $this->_logic_query_param_keys ),
2970
						$query_param ,
2971
						get_class( $this ),
2972
						'<br />',
2973
						"\t" . ' $passed_in_query_info = <pre>' . print_r( $passed_in_query_info, TRUE ) . '</pre>' . "\n\t" . ' $query_param_type = ' . $query_param_type . "\n\t" . ' $original_query_param = ' . $original_query_param
2974
					)
2975
				);
2976
			}
2977
		}
2978
2979
		//check if it's a custom selection
2980
		elseif(array_key_exists($query_param,$this->_custom_selections)){
2981
			return;
2982
		}
2983
2984
		//check if has a model name at the beginning
2985
		//and
2986
		//check if it's a field on a related model
2987
		foreach($this->_model_relations as $valid_related_model_name=>$relation_obj){
2988
			if(strpos($query_param, $valid_related_model_name.".") === 0){
2989
				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info,$original_query_param);
2990
				$query_param = substr($query_param, strlen($valid_related_model_name."."));
2991
				if($query_param == ''){
2992
					//nothing left to $query_param
2993
					//we should actually end in a field name, not a model like this!
2994
					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ", "event_espresso"),
2995
					$query_param,$query_param_type,get_class($this),$valid_related_model_name));
2996
				}else{
2997
					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
2998
					$related_model_obj->_extract_related_model_info_from_query_param($query_param, $passed_in_query_info, $query_param_type, $original_query_param);
2999
					return;
3000
				}
3001
			}elseif($query_param == $valid_related_model_name){
3002
				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info,$original_query_param);
3003
				return;
3004
			}
3005
		}
3006
3007
3008
		//ok so $query_param didn't start with a model name
3009
		//and we previously confirmed it wasn't a logic query param or field on the current model
3010
		//it's wack, that's what it is
3011
		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", "event_espresso"),
3012
				$query_param,get_class($this),$query_param_type,$original_query_param));
3013
3014
	}
3015
3016
3017
3018
	/**
3019
	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3020
	 * and store it on $passed_in_query_info
3021
	 * @param string $model_name
3022
	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3023
	 * @param string $original_query_param used to extract the relation chain between the queried model and $model_name.
3024
	 * Eg, if we are querying Event, and are adding a join to 'Payment' with the original query param key 'Registration.Transaction.Payment.PAY_amount',
3025
	 * we want to extract 'Registration.Transaction.Payment', in case Payment wants to add default query params so that it will know
3026
	 * what models to prepend onto its default query params or in case it wants to rename tables (in case there are multiple joins to the same table)
3027
	 * @return void
3028
	 */
3029
	private function _add_join_to_model($model_name, EE_Model_Query_Info_Carrier $passed_in_query_info,$original_query_param){
3030
		$relation_obj = $this->related_settings_for($model_name);
3031
3032
		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3033
		//check if the relation is HABTM, because then we're essentially doing two joins
3034
		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3035
		if($relation_obj instanceof EE_HABTM_Relation){
3036
			$join_model_obj = $relation_obj->get_join_model();
3037
			//replace the model specified with the join model for this relation chain, whi
3038
			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name, $join_model_obj->get_this_model_name(), $model_relation_chain);
0 ignored issues
show
Bug introduced by
The method get_this_model_name cannot be called on $join_model_obj (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3039
			$new_query_info = new EE_Model_Query_Info_Carrier(
3040
					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
0 ignored issues
show
Bug introduced by
The method get_this_model_name cannot be called on $join_model_obj (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3041
					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3042
			$passed_in_query_info->merge( $new_query_info  );
3043
		}
3044
		//now just join to the other table pointed to by the relation object, and add its data types
3045
		$new_query_info = new EE_Model_Query_Info_Carrier(
3046
				array($model_relation_chain=>$model_name),
3047
				$relation_obj->get_join_statement($model_relation_chain));
3048
		$passed_in_query_info->merge( $new_query_info  );
3049
	}
3050
3051
3052
	/**
3053
	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3054
	 * @param array $where_params like EEM_Base::get_all
3055
	 * @return string of SQL
3056
	 */
3057
	private function _construct_where_clause($where_params){
3058
		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3059
		if($SQL){
3060
			return " WHERE ". $SQL;
3061
		}else{
3062
			return '';
3063
		}
3064
	}
3065
3066
	/**
3067
	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3068
	 * and should be passed HAVING parameters, not WHERE parameters
3069
	 * @param array $having_params
3070
	 * @return string
3071
	 */
3072
	private function _construct_having_clause($having_params){
3073
		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3074
		if($SQL){
3075
			return " HAVING ". $SQL;
3076
		}else{
3077
			return '';
3078
		}
3079
3080
	}
3081
3082
	/**
3083
	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3084
	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on EEM_Attendee.
3085
	 * @param string $field_name
3086
	 * @param string $model_name
3087
	 * @return EE_Model_Field_Base
3088
	 * @throws EE_Error
3089
	 */
3090
	protected function _get_field_on_model($field_name,$model_name){
3091
		$model_class = 'EEM_'.$model_name;
3092
		$model_filepath = $model_class.".model.php";
3093
		EE_Registry::instance()->load_helper( 'File' );
3094
		if ( is_readable($model_filepath)){
3095
			require_once($model_filepath);
3096
			$model_instance=call_user_func($model_name."::instance");
3097
			/* @var $model_instance EEM_Base */
3098
			return $model_instance->field_settings_for($field_name);
3099
		}else{
3100
			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s','event_espresso'),$model_name,$model_class,$model_filepath));
3101
		}
3102
	}
3103
3104
3105
3106
	/**
3107
	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND Event_Meta.meta_value = 'foo'))"
3108
	 * @param array  $where_params see EEM_Base::get_all for documentation
3109
	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3110
	 * @throws EE_Error
3111
	 * @return string of SQL
3112
	 */
3113
	private function _construct_condition_clause_recursive($where_params, $glue = ' AND'){
3114
		$where_clauses=array();
3115
		foreach($where_params as $query_param => $op_and_value_or_sub_condition){
3116
			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3117
			if(in_array($query_param,$this->_logic_query_param_keys)){
3118
				switch($query_param){
3119
					case 'not':
3120
					case 'NOT':
3121
						$where_clauses[] = "! (". $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition, $glue).")";
3122
						break;
3123
					case 'and':
3124
					case 'AND':
3125
						$where_clauses[] = " (". $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition, ' AND ') .")";
3126
						break;
3127
					case 'or':
3128
					case 'OR':
3129
						$where_clauses[] = " (". $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition, ' OR ') .")";
3130
						break;
3131
				}
3132
			}else{
3133
				$field_obj = $this->_deduce_field_from_query_param($query_param);
3134
3135
				//if it's not a normal field, maybe it's a custom selection?
3136
				if( ! $field_obj){
3137
					if(isset( $this->_custom_selections[$query_param][1])){
3138
						$field_obj = $this->_custom_selections[$query_param][1];
3139
					}else{
3140
						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection", "event_espresso"),$query_param));
3141
					}
3142
				}
3143
				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3144
				$where_clauses[]=$this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
0 ignored issues
show
Documentation introduced by
$query_param is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3145
			}
3146
		}
3147
		if($where_clauses){
0 ignored issues
show
Bug Best Practice introduced by
The expression $where_clauses of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
3148
			$SQL = implode($glue,$where_clauses);
3149
		}else{
3150
			$SQL = '';
3151
		}
3152
		return $SQL;
3153
	}
3154
3155
3156
3157
	/**
3158
	 * Takes the input parameter and extract the table name (alias) and column name
3159
	 * @param array $query_param  like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3160
	 * @throws EE_Error
3161
	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3162
	 */
3163
	private function _deduce_column_name_from_query_param($query_param){
3164
		$field = $this->_deduce_field_from_query_param($query_param);
0 ignored issues
show
Documentation introduced by
$query_param is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3165
3166
		if( $field ){
3167
			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param( $field->get_model_name(), $query_param );
0 ignored issues
show
Documentation introduced by
$query_param is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3168
			return $table_alias_prefix . $field->get_qualified_column();
3169
		}elseif(array_key_exists($query_param,$this->_custom_selections)){
3170
			//maybe it's custom selection item?
3171
			//if so, just use it as the "column name"
3172
			return $query_param;
3173
		}else{
3174
			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)", "event_espresso"),$query_param,implode(",",$this->_custom_selections)));
3175
		}
3176
	}
3177
3178
	/**
3179
	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition query
3180
	 * param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get overwritten
3181
	 * Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
3182
	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
3183
	 * @param string $condition_query_param_key
3184
	 * @return string
3185
	 */
3186 View Code Duplication
	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
3187
		$pos_of_star = strpos($condition_query_param_key, '*');
3188
		if($pos_of_star === FALSE){
3189
			return $condition_query_param_key;
3190
		}else{
3191
			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
3192
			return $condition_query_param_sans_star;
3193
		}
3194
	}
3195
3196
3197
3198
	/**
3199
	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
3200
	 * @param mixed array | string 	$op_and_value
3201
	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
3202
	 * @throws EE_Error
3203
	 * @return string
3204
	 */
3205
	private function _construct_op_and_value($op_and_value, $field_obj){
3206
		if(is_array( $op_and_value )){
3207
			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
3208
			if( ! $operator){
0 ignored issues
show
Bug Best Practice introduced by
The expression $operator of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
3209
				$php_array_like_string = array();
3210
				foreach($op_and_value as $key => $value){
3211
					$php_array_like_string[] = "$key=>$value";
3212
				}
3213
				throw new EE_Error(sprintf(__("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))", "event_espresso"), implode(",",$php_array_like_string)));
3214
			}
3215
			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
3216
		}else{
3217
			$operator = '=';
3218
			$value = $op_and_value;
3219
		}
3220
3221
		//check to see if the value is actually another field
3222
		if(is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true){
3223
			return $operator.SP.$this->_deduce_column_name_from_query_param($value);
3224
		}elseif(in_array($operator, $this->_in_style_operators) && is_array($value)){
3225
			//in this case, the value should be an array, or at least a comma-separated list
3226
			//it will need to handle a little differently
3227
			$cleaned_value = $this->_construct_in_value($value, $field_obj);
3228
			//note: $cleaned_value has already been run through $wpdb->prepare()
3229
			return $operator.SP.$cleaned_value;
3230
		} elseif( in_array( $operator, $this->_between_style_operators ) && is_array( $value ) ) {
3231
			//the value should be an array with count of two.
3232
			if ( count($value) !== 2 )
3233
				throw new EE_Error( sprintf( __("The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.", 'event_espresso'), "BETWEEN" ) );
3234
			$cleaned_value = $this->_construct_between_value( $value, $field_obj );
3235
			return $operator.SP.$cleaned_value;
3236 View Code Duplication
		} elseif( in_array( $operator, $this->_null_style_operators ) ) {
3237
			if($value != NULL){
3238
				throw new EE_Error(sprintf(__("You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid", "event_espresso"),$value,$operator));
3239
			}
3240
			return $operator;
3241
		}elseif( $operator == 'LIKE' && ! is_array($value)){
3242
			//if the operator is 'LIKE', we want to allow percent signs (%) and not
3243
			//remove other junk. So just treat it as a string.
3244
			return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
3245
		}elseif( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)){
3246
			return $operator.SP.$this->_wpdb_prepare_using_field($value,$field_obj);
3247 View Code Duplication
		}elseif(in_array($operator, $this->_in_style_operators) && ! is_array($value)){
3248
			throw new EE_Error(sprintf(__("Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",'event_espresso'),$operator, $operator));
3249
		}elseif( ! in_array($operator, $this->_in_style_operators) && is_array($value)){
3250
			throw new EE_Error(sprintf(__("Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",'event_espresso'),$operator,$operator));
3251
		}else{
3252
			throw new EE_Error(sprintf(__("It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all", "event_espresso"),  http_build_query($op_and_value)));
3253
		}
3254
	}
3255
3256
3257
3258
	/**
3259
	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
3260
	 * @param array $values
3261
	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg '%s'
3262
	 * @return string
3263
	 */
3264
	function _construct_between_value( $values, $field_obj ) {
3265
		$cleaned_values = array();
3266
		foreach ( $values as $value ) {
3267
			$cleaned_values[] = $this->_wpdb_prepare_using_field($value,$field_obj);
3268
		}
3269
		return  $cleaned_values[0] . " AND " . $cleaned_values[1];
3270
	}
3271
3272
3273
3274
3275
	/**
3276
	 * Takes an array or a comma-separated list of $values and cleans them
3277
	 * according to $data_type using $wpdb->prepare, and then makes the list a
3278
	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
3279
	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
3280
	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
3281
	 * @param mixed $values array or comma-separated string
3282
	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
3283
	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
3284
	 */
3285
	function _construct_in_value($values,  $field_obj){
3286
		//check if the value is a CSV list
3287
		if(is_string($values)){
3288
			//in which case, turn it into an array
3289
			$values = explode(",",$values);
3290
		}
3291
		$cleaned_values = array();
3292
		foreach($values as $value){
0 ignored issues
show
Bug introduced by
The expression $values of type object|integer|double|null|array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
3293
			$cleaned_values[] = $this->_wpdb_prepare_using_field($value,$field_obj);
3294
		}
3295
		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
3296
		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
3297
		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
3298
		if(empty($cleaned_values)){
3299
			$all_fields = $this->field_settings();
3300
			$a_field = array_shift($all_fields);
3301
			$main_table = $this->_get_main_table();
3302
			$cleaned_values[] = "SELECT ".$a_field->get_table_column()." FROM ".$main_table->get_table_name()." WHERE FALSE";
3303
		}
3304
		return "(".implode(",",$cleaned_values).")";
3305
	}
3306
3307
3308
3309
	/**
3310
	 *
3311
	 * @param mixed 	$value
3312
	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
3313
	 * @throws EE_Error
3314
	 * @return false|null|string
3315
	 */
3316
	private function _wpdb_prepare_using_field($value,$field_obj){
3317
		/** @type WPDB $wpdb */
3318
		global $wpdb;
3319
		if($field_obj instanceof EE_Model_Field_Base){
3320
			return $wpdb->prepare($field_obj->get_wpdb_data_type(),$this->_prepare_value_for_use_in_db($value, $field_obj));
3321
		}else{//$field_obj should really just be a data type
3322 View Code Duplication
			if( ! in_array($field_obj,$this->_valid_wpdb_data_types)){
3323
				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),$field_obj,implode(",",$this->_valid_wpdb_data_types)));
3324
			}
3325
			return $wpdb->prepare($field_obj,$value);
3326
		}
3327
	}
3328
3329
3330
3331
	/**
3332
	 * Takes the input parameter and finds the model field that it indicates.
3333
	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3334
	 * @throws EE_Error
3335
	 * @return EE_Model_Field_Base
3336
	 */
3337
	protected function _deduce_field_from_query_param($query_param_name){
3338
		//ok, now proceed with deducing which part is the model's name, and which is the field's name
3339
		//which will help us find the database table and column
3340
3341
		$query_param_parts = explode(".",$query_param_name);
3342
		if(empty($query_param_parts)){
3343
			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",'event_espresso'),$query_param_name));
3344
		}
3345
		$number_of_parts = count($query_param_parts);
3346
		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
3347
		if($number_of_parts == 1){
3348
			$field_name = $last_query_param_part;
3349
			$model_obj = $this;
3350
		}else{// $number_of_parts >= 2
3351
			//the last part is the column name, and there are only 2parts. therefore...
3352
			$field_name = $last_query_param_part;
3353
			$model_obj = $this->get_related_model_obj( $query_param_parts[ $number_of_parts - 2 ]);
3354
		}
3355
		try{
3356
			return $model_obj->field_settings_for($field_name);
3357
		}catch(EE_Error $e){
3358
			return null;
3359
		}
3360
	}
3361
3362
3363
3364
	/**
3365
	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's alias and column
3366
	 * which corresponds to it
3367
	 * @param string $field_name
3368
	 * @throws EE_Error
3369
	 * @return string
3370
	 */
3371
	function _get_qualified_column_for_field($field_name){
3372
		$all_fields = $this->field_settings();
3373
		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : FALSE;
3374
		if($field){
3375
			return $field->get_qualified_column();
3376
		}else{
3377
			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.",'event_espresso'),$field_name,get_class($this)));
3378
		}
3379
	}
3380
3381
3382
3383
3384
	/**
3385
	 * constructs the select use on special limit joins
3386
	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although its setup so the select query will be setup on and just doing the special select join off of the primary table (as that is typically where the limits would be set).
3387
	 * @param  string $table_alias The table the select is being built for
3388
	 * @param  mixed|string $limit The limit for this select
3389
	 * @return string 				The final select join element for the query.
3390
	 */
3391
	function _construct_limit_join_select( $table_alias, $limit ) {
3392
		$SQL = '';
3393
3394
		foreach ( $this->_tables as $table_obj ) {
3395
			if ( $table_obj instanceof EE_Primary_Table ) {
3396
				$SQL .= $table_alias == $table_obj->get_table_alias() ? $table_obj->get_select_join_limit( $limit ) : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
3397
			} elseif ( $table_obj instanceof EE_Secondary_Table ) {
3398
				$SQL .= $table_alias == $table_obj->get_table_alias() ? $table_obj->get_select_join_limit_join($limit) : SP . $table_obj->get_join_sql( $table_alias ).SP;
3399
			}
3400
		}
3401
		return $SQL;
3402
	}
3403
3404
3405
3406
	/**
3407
	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
3408
	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
3409
	 * @return string SQL
3410
	 */
3411
	function _construct_internal_join(){
3412
		$SQL = $this->_get_main_table()->get_table_sql();
3413
		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
3414
		return $SQL;
3415
	}
3416
3417
3418
3419
	/**
3420
	 * Constructs the SQL for joining all the tables on this model.
3421
	 * Normally $alias should be the primary table's alias, but in cases where
3422
	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the primary table)
3423
	 * then we should provide that secondary table's alias.
3424
	 * Eg, with $alias being the primary table's alias, this will construct SQL like:
3425
	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
3426
	 * With $alias being a secondary table's alias, this will construct SQL like:
3427
	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
3428
	 *
3429
	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
3430
	 * @return string
3431
	 */
3432
	function _construct_internal_join_to_table_with_alias($alias_prefixed){
3433
		$SQL = '';
3434
		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
3435
		foreach($this->_tables as $table_obj){
3436
			if($table_obj instanceof EE_Secondary_Table){//table is secondary table
3437
				if($alias_sans_prefix == $table_obj->get_table_alias()){
3438
					//so we're joining to this table, meaning the table is already in
3439
					//the FROM statement, BUT the primary table isn't. So we want
3440
					//to add the inverse join sql
3441
					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
3442
				}else{
3443
					//just add a regular JOIN to this table from the primary table
3444
					$SQL .= $table_obj->get_join_sql($alias_prefixed);
3445
				}
3446
			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
3447
		}
3448
		return $SQL;
3449
	}
3450
3451
	/**
3452
	 * Gets an array for storing all the data types on the next-to-be-executed-query.
3453
	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being their data type (eg, '%s', '%d', etc)
3454
	 * @return array
3455
	 */
3456
	function _get_data_types(){
3457
		$data_types = array();
3458
		foreach(array_values($this->field_settings()) as $field_obj){
3459
			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
3460
			/** @var $field_obj EE_Model_Field_Base */
3461
			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
3462
		}
3463
		return $data_types;
3464
	}
3465
3466
3467
3468
	/**
3469
	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
3470
	 * @param string $model_name
3471
	 * @throws EE_Error
3472
	 * @return EEM_Base
3473
	 */
3474
	function get_related_model_obj($model_name){
3475
3476
		$model_classname = "EEM_".$model_name;
3477
		if(!class_exists($model_classname)){
3478
			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",'event_espresso'),$model_name,$model_classname));
3479
		}
3480
		$model_obj = call_user_func($model_classname."::instance");
3481
		return $model_obj;
3482
	}
3483
3484
3485
	/**
3486
	 * Returns the array of EE_ModelRelations for this model.
3487
	 * @return EE_Model_Relation_Base[]
3488
	 */
3489
	public function relation_settings(){
3490
		return $this->_model_relations;
3491
	}
3492
3493
	/**
3494
	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
3495
	 * because without THOSE models, this model probably doesn't have much purpose.
3496
	 * (Eg, without an event, datetimes have little purpose.)
3497
	 * @return EE_Belongs_To_Relation[]
3498
	 */
3499
	public function belongs_to_relations(){
3500
		$belongs_to_relations = array();
3501
		foreach($this->relation_settings() as $model_name => $relation_obj){
3502
			if($relation_obj instanceof EE_Belongs_To_Relation){
3503
				$belongs_to_relations[$model_name] = $relation_obj;
3504
			}
3505
		}
3506
		return $belongs_to_relations;
3507
	}
3508
3509
3510
3511
	/**
3512
	 * Returns the specified EE_Model_Relation, or throws an exception
3513
	 * @param string $relation_name name of relation, key in $this->_relatedModels
3514
	 * @throws EE_Error
3515
	 * @return EE_Model_Relation_Base
3516
	 */
3517
	public function related_settings_for($relation_name){
3518
		$relatedModels=$this->relation_settings();
3519 View Code Duplication
		if(!array_key_exists($relation_name,$relatedModels)){
3520
			throw new EE_Error(
3521
				sprintf(
3522
					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...','event_espresso'),
3523
					$relation_name,
3524
					$this->_get_class_name(),
3525
					implode( ', ', array_keys( $relatedModels ))
3526
				)
3527
			);
3528
		}
3529
		return $relatedModels[$relation_name];
3530
	}
3531
3532
3533
3534
	/**
3535
	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all fields
3536
	 * @param string $fieldName
3537
	 * @throws EE_Error
3538
	 * @return EE_Model_Field_Base
3539
	 */
3540 View Code Duplication
	public function field_settings_for($fieldName){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
3541
		$fieldSettings=$this->field_settings(true);
3542
		if( ! array_key_exists($fieldName,$fieldSettings)){
3543
			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'",'event_espresso'),$fieldName,get_class($this)));
3544
		}
3545
		return $fieldSettings[$fieldName];
3546
	}
3547
3548
	/**
3549
	 * Checks if this field exists on this model
3550
	 * @param string $fieldName a key in the model's _field_settings array
3551
	 * @return boolean
3552
	 */
3553
	public function has_field($fieldName){
3554
		$fieldSettings = $this->field_settings(true);
3555
		if( isset($fieldSettings[$fieldName])){
3556
			return true;
3557
		}else{
3558
			return false;
3559
		}
3560
	}
3561
3562
	/**
3563
	 * Returns whether or not this model has a relation to the specified model
3564
	 * @param string $relation_name possibly one of the keys in the relation_settings array
3565
	 * @return boolean
3566
	 */
3567
	public function has_relation($relation_name){
3568
		$relations = $this->relation_settings();
3569
		if(isset($relations[$relation_name])){
3570
			return true;
3571
		}else{
3572
			return false;
3573
		}
3574
	}
3575
3576
3577
	/**
3578
	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
3579
	 * Eg, on EE_Answer that would be ANS_ID field object
3580
	 * @param $field_obj
3581
	 * @return EE_Model_Field_Base
3582
	 */
3583
	public function is_primary_key_field( $field_obj ){
3584
		return $field_obj instanceof EE_Primary_Key_Field_Base ? TRUE : FALSE;
3585
	}
3586
3587
3588
3589
	/**
3590
	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
3591
	 * Eg, on EE_Answer that would be ANS_ID field object
3592
	 * @return EE_Model_Field_Base
3593
	 * @throws EE_Error
3594
	 */
3595
	public function get_primary_key_field(){
3596
		if( $this->_primary_key_field === NULL ){
3597
			foreach( $this->field_settings( TRUE ) as $field_obj ){
3598
				if( $this->is_primary_key_field( $field_obj )){
3599
					$this->_primary_key_field = $field_obj;
3600
					break;
3601
				}
3602
			}
3603
			if( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base ){
3604
				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s",'event_espresso'),get_class($this)));
3605
			}
3606
		}
3607
		return $this->_primary_key_field;
3608
	}
3609
3610
3611
3612
	/**
3613
	 * Returns whether or not not there is a primary key on this model.
3614
	 * Internally does some caching.
3615
	 * @return boolean
3616
	 */
3617
	public function has_primary_key_field(){
3618
		if($this->_has_primary_key_field === null){
3619
			try{
3620
				$this->get_primary_key_field();
3621
				$this->_has_primary_key_field = true;
3622
			}catch(EE_Error $e){
3623
				$this->_has_primary_key_field = false;
3624
			}
3625
		}
3626
		return $this->_has_primary_key_field;
3627
	}
3628
3629
3630
3631
	/**
3632
	 * Finds the first field of type $field_class_name.
3633
	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field, EE_Foreign_Key_Field, etc
3634
	 * @return EE_Model_Field_Base or null if none is found
3635
	 */
3636
	public function get_a_field_of_type($field_class_name){
3637
		foreach($this->field_settings() as $field){
3638
			if( $field instanceof $field_class_name ){
3639
				return $field;
3640
			}
3641
		}
3642
		return null;
3643
	}
3644
3645
3646
	/**
3647
	 * Gets a foreign key field pointing to model.
3648
	 * @param string $model_name eg Event, Registration, not EEM_Event
3649
	 * @return EE_Foreign_Key_Field_Base
3650
	 * @throws EE_Error
3651
	 */
3652
	public function get_foreign_key_to($model_name){
3653
		if( ! isset( $this->_cache_foreign_key_to_fields[ $model_name ] ) ){
3654
			foreach($this->field_settings() as $field){
3655
//				if(is_subclass_of($field, 'EE_Foreign_Key_Field_Base')){
3656
				if( $field instanceof EE_Foreign_Key_Field_Base ){
3657
					if (in_array($model_name,$field->get_model_names_pointed_to() ) ) {
3658
						$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
3659
					}
3660
				}
3661
			}
3662 View Code Duplication
			if( ! isset( $this->_cache_foreign_key_to_fields[ $model_name ] ) ){
3663
				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",'event_espresso'),$model_name,get_class($this)));
3664
			}
3665
		}
3666
		return $this->_cache_foreign_key_to_fields[ $model_name ];
3667
	}
3668
3669
3670
3671
	/**
3672
	 * Gets the actual table for the table alias
3673
	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
3674
	 * a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'. Either one works
3675
	 * @return EE_Table_Base
3676
	 */
3677
	function get_table_for_alias($table_alias){
3678
		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
3679
		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
3680
	}
3681
3682
3683
3684
	/**
3685
	 * Returns a flat array of all field son this model, instead of organizing them
3686
	 * by table_alias as they are in the constructor.
3687
	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
3688
	 * @return EE_Model_Field_Base[] where the keys are the field's name
3689
	 */
3690
	public function field_settings($include_db_only_fields = false){
3691
		if( $include_db_only_fields ){
3692 View Code Duplication
			if( $this->_cached_fields === NULL ){
3693
				$this->_cached_fields = array();
3694
				foreach($this->_fields as $fields_corresponding_to_table){
3695
					foreach($fields_corresponding_to_table as $field_name => $field_obj){
0 ignored issues
show
Bug introduced by
The expression $fields_corresponding_to_table of type object<EE_Model_Field_Base> is not traversable.
Loading history...
3696
						$this->_cached_fields[$field_name]=$field_obj;
3697
					}
3698
				}
3699
			}
3700
			return $this->_cached_fields;
3701 View Code Duplication
		}else{
3702
			if( $this->_cached_fields_non_db_only === NULL ){
3703
				$this->_cached_fields_non_db_only = array();
3704
				foreach($this->_fields as $fields_corresponding_to_table){
3705
					foreach($fields_corresponding_to_table as $field_name => $field_obj){
0 ignored issues
show
Bug introduced by
The expression $fields_corresponding_to_table of type object<EE_Model_Field_Base> is not traversable.
Loading history...
3706
						/** @var $field_obj EE_Model_Field_Base */
3707
						if( ! $field_obj->is_db_only_field() ){
3708
							$this->_cached_fields_non_db_only[$field_name]=$field_obj;
3709
						}
3710
					}
3711
				}
3712
			}
3713
			return $this->_cached_fields_non_db_only;
3714
		}
3715
	}
3716
3717
3718
3719
	/**
3720
	 *        cycle though array of attendees and create objects out of each item
3721
	 *
3722
	 * @access        private
3723
	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
3724
	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not, numerically indexed)
3725
	 * @throws \EE_Error
3726
	 */
3727
	protected function _create_objects( $rows = array() ) {
3728
		$array_of_objects=array();
3729
		if(empty($rows)){
3730
			return array();
3731
		}
3732
		$count_if_model_has_no_primary_key = 0;
3733
		$has_primary_key = $this->has_primary_key_field();
3734
		if( $has_primary_key ) {
3735
			$primary_key_field = $this->get_primary_key_field();
3736
		} else {
3737
			$primary_key_field = null;
3738
		}
3739
		foreach ( $rows as $row ) {
3740
			if(empty($row)){
3741
				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
3742
				return array();
3743
			}
3744
			//check if we've already set this object in the results array,
3745
			//in which case there's no need to process it further (again)
3746
			if( $has_primary_key ) {
3747
				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
3748
					$row,
3749
					$primary_key_field->get_qualified_column(),
3750
					$primary_key_field->get_table_column()
3751
				);
3752
				if( $table_pk_value &&
3753
					isset( $array_of_objects[ $table_pk_value ] ) ) {
3754
					continue;
3755
				}
3756
			}
3757
			$classInstance=$this->instantiate_class_from_array_or_object($row);
3758 View Code Duplication
			if( ! $classInstance ) {
3759
				throw new EE_Error(
3760
					sprintf(
3761
						__( 'Could not create instance of class %s from row %s', 'event_espresso' ),
3762
						$this->get_this_model_name(),
3763
						http_build_query( $row )
3764
					)
3765
				);
3766
			}
3767
			//set the timezone on the instantiated objects
3768
			$classInstance->set_timezone( $this->_timezone );
3769
			//make sure if there is any timezone setting present that we set the timezone for the object
3770
			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
3771
			$array_of_objects[ $key ] = $classInstance;
3772
			//also, for all the relations of type BelongsTo, see if we can cache
3773
			//those related models
3774
			//(we could do this for other relations too, but if there are conditions
3775
			//that filtered out some fo the results, then we'd be caching an incomplete set
3776
			//so it requires a little more thought than just caching them immediately...)
3777
			foreach($this->_model_relations as $modelName => $relation_obj){
3778
				if( $relation_obj instanceof EE_Belongs_To_Relation){
3779
					//check if this model's INFO is present. If so, cache it on the model
3780
					$other_model = $relation_obj->get_other_model();
3781
3782
					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
0 ignored issues
show
Bug introduced by
The method instantiate_class_from_array_or_object cannot be called on $other_model (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3783
3784
					//if we managed to make a model object from the results, cache it on the main model object
3785
					if( $other_model_obj_maybe ){
3786
						//set timezone on these other model objects if they are present
3787
						$other_model_obj_maybe->set_timezone( $this->_timezone );
3788
						$classInstance->cache($modelName, $other_model_obj_maybe);
3789
					}
3790
				}
3791
			}
3792
		}
3793
		return $array_of_objects;
3794
	}
3795
3796
3797
3798
	/**
3799
	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default values.
3800
	 * A typical example of where this is used is when creating a new item and the initial load of a form.  We dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the object (as set in the model_field!).
3801
	 *
3802
	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
3803
	 */
3804
	public function create_default_object() {
3805
3806
		$this_model_fields_and_values = array();
3807
		//setup the row using default values;
3808
		foreach ( $this->field_settings() as $field_name => $field_obj ) {
3809
			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
3810
		}
3811
3812
		$className = $this->_get_class_name();
3813
		$classInstance = EE_Registry::instance()->load_class( $className, array( $this_model_fields_and_values ), FALSE, FALSE );
3814
3815
		return $classInstance;
3816
	}
3817
3818
3819
3820
	/**
3821
	 *
3822
	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
3823
	 * or an stdClass where each property is the name of a column,
3824
	 * @return EE_Base_Class
3825
	 */
3826
	public function instantiate_class_from_array_or_object($cols_n_values){
3827
		if( ! is_array( $cols_n_values ) && is_object( $cols_n_values )) {
3828
			$cols_n_values = get_object_vars( $cols_n_values );
3829
		}
3830
		$primary_key = NULL;
3831
		//make sure the array only has keys that are fields/columns on this model
3832
		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values( $cols_n_values );
3833
		if( $this->has_primary_key_field() && isset( $this_model_fields_n_values[ $this->primary_key_name() ] ) ){
3834
			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
3835
		}
3836
		$className=$this->_get_class_name();
3837
3838
		//check we actually found results that we can use to build our model object
3839
		//if not, return null
3840
		if( $this->has_primary_key_field()){
3841
			if(empty( $this_model_fields_n_values[$this->primary_key_name()] )){
3842
				return NULL;
3843
			}
3844
		}else if($this->unique_indexes()){
3845
			$first_column = reset($this_model_fields_n_values);
3846
			if(empty($first_column)){
3847
				return NULL;
3848
			}
3849
		}
3850
3851
		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
3852
		if ( $primary_key){
3853
			$classInstance = $this->get_from_entity_map( $primary_key );
3854
			if( ! $classInstance) {
3855
				$classInstance = EE_Registry::instance()->load_class( $className, array( $this_model_fields_n_values, $this->_timezone ), TRUE, FALSE );
3856
				// add this new object to the entity map
3857
				$classInstance = $this->add_to_entity_map( $classInstance );
0 ignored issues
show
Documentation introduced by
$classInstance is of type boolean, but the function expects a object<EE_Base_Class>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3858
			}
3859
		}else{
3860
			$classInstance = EE_Registry::instance()->load_class( $className, array( $this_model_fields_n_values, $this->_timezone ), TRUE, FALSE );
0 ignored issues
show
Bug Compatibility introduced by
The expression \EE_Registry::instance()...imezone), TRUE, FALSE); of type boolean adds the type boolean to the return on line 3865 which is incompatible with the return type documented by EEM_Base::instantiate_class_from_array_or_object of type EE_Base_Class|null.
Loading history...
3861
		}
3862
3863
			//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.
3864
		$this->set_timezone( $classInstance->get_timezone() );
3865
		return $classInstance;
3866
	}
3867
	/**
3868
	 * Gets the model object from the  entity map if it exists
3869
	 * @param int|string $id the ID of the model object
3870
	 * @return EE_Base_Class
3871
	 */
3872
	public function get_from_entity_map( $id ){
3873
		return isset( $this->_entity_map[ $id ] ) ? $this->_entity_map[ $id ] : NULL;
3874
	}
3875
3876
3877
3878
	/**
3879
	 * add_to_entity_map
3880
	 *
3881
	 * Adds the object to the model's entity mappings
3882
	 * 		Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
3883
	 * 		and for the remainder of the request, it's even more up-to-date than what's in the database.
3884
	 * 		So, if the database doesn't agree with what's in the entity mapper, ignore the database"
3885
	 * 		If the database gets updated directly and you want the entity mapper to reflect that change,
3886
	 * 		then this method should be called immediately after the update query
3887
	 *
3888
	 * @param 	EE_Base_Class $object
3889
	 * @throws EE_Error
3890
	 * @return \EE_Base_Class
3891
	 */
3892
	public function add_to_entity_map( EE_Base_Class $object) {
3893
		$className = $this->_get_class_name();
3894
		if( ! $object instanceof $className ){
3895
			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),is_object( $object ) ? get_class( $object ) : $object, $className ) );
3896
		}
3897
		/** @var $object EE_Base_Class */
3898
		if ( ! $object->ID() ){
3899
			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.", "event_espresso"),get_class($this)));
3900
		}
3901
		// double check it's not already there
3902
		$classInstance = $this->get_from_entity_map( $object->ID() );
3903
		if ( $classInstance ) {
3904
			return $classInstance;
3905
		} else {
3906
			$this->_entity_map[ $object->ID() ] = $object;
3907
			return $object;
3908
		}
3909
	}
3910
3911
	/**
3912
	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
3913
	 *
3914
	 * Given an array where keys are column (or column alias) names and values,
3915
	 * returns an array of their corresponding field names and database values
3916
	 * @param array $cols_n_values
3917
	 * @return array
3918
	 */
3919
	public function deduce_fields_n_values_from_cols_n_values( $cols_n_values ) {
3920
		return $this->_deduce_fields_n_values_from_cols_n_values( $cols_n_values );
0 ignored issues
show
Documentation introduced by
$cols_n_values is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3921
	}
3922
3923
3924
	/**
3925
	 * _deduce_fields_n_values_from_cols_n_values
3926
	 *
3927
	 * Given an array where keys are column (or column alias) names and values,
3928
	 * returns an array of their corresponding field names and database values
3929
	 *
3930
	 * @param string $cols_n_values
3931
	 * @return array
3932
	 */
3933
	protected function _deduce_fields_n_values_from_cols_n_values( $cols_n_values ){
3934
		$this_model_fields_n_values = array();
3935
		foreach( $this->get_tables() as $table_alias => $table_obj ) {
3936
			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values, $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column() );
3937
			//there is a primary key on this table and its not set. Use defaults for all its columns
3938
			if( $table_obj->get_pk_column() && $table_pk_value === NULL ){
3939
				foreach( $this->_get_fields_for_table( $table_alias ) as $field_name => $field_obj ) {
0 ignored issues
show
Bug introduced by
The expression $this->_get_fields_for_table($table_alias) of type object<EE_Model_Field_Base> is not traversable.
Loading history...
3940
					if( ! $field_obj->is_db_only_field() ){
3941
						//prepare field as if its coming from db
3942
						$prepared_value = $field_obj->prepare_for_set( $field_obj->get_default_value() );
3943
						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db( $prepared_value );
3944
					}
3945
				}
3946
			}else{
3947
				//the table's rows existed. Use their values
3948
				foreach( $this->_get_fields_for_table( $table_alias ) as $field_name => $field_obj ) {
0 ignored issues
show
Bug introduced by
The expression $this->_get_fields_for_table($table_alias) of type object<EE_Model_Field_Base> is not traversable.
Loading history...
3949
					if( ! $field_obj->is_db_only_field() )
3950
					$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not($cols_n_values, $field_obj->get_qualified_column(), $field_obj->get_table_column() );
3951
				}
3952
			}
3953
		}
3954
		return $this_model_fields_n_values;
3955
	}
3956
3957
	protected function _get_column_value_with_table_alias_or_not( $cols_n_values, $qualified_column, $regular_column ){
3958
		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
3959
		//does the field on the model relate to this column retrieved from the db?
3960
		//or is it a db-only field? (not relating to the model)
3961
		if( isset( $cols_n_values[ $qualified_column ] ) ){
3962
			$value = $cols_n_values[ $qualified_column ];
3963
3964
		}elseif( isset( $cols_n_values[ $regular_column ] ) ){
3965
			$value = $cols_n_values[ $regular_column ];
3966
		}else{
3967
			$value = NULL;
3968
		}
3969
3970
		return $value;
3971
	}
3972
3973
3974
3975
	/**
3976
	 * refresh_entity_map_from_db
3977
	 *
3978
	 * Makes sure the model object in the entity map at $id assumes the values
3979
	 * of the database (opposite of EE_base_Class::save())
3980
	 *
3981
	 * @param int|string $id
3982
	 * @return EE_Base_Class
3983
	 */
3984
	public function refresh_entity_map_from_db( $id ){
3985
		$obj_in_map = $this->get_from_entity_map( $id );
3986
		if( $obj_in_map ){
3987
			$wpdb_results = $this->_get_all_wpdb_results( array( array ( $this->get_primary_key_field()->get_name() => $id ), 'limit' => 1 ) );
3988
			if( $wpdb_results && is_array( $wpdb_results ) ){
0 ignored issues
show
Bug Best Practice introduced by
The expression $wpdb_results of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
3989
				$one_row = reset( $wpdb_results );
3990
				foreach( $this->_deduce_fields_n_values_from_cols_n_values($one_row ) as $field_name => $db_value ) {
3991
					$obj_in_map->set_from_db( $field_name, $db_value );
3992
				}
3993
				//clear the cache of related model objects
3994
				foreach ( $this->relation_settings() as $relation_name => $relation_obj ){
3995
					$obj_in_map->clear_cache($relation_name, NULL, TRUE );
3996
				}
3997
			}
3998
			return $obj_in_map;
3999
		}else{
4000
			return $this->get_one_by_ID( $id );
4001
		}
4002
	}
4003
4004
4005
4006
	/**
4007
	 * refresh_entity_map_with
4008
	 *
4009
	 * Leaves the entry in the entity map alone, but updates it to match the provided
4010
	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
4011
	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
4012
	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
4013
	 *
4014
	 * @param int|string    $id
4015
	 * @param EE_Base_Class $replacing_model_obj
4016
	 * @return \EE_Base_Class
4017
	 */
4018
	public function refresh_entity_map_with( $id, $replacing_model_obj ) {
4019
		$obj_in_map = $this->get_from_entity_map( $id );
4020
		if( $obj_in_map ){
4021
			if( $replacing_model_obj instanceof EE_Base_Class ){
4022
				foreach( $replacing_model_obj->model_field_array() as $field_name => $value ) {
4023
					$obj_in_map->set( $field_name, $value );
4024
				}
4025
				//make the model object in the entity map's cache match the $replacing_model_obj
4026
				foreach ( $this->relation_settings() as $relation_name => $relation_obj ){
4027
					$obj_in_map->clear_cache($relation_name, NULL, TRUE );
4028
					foreach( $replacing_model_obj->get_all_from_cache( $relation_name ) as $cache_id => $cached_obj ) {
4029
						$obj_in_map->cache( $relation_name, $cached_obj, $cache_id );
4030
					}
4031
				}
4032
			}
4033
			return $obj_in_map;
4034
		}else{
4035
			$this->add_to_entity_map( $replacing_model_obj );
4036
			return $replacing_model_obj;
4037
		}
4038
	}
4039
4040
4041
4042
	/**
4043
	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
4044
	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
4045
	 * require_once($this->_getClassName().".class.php");
4046
	 * @return string
4047
	 */
4048
	private function _get_class_name(){
4049
		return "EE_".$this->get_this_model_name();
4050
	}
4051
4052
4053
4054
	/**
4055
	 * Get the name of the items this model represents, for the quantity specified. Eg,
4056
	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
4057
	 * it would be 'Events'.
4058
	 * @param int $quantity
4059
	 * @return string
4060
	 */
4061
	public function item_name($quantity = 1){
4062
		if($quantity == 1){
4063
			return $this->singular_item;
4064
		}else{
4065
			return $this->plural_item;
4066
		}
4067
	}
4068
4069
4070
4071
	/**
4072
	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
4073
	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called (http://www.garfieldtech.com/blog/php-magic-call)
4074
	 * and passed the method's name and arguments.
4075
	 * Instead of requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that happen?)
4076
	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg, filters_hook_espresso__EE_Answer__my_great_function)
4077
	 * and accepts 2 arguments: the object on which the function was called, and an array of the original arguments passed to the function. Whatever their callback function returns will be returned by this function.
4078
	 * Example: in functions.php (or in a plugin):
4079
	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
4080
	 * function my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
4081
	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
4082
	 *        return $previousReturnValue.$returnString;
4083
	 * }
4084
	 * require('EEM_Answer.model.php');
4085
	 * $answer=EEM_Answer::instance();
4086
	 * echo $answer->my_callback('monkeys',100);
4087
	 * //will output "you called my_callback! and passed args:monkeys,100"
4088
	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
4089
	 * @param array  $args       array of original arguments passed to the function
4090
	 * @throws EE_Error
4091
	 * @return mixed whatever the plugin which calls add_filter decides
4092
	 */
4093 View Code Duplication
	public function __call($methodName,$args){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
4094
		$className=get_class($this);
4095
		$tagName="FHEE__{$className}__{$methodName}";
4096
		if(!has_filter($tagName)){
4097
			throw new EE_Error(
4098
				sprintf(
4099
					__( '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 );', 'event_espresso' ),
4100
					$methodName,
4101
					$className,
4102
					$tagName,
4103
					'<br />'
4104
				)
4105
			);
4106
		}
4107
4108
		return apply_filters($tagName,null,$this,$args);
4109
	}
4110
4111
4112
4113
	/**
4114
	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
4115
	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
4116
	 * @param EE_Base_Class | int $base_class_obj_or_id  	either the EE_Base_Class that corresponds to this Model, or its ID
4117
	 * @param boolean $ensure_is_in_db if set, we will also verify this model object exists in the database. If it does not, we add it
4118
	 * @throws EE_Error
4119
	 * @return EE_Base_Class
4120
	 */
4121
	public function ensure_is_obj( $base_class_obj_or_id, $ensure_is_in_db = FALSE ){
4122
		$className = $this->_get_class_name();
4123
		$primary_key_field = $this->get_primary_key_field();
4124
		if( $base_class_obj_or_id instanceof $className ){
4125
			$model_object = $base_class_obj_or_id;
4126
		}elseif( $primary_key_field instanceof EE_Primary_Key_Int_Field && (
4127
				is_int( $base_class_obj_or_id ) ||
4128
				is_string( $base_class_obj_or_id ) )){//assume it's an ID. either a proper integer or a string representing an integer (eg "101" instead of 101)
4129
			$model_object = $this->get_one_by_ID($base_class_obj_or_id);
4130
		}elseif( $primary_key_field instanceof EE_Primary_Key_String_Field && is_string($base_class_obj_or_id) ){
4131
			//assume its a string representation of the object
4132
			$model_object = $this->get_one_by_ID($base_class_obj_or_id);
4133
		}else{
4134
			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",'event_espresso'),$base_class_obj_or_id,$this->_get_class_name(),print_r($base_class_obj_or_id,true)));
4135
		}
4136
		if( $model_object->ID() == NULL && $ensure_is_in_db){
4137
			$model_object->save();
4138
		}
4139
		return $model_object;
4140
	}
4141
4142
4143
4144
	/**
4145
	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
4146
	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
4147
	 * returns it ID.
4148
	 * @param EE_Base_Class|int|string $base_class_obj_or_id
4149
	 * @return int|string depending on the type of this model object's ID
4150
	 * @throws EE_Error
4151
	 */
4152
	public function ensure_is_ID($base_class_obj_or_id){
4153
		$className = $this->_get_class_name();
4154
		if( $base_class_obj_or_id instanceof $className ){
4155
			/** @var $base_class_obj_or_id EE_Base_Class */
4156
			$id = $base_class_obj_or_id->ID();
4157
		}elseif(is_int($base_class_obj_or_id)){
4158
			//assume it's an ID
4159
			$id = $base_class_obj_or_id;
4160
		}elseif(is_string($base_class_obj_or_id)){
4161
			//assume its a string representation of the object
4162
			$id = $base_class_obj_or_id;
4163
		}else{
4164
			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",'event_espresso'),$base_class_obj_or_id,$this->_get_class_name(),print_r($base_class_obj_or_id,true)));
4165
		}
4166
		return $id;
4167
	}
4168
4169
4170
4171
	/**
4172
	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
4173
	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
4174
	 * been sanitized and converted into the appropriate domain.
4175
	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by the model
4176
	 * object/model field) is when making a method call from WITHIN a model object, which has direct access to its sanitized
4177
	 * values.
4178
	 * Note: after changing this setting, you should set it back to its previous value (using get_assumption_concerning_values_already_prepared_by_model_object())
4179
	 * eg.
4180
	 * $EVT = EEM_Event::instance(); $old_setting = $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
4181
	 * $EVT->assume_values_already_prepared_by_model_object(true);
4182
	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
4183
	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
4184
	 * @param int $values_already_prepared like one of the constants on EEM_Base
4185
	 * @return void
4186
	 */
4187
	public function assume_values_already_prepared_by_model_object($values_already_prepared = self::not_prepared_by_model_object){
4188
		$this->_values_already_prepared_by_model_object = $values_already_prepared;
0 ignored issues
show
Documentation Bug introduced by
The property $_values_already_prepared_by_model_object was declared of type boolean, but $values_already_prepared is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
4189
	}
4190
	/**
4191
	 * Read comments for assume_values_already_prepared_by_model_object()
4192
	 * @return int
4193
	 */
4194
	public function get_assumption_concerning_values_already_prepared_by_model_object(){
4195
		return $this->_values_already_prepared_by_model_object;
4196
	}
4197
4198
	/**
4199
	 * Gets all the indexes on this model
4200
	 * @return EE_Index[]
4201
	 */
4202
	public function indexes(){
4203
		return $this->_indexes;
4204
	}
4205
	/**
4206
	 * Gets all the Unique Indexes on this model
4207
	 * @return EE_Unique_Index[]
4208
	 */
4209
	public function unique_indexes(){
4210
		$unique_indexes = array();
4211
		foreach($this->_indexes as $name => $index){
4212
			if($index instanceof EE_Unique_Index){
4213
				$unique_indexes [$name] = $index;
4214
			}
4215
		}
4216
		return $unique_indexes;
4217
	}
4218
	/**
4219
	 * Gets all the fields which, when combined, make the primary key.
4220
	 * This is usually just an array with 1 element (the primary key), but in cases
4221
	 * where there is no primary key, it's a combination of fields as defined
4222
	 * on a primary index
4223
	 * @return EE_Model_Field_Base[] indexed by the field's name
4224
	 */
4225
	public function get_combined_primary_key_fields(){
4226
		foreach($this->indexes() as $index){
4227
			if($index instanceof EE_Primary_Key_Index){
4228
				return $index->fields();
4229
			}
4230
		}
4231
		return array( $this->primary_key_name() => $this->get_primary_key_field());
4232
	}
4233
	
4234
4235
	/**
4236
	 * Used to build a primary key string (when the model has no primary key),
4237
	 * which can be used a unique string to identify this model object.
4238
	 * @param array $cols_n_values keys are field names, values are their values
4239
	 * @return string
4240
	 */
4241
	public function get_index_primary_key_string($cols_n_values){
4242
		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values, $this->get_combined_primary_key_fields());
4243
		return http_build_query($cols_n_values_for_primary_key_index);
4244
	}
4245
4246
4247
	/**
4248
	 * Gets the field values from the primary key string
4249
	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
4250
	 * @param string $index_primary_key_string
4251
	 * @return null|array
4252
	 */
4253
	function parse_index_primary_key_string( $index_primary_key_string) {
4254
		$key_fields = $this->get_combined_primary_key_fields();
4255
		//check all of them are in the $id
4256
		$key_vals_in_combined_pk = array();
4257
		parse_str( $index_primary_key_string, $key_vals_in_combined_pk );
4258
		foreach( $key_fields as $key_field_name => $field_obj ) {
4259
			if( ! isset( $key_vals_in_combined_pk[ $key_field_name ] ) ){
4260
				return NULL;
4261
			}
4262
		}
4263
		return $key_vals_in_combined_pk;
4264
	}
4265
4266
	/**
4267
	 * verifies that an array of key-value pairs for model fields has a key
4268
	 * for each field comprising the primary key index
4269
	 * @param array $key_vals
4270
	 * @return boolean
4271
	 */
4272
	function has_all_combined_primary_key_fields( $key_vals ) {
4273
		$keys_it_should_have = array_keys( $this->get_combined_primary_key_fields() );
4274
		foreach( $keys_it_should_have as $key ){
4275
			if( ! isset( $key_vals[ $key ] ) ){
4276
				return false;
4277
			}
4278
		}
4279
		return true;
4280
	}
4281
4282
4283
	/**
4284
	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
4285
	 * We consider something to be a copy if all the attributes match (except the ID, of course).
4286
	 * @param array|EE_Base_Class $model_object_or_attributes_array 	If its an array, it's field-value pairs
4287
	 * @param array                $query_params like EEM_Base::get_all's query_params.
4288
	 * @throws EE_Error
4289
	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically indexed)
4290
	 */
4291
	public function get_all_copies($model_object_or_attributes_array, $query_params = array()){
4292
4293 View Code Duplication
		if($model_object_or_attributes_array instanceof EE_Base_Class){
4294
			$attributes_array = $model_object_or_attributes_array->model_field_array();
4295
		}elseif(is_array($model_object_or_attributes_array)){
4296
			$attributes_array = $model_object_or_attributes_array;
4297
		}else{
4298
			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", "event_espresso"),$model_object_or_attributes_array));
4299
		}
4300
		//even copies obviously won't have the same ID, so remove the primary key
4301
		//from the WHERE conditions for finding copies (if there is a primary key, of course)
4302
		if($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])){
4303
			unset($attributes_array[$this->primary_key_name()]);
4304
		}
4305
		if(isset($query_params[0])){
4306
			$query_params[0] = array_merge($attributes_array,$query_params);
4307
		}else{
4308
			$query_params[0] = $attributes_array;
4309
		}
4310
		return $this->get_all($query_params);
4311
	}
4312
4313
4314
4315
	/**
4316
	 * Gets the first copy we find. See get_all_copies for more details
4317
	 * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
4318
	 * @param array $query_params
4319
	 * @return EE_Base_Class
4320
	 */
4321 View Code Duplication
	function get_one_copy($model_object_or_attributes_array,$query_params = array()){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
4322
		if( ! is_array( $query_params ) ){
4323
			EE_Error::doing_it_wrong('EEM_Base::get_one_copy', sprintf( __( '$query_params should be an array, you passed a variable of type %s', 'event_espresso' ), gettype( $query_params ) ), '4.6.0' );
4324
			$query_params = array();
4325
		}
4326
		$query_params['limit'] = 1;
4327
		$copies = $this->get_all_copies($model_object_or_attributes_array,$query_params);
4328
		if(is_array($copies)){
4329
			return array_shift($copies);
4330
		}else{
4331
			return null;
4332
		}
4333
	}
4334
4335
4336
4337
	/**
4338
	 * Updates the item with the specified id. Ignores default query parameters because
4339
	 * we have specified the ID, and its assumed we KNOW what we're doing
4340
	 * @param array $fields_n_values keys are field names, values are their new values
4341
	 * @param int|string $id the value of the primary key to update
4342
	 * @return int number of rows updated
4343
	 */
4344
	public function update_by_ID($fields_n_values,$id){
4345
		$query_params = array(0=>array($this->get_primary_key_field()->get_name() => $id),
4346
			'default_where_conditions'=>'other_models_only',);
4347
		return $this->update($fields_n_values,$query_params);
4348
	}
4349
4350
4351
4352
	/**
4353
	 * Changes an operator which was supplied to the models into one usable in SQL
4354
	 * @param string $operator_supplied
4355
	 * @return string an operator which can be used in SQL
4356
	 * @throws EE_Error
4357
	 */
4358
	private function _prepare_operator_for_sql($operator_supplied){
4359
		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied] : null;
4360 View Code Duplication
		if($sql_operator){
4361
			return $sql_operator;
4362
		}else{
4363
			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s", "event_espresso"),$operator_supplied,implode(",",array_keys($this->_valid_operators))));
4364
		}
4365
	}
4366
4367
	/**
4368
	 * Gets an array where keys are the primary keys and values are their 'names'
4369
	 * (as determined by the model object's name() function, which is often overridden)
4370
	 * @param array $query_params like get_all's
4371
	 * @return string[]
4372
	 */
4373
	public function get_all_names($query_params = array()){
4374
		$objs = $this->get_all($query_params);
4375
		$names = array();
4376
		foreach($objs as $obj){
4377
			$names[$obj->ID()] = $obj->name();
4378
		}
4379
		return $names;
4380
	}
4381
4382
	/**
4383
	 * Gets an array of primary keys from the model objects. If you acquired the model objects
4384
	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
4385
	 * this is duplicated effort and reduces efficiency) you would be better to use
4386
	 * array_keys() on $model_objects.
4387
	 * @param /EE_Base_Class[] $model_objects
0 ignored issues
show
Documentation introduced by
The doc-type /EE_Base_Class[] could not be parsed: Unknown type name "/EE_Base_Class" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
4388
	 * @param boolean $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it in the returned array
4389
	 * @return array
4390
	 */
4391
	public function get_IDs( $model_objects, $filter_out_empty_ids = false) {
4392
		if( ! $this->has_primary_key_field() ) {
4393
			if( WP_DEBUG ) {
4394
				EE_Error::add_error( __( 'Trying to get IDs from a model than has no primary key', 'event_espresso' ), __FILE__, __FUNCTION__, __LINE__ );
4395
				return array();
4396
			}
4397
		}
4398
		$IDs = array();
4399
		foreach( $model_objects as $model_object ) {
4400
			$id = $model_object->ID();
4401
			if( ! $id ) {
4402
				if( $filter_out_empty_ids ) {
4403
					continue;
4404
				}
4405
				if( WP_DEBUG ) {
4406
					EE_Error::add_error(__( 'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database', 'event_espresso' ), __FILE__, __FUNCTION__, __LINE__ );
4407
				}
4408
			}
4409
			$IDs[] = $id;
4410
		}
4411
		return $IDs;
4412
	}
4413
4414
	/**
4415
	 * Returns the string used in capabilities relating to this model. If there
4416
	 * are no capabilities that relate to this model returns false
4417
	 * @return string|false
4418
	 */
4419
	public function cap_slug(){
4420
		return apply_filters( 'FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
4421
	}
4422
4423
	/**
4424
	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
4425
	 *
4426
	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
4427
	 * only returns the cap restrictions array in that context (ie, the array
4428
	 * at that key)
4429
	 * @param string $context
4430
	 * @return EE_Default_Where_Conditions[] indexed by associated capability
4431
	 */
4432
	public function cap_restrictions( $context = EEM_Base::caps_read ) {
4433
		EEM_Base::verify_is_valid_cap_context( $context );
4434
		//check if we ought to run the restriction generator first
4435
		if( isset( $this->_cap_restriction_generators[ $context ] ) &&
4436
				$this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base &&
4437
				! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions() ) {
4438
			$this->_cap_restrictions[ $context ] = array_merge( $this->_cap_restrictions[ $context ],  $this->_cap_restriction_generators[ $context ]->generate_restrictions() );
4439
		}
4440
		//and make sure we've finalized the construction of each restriction
4441
		foreach( $this->_cap_restrictions[ $context ] as $where_conditions_obj ) {
4442
			$where_conditions_obj->_finalize_construct( $this );
4443
		}
4444
4445
		return $this->_cap_restrictions[ $context ];
4446
	}
4447
4448
	/**
4449
	 * Indicating whether or not this model thinks its a wp core model
4450
	 * @return boolean
4451
	 */
4452
	public function is_wp_core_model(){
4453
		return $this->_wp_core_model;
4454
	}
4455
4456
	/**
4457
	 * Gets all the caps that are missing which impose a restriction on
4458
	 * queries made in this context
4459
	 * @param string $context one of EEM_Base::caps_ constants
4460
	 * @return EE_Default_Where_Conditions[] indexed by capability name
4461
	 */
4462
	public function caps_missing( $context = EEM_Base::caps_read ) {
4463
		$missing_caps = array();
4464
		$cap_restrictions = $this->cap_restrictions( $context );
4465
		foreach( $cap_restrictions as $cap => $restriction_if_no_cap ) {
4466
			if( ! EE_Capabilities::instance()->current_user_can( $cap, $this->get_this_model_name() . '_model_applying_caps') ) {
4467
				$missing_caps[ $cap ] = $restriction_if_no_cap;
4468
			}
4469
		}
4470
		return $missing_caps;
4471
	}
4472
4473
	/**
4474
	 * Gets the mapping from capability contexts to action strings used in capability names
4475
	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
4476
	 * one of 'read', 'edit', or 'delete'
4477
	 */
4478
	public function cap_contexts_to_cap_action_map() {
4479
		return apply_filters( 'FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map, $this );
4480
	}
4481
4482
4483
4484
	/**
4485
	 * Gets the action string for the specified capability context
4486
	 * @param string $context
4487
	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
4488
	 * @throws \EE_Error
4489
	 */
4490
	public function cap_action_for_context( $context ) {
4491
		$mapping = $this->cap_contexts_to_cap_action_map();
4492
		if( isset( $mapping[ $context ] ) ) {
4493
			return $mapping[ $context ];
4494
		}
4495
		if( $action = apply_filters( 'FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context ) ) {
4496
			return $action;
4497
		}
4498
		throw new EE_Error(
4499
			sprintf(
4500
				__( 'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso' ),
4501
				$context,
4502
				implode(',', array_keys( $this->cap_contexts_to_cap_action_map() ) )
4503
			)
4504
		);
4505
4506
	}
4507
4508
	/**
4509
	 * Returns all the capability contexts which are valid when querying models
4510
	 * @return array
4511
	 */
4512
	static public function valid_cap_contexts() {
4513
		return apply_filters( 'FHEE__EEM_Base__valid_cap_contexts', array(
4514
			self::caps_read,
4515
			self::caps_read_admin,
4516
			self::caps_edit,
4517
			self::caps_delete
4518
		));
4519
	}
4520
4521
4522
4523
	/**
4524
	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
4525
	 * @param string $context
4526
	 * @return bool
4527
	 * @throws \EE_Error
4528
	 */
4529
	static public function verify_is_valid_cap_context( $context ) {
4530
		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
4531 View Code Duplication
		if( in_array( $context, $valid_cap_contexts ) ) {
4532
			return true;
4533
		}else{
4534
			throw new EE_Error(
4535
				sprintf(
4536
					__( 'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s', 'event_espresso' ),
4537
					$context,
4538
					'EEM_Base' ,
4539
					implode(',', $valid_cap_contexts )
4540
				)
4541
			);
4542
		}
4543
	}
4544
4545
	/**
4546
	 * Clears all the models field caches. This is only useful when a sub-class
4547
	 * might have added a field or something and these caches might be invaldiated
4548
	 */
4549
	protected function _invalidate_field_caches() {
4550
		$this->_cache_foreign_key_to_fields = array();
4551
		$this->_cached_fields = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array<integer,object<EE_Model_Field_Base>> of property $_cached_fields.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
4552
		$this->_cached_fields_non_db_only = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array<integer,object<EE_Model_Field_Base>> of property $_cached_fields_non_db_only.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
4553
	}
4554
4555
4556
4557
4558
}
4559