Completed
Branch FEAT-7553-PayPal-Express-PM (0ca3c2)
by
unknown
71:02 queued 56:56
created

EEM_Base::get_var()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 2
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
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 requester 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
	/**
171
	 * Array defining which cap restriction generators to use to create default
172
	 * cap restrictions to put in EEM_Base::_cap_restrictions.
173
	 *
174
	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
175
	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
176
	 * automatically set this to false (not just null).
177
	 * @var EE_Restriction_Generator_Base[]
178
	 */
179
	protected $_cap_restriction_generators = array();
180
181
	/**
182
	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
183
	 */
184
	const caps_read = 'read';
185
	const caps_read_admin = 'read_admin';
186
	const caps_edit = 'edit';
187
	const caps_delete = 'delete';
188
189
	/**
190
	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
191
	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
192
	 * maps to 'read' because when looking for relevant permissions we're going to use
193
	 * 'read' in teh capabilities names like 'ee_read_events' etc.
194
	 * @var array
195
	 */
196
	protected $_cap_contexts_to_cap_action_map = array(
197
		self::caps_read => 'read',
198
		self::caps_read_admin => 'read',
199
		self::caps_edit => 'edit',
200
		self::caps_delete => 'delete' );
201
202
	/**
203
	 * Timezone
204
	 * 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.
205
	 * @var string
206
	 */
207
	protected $_timezone;
208
209
210
	/**
211
	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for multisite.
212
	 * @var int
213
	 */
214
	protected static $_model_query_blog_id;
215
216
	/**
217
	 * A copy of _fields, except the array keys are the model names pointed to by
218
	 * the field
219
	 * @var EE_Model_Field_Base[]
220
	 */
221
	private $_cache_foreign_key_to_fields = array();
222
223
	/**
224
	 * Cached list of all the fields on the model, indexed by their name
225
	 * @var EE_Model_Field_Base[]
226
	 */
227
	private $_cached_fields = NULL;
228
229
	/**
230
	 * Cached list of all the fields on the model, except those that are
231
	 * marked as only pertinent to the database
232
	 * @var EE_Model_Field_Base[]
233
	 */
234
	private $_cached_fields_non_db_only = NULL;
235
236
	/**
237
	 * A cached reference to the primary key for quick lookup
238
	 * @var EE_Model_Field_Base
239
	 */
240
	private $_primary_key_field = NULL;
241
242
	/**
243
	 * Flag indicating whether this model has a primary key or not
244
	 * @var boolean
245
	 */
246
	protected $_has_primary_key_field=null;
247
248
	/**
249
	 * Whether or not this model is based off a table in WP core only (CPTs should set
250
	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
251
	 * @var boolean
252
	 */
253
	protected $_wp_core_model = false;
254
255
	/**
256
	 *	List of valid operators that can be used for querying.
257
	 * The keys are all operators we'll accept, the values are the real SQL
258
	 * operators used
259
	 * @var array
260
	 */
261
	protected $_valid_operators = array(
262
		'='=>'=',
263
		'<='=>'<=',
264
		'<'=>'<',
265
		'>='=>'>=',
266
		'>'=>'>',
267
		'!='=>'!=',
268
		'LIKE'=>'LIKE',
269
		'like'=>'LIKE',
270
		'NOT_LIKE'=>'NOT LIKE',
271
		'not_like'=>'NOT LIKE',
272
		'NOT LIKE'=>'NOT LIKE',
273
		'not like'=>'NOT LIKE',
274
		'IN'=>'IN',
275
		'in'=>'IN',
276
		'NOT_IN'=>'NOT IN',
277
		'not_in'=>'NOT IN',
278
		'NOT IN'=>'NOT IN',
279
		'not in'=>'NOT IN',
280
		'between' => 'BETWEEN',
281
		'BETWEEN' => 'BETWEEN',
282
		'IS_NOT_NULL' => 'IS NOT NULL',
283
		'is_not_null' =>'IS NOT NULL',
284
		'IS NOT NULL' => 'IS NOT NULL',
285
		'is not null' => 'IS NOT NULL',
286
		'IS_NULL' => 'IS NULL',
287
		'is_null' => 'IS NULL',
288
		'IS NULL' => 'IS NULL',
289
		'is null' => 'IS NULL',
290
		'REGEXP' => 'REGEXP',
291
		'regexp' => 'REGEXP',
292
		'NOT_REGEXP' => 'NOT REGEXP',
293
		'not_regexp' => 'NOT REGEXP',
294
		'NOT REGEXP' => 'NOT REGEXP',
295
		'not regexp' => 'NOT REGEXP',
296
	);
297
298
	/**
299
	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
300
	 * @var array
301
	 */
302
	protected $_in_style_operators = array('IN', 'NOT IN');
303
304
	/**
305
	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND '12-31-2012'"
306
	 * @var array
307
	 */
308
	protected $_between_style_operators = array( 'BETWEEN' );
309
310
	/**
311
	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists on a join table.
312
	 * @var array
313
	 */
314
	protected $_null_style_operators = array( 'IS NOT NULL', 'IS NULL');
315
316
	/**
317
	 * Allowed values for $query_params['order'] for ordering in queries
318
	 * @var array
319
	 */
320
	protected $_allowed_order_values = array('asc','desc','ASC','DESC');
321
322
	/**
323
	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
324
	 * than regular field names. It is assumed that their values are an array of WHERE conditions
325
	 * @var array
326
	 */
327
	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
328
329
	/**
330
	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
331
	 * 'where', but 'where' clauses are so common that we thought we'd omit it
332
	 * @var array
333
	 */
334
	private $_allowed_query_params = array(0, 'limit','order_by','group_by','having','force_join','order','on_join_limit','default_where_conditions', 'caps');
335
336
	/**
337
	 * All the data types that can be used in $wpdb->prepare statements.
338
	 * @var array
339
	 */
340
	private $_valid_wpdb_data_types = array('%d','%s','%f');
341
342
	/**
343
	 * 	EE_Registry Object
344
	 *	@var 	object
345
	 * 	@access 	protected
346
	 */
347
	protected $EE = NULL;
348
349
350
	/**
351
	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
352
	 * @var int
353
	 */
354
	protected $_show_next_x_db_queries = 0;
355
356
	/**
357
	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
358
	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
359
	 * @var array
360
	 */
361
	protected $_custom_selections = array();
362
363
	/**
364
	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
365
	 * caches every model object we've fetched from the DB on this request
366
	 * @var array
367
	 */
368
	protected $_entity_map;
369
370
	/**
371
	 * constant used to show EEM_Base has not yet verified the db on this http request
372
	 */
373
	const db_verified_none 		= 0;
374
	/**
375
	 * constant used to show EEM_Base has verified the EE core db on this http request,
376
	 * but not the addons' dbs
377
	 */
378
	const db_verified_core 		= 1;
379
	/**
380
	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
381
	 * the EE core db too)
382
	 */
383
	const db_verified_addons 	= 2;
384
385
	/**
386
	 * indicates whether an EEM_Base child has already re-verified the DB
387
	 * is ok (we don't want to do it repetitively). Should be set to one the constants
388
	 * looking like EEM_Base::db_verified_*
389
	 * @var int - 0 = none, 1 = core, 2 = addons
390
	 */
391
	protected static $_db_verification_level = EEM_Base::db_verified_none;
392
393
394
395
396
	/**
397
	 * About all child constructors:
398
	 * they should define the _tables, _fields and _model_relations arrays.
399
	 * Should ALWAYS be called after child constructor.
400
	 * In order to make the child constructors to be as simple as possible, this parent constructor
401
	 * finalizes constructing all the object's attributes.
402
	 * Generally, rather than requiring a child to code
403
	 * $this->_tables = array(
404
	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
405
	 *        ...);
406
	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
407
	 * each EE_Table has a function to set the table's alias after the constructor, using
408
	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
409
	 * do something similar.
410
	 *
411
	 * @param null $timezone
412
	 * @throws \EE_Error
413
	 */
414
	protected function __construct( $timezone = NULL ){
415
		// check that the model has not been loaded too soon
416
		if ( ! did_action( 'AHEE__EE_System__load_espresso_addons' )) {
417
			throw new EE_Error (
418
				sprintf(
419
					__( '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' ),
420
					get_class( $this )
421
				)
422
			);
423
		}
424
425
		/**
426
		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
427
		 */
428
		if ( empty( EEM_Base::$_model_query_blog_id ) ) {
429
			EEM_Base::set_model_query_blog_id();
430
		}
431
432
		/**
433
		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
434
		 * just use EE_Register_Model_Extension
435
		 * @var EE_Table_Base[] $_tables
436
		 */
437
		$this->_tables = apply_filters( 'FHEE__'.get_class($this).'__construct__tables', $this->_tables );
438
		foreach($this->_tables as $table_alias => $table_obj){
439
			/** @var $table_obj EE_Table_Base */
440
			$table_obj->_construct_finalize_with_alias($table_alias);
441
			if( $table_obj instanceof EE_Secondary_Table ){
442
				/** @var $table_obj EE_Secondary_Table */
443
				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
444
			}
445
		}
446
		/**
447
		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
448
		 * EE_Register_Model_Extension
449
		 * @param EE_Model_Field_Base[] $_fields
450
		 */
451
		$this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields',$this->_fields);
452
		$this->_invalidate_field_caches();
453
		foreach($this->_fields as $table_alias => $fields_for_table){
454
			if ( ! array_key_exists( $table_alias, $this->_tables )){
455
				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)));
456
			}
457
			foreach($fields_for_table as $field_name => $field_obj){
458
				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
459
				//primary key field base has a slightly different _construct_finalize
460
				/** @var $field_obj EE_Model_Field_Base */
461
				$field_obj->_construct_finalize( $table_alias, $field_name, $this->get_this_model_name() );
462
			}
463
		}
464
465
		// everything is related to Extra_Meta
466
		if( get_class($this) !== 'EEM_Extra_Meta'){
467
			//make extra meta related to everything, but don't block deleting things just
468
			//because they have related extra meta info. For now just orphan those extra meta
469
			//in the future we should automatically delete them
470
			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation( FALSE );
471
		}
472
		//and change logs
473
		if( get_class( $this) !==  'EEM_Change_Log' ) {
474
			$this->_model_relations[ 'Change_Log' ] = new EE_Has_Many_Any_Relation( FALSE );
475
		}
476
		/**
477
		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
478
		 * EE_Register_Model_Extension
479
		 * @param EE_Model_Relation_Base[] $_model_relations
480
		 */
481
		$this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',$this->_model_relations);
482
		foreach($this->_model_relations as $model_name => $relation_obj){
483
			/** @var $relation_obj EE_Model_Relation_Base */
484
			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
485
		}
486
		foreach($this->_indexes as $index_name => $index_obj){
487
			/** @var $index_obj EE_Index */
488
			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
489
		}
490
491
		$this->set_timezone($timezone);
492
		//finalize default where condition strategy, or set default
493
		if( ! $this->_default_where_conditions_strategy){
494
			//nothing was set during child constructor, so set default
495
			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
496
		}
497
		$this->_default_where_conditions_strategy->_finalize_construct($this);
498
		if( ! $this->_minimum_where_conditions_strategy){
499
			//nothing was set during child constructor, so set default
500
			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
501
		}
502
		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
503
504
		//if the cap slug hasn't been set, and we haven't set it to false on purpose
505
		//to indicate to NOT set it, set it to the logical default
506
		if( $this->_caps_slug === null ) {
507
			$this->_caps_slug = EEH_Inflector::pluralize_and_lower( $this->get_this_model_name() );
508
		}
509
		//initialize the standard cap restriction generators if none were specified by the child constructor
510
		if( $this->_cap_restriction_generators !== false ){
511
			foreach( $this->cap_contexts_to_cap_action_map() as $cap_context => $action ){
512
				if( ! isset( $this->_cap_restriction_generators[ $cap_context ] ) ) {
513
					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
514
						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
515
						new EE_Restriction_Generator_Protected(),
516
						$cap_context,
517
						$this
518
					);
519
				}
520
			}
521
		}
522
		//if there are cap restriction generators, use them to make the default cap restrictions
523
		if( $this->_cap_restriction_generators !== false ){
524
			foreach( $this->_cap_restriction_generators as $context => $generator_object ) {
525
				if( ! $generator_object ){
526
					continue;
527
				}
528 View Code Duplication
				if( ! $generator_object instanceof EE_Restriction_Generator_Base ){
529
					throw new EE_Error(
530
						sprintf(
531
							__( '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' ),
532
							$context,
533
							$this->get_this_model_name()
534
						)
535
					);
536
				}
537
				$action = $this->cap_action_for_context( $context );
538
				if( ! $generator_object->construction_finalized() ){
539
					$generator_object->_construct_finalize( $this, $action );
540
				}
541
542
			}
543
		}
544
		do_action('AHEE__'.get_class($this).'__construct__end');
545
	}
546
547
	/**
548
	 * Generates the cap restrictions for the given context, or if they were
549
	 * already generated just gets what's cached
550
	 * @param string $context one of EEM_Base::valid_cap_contexts()
551
	 * @return EE_Default_Where_Conditions[]
552
	 */
553
	protected function _generate_cap_restrictions( $context ){
554
		if( isset( $this->_cap_restriction_generators[ $context ] ) &&
555
				$this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base ) {
556
			return $this->_cap_restriction_generators[ $context ]->generate_restrictions();
557
		}else{
558
			return array();
559
		}
560
	}
561
562
563
	/**
564
	 * Used to set the $_model_query_blog_id static property.
565
	 *
566
	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
567
	 *                      value for get_current_blog_id() will be used.
568
	 */
569
	public static function set_model_query_blog_id( $blog_id = 0 ) {
570
		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
571
	}
572
573
574
575
576
	/**
577
	 * Returns whatever is set as the internal $model_query_blog_id.
578
	 *
579
	 * @return int
580
	 */
581
	public static function get_model_query_blog_id() {
582
		return EEM_Base::$_model_query_blog_id;
583
	}
584
585
586
587
	/**
588
	 *		This function is a singleton method used to instantiate the Espresso_model object
589
	 *
590
	 *		@access public
591
	 *		@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)
592
	 *		@return static (as in the concrete child class)
593
	 */
594 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...
595
596
		// check if instance of Espresso_model already exists
597
		if ( ! static::$_instance instanceof static) {
598
			// instantiate Espresso_model
599
			static::$_instance = new static( $timezone );
0 ignored issues
show
Bug introduced by
It seems like $timezone defined by parameter $timezone on line 594 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...
600
		}
601
602
		//we might have a timezone set, let set_timezone decide what to do with it
603
		static::$_instance->set_timezone( $timezone );
604
605
		// Espresso_model object
606
		return static::$_instance;
607
	}
608
609
610
611
	/**
612
	 * resets the model and returns it
613
	 * @param null | string $timezone
614
	 * @return EEM_Base|null (if the model was already instantiated, returns it, with 
615
	 * all its properties reset; if it wasn't instantiated, returns null)
616
	 */
617
	public static function reset(  $timezone = NULL ){
618
		if ( static::$_instance instanceof EEM_Base ) {
619
			//let's try to NOT swap out the current instance for a new one
620
			//because if someone has a reference to it, we can't remove their reference
621
			//so it's best to keep using the same reference, but change the original object
622
			//reset all its properties to their original values as defined in the class
623
			$r = new ReflectionClass( get_class( static::$_instance ) );
624
			$static_properties = $r->getStaticProperties();
625
			foreach( $r->getDefaultProperties() as $property => $value ) {
626
				//don't set instance to null like it was originally,
627
				//but it's static anyways, and we're ignoring static properties (for now at least)
628
				if( ! isset( $static_properties[ $property ] ) ) {
629
					static::$_instance->{$property} = $value;
630
				}
631
			}
632
			//and then directly call its constructor again, like we would if we 
633
			//were creating a new one
634
			static::$_instance->__construct( $timezone );
635
			return self::instance();
636
		}
637
		return null;
638
	}
639
640
641
642
	/**
643
	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
644
	 *
645
	 * @param  boolean $translated return localized strings or JUST the array.
646
	 * @return array
647
	 * @throws \EE_Error
648
	 */
649
	 public function status_array( $translated = FALSE ) {
650
		 if ( ! array_key_exists( 'Status', $this->_model_relations ) ) {
651
			 return array();
652
		 }
653
		 $model_name = $this->get_this_model_name();
654
		 $status_type = str_replace( ' ', '_', strtolower( str_replace( '_', ' ', $model_name ) ) );
655
		 $stati = EEM_Status::instance()->get_all( array( array( 'STS_type' => $status_type ) ) );
656
		 $status_array = array();
657
		 foreach ( $stati as $status ) {
658
			 $status_array[ $status->ID() ] = $status->get( 'STS_code' );
659
		 }
660
		 return $translated
661
			 ? EEM_Status::instance()->localized_status( $status_array, false, 'sentence' )
662
			 : $status_array;
663
	 }
664
665
666
667
	/**
668
	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
669
	 *
670
	 * @param array $query_params {
671
     *	@var array $0 (where) array {
672
	 *		eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine if user is bob')
673
			* becomes
674
	 *		SQL >> "...WHERE QST_display_text = 'Are you bob?' AND QST_admin_text = 'Determine if user is bob'...")
675
     *		To add WHERE conditions based on related models (and even models-related-to-related-models) prepend the model's name
676
	 *		onto the field name. Eg, EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12)));
677
	 *		becomes
678
	 *		SQL >> "SELECT * FROM wp_posts AS Event_CPT
679
	 *						LEFT JOIN wp_esp_event_meta AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID
680
	 *						LEFT JOIN wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID
681
	 *						LEFT JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID
682
	 *						LEFT JOIN wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID
683
	 *						WHERE Venue_CPT.ID = 12
684
	 *		Notice that automatically took care of joining Events to Venues (even when each of those models actually consisted of two tables).
685
	 * 	 	Also, you may chain the model relations together. Eg instead of just having "Venue.VNU_ID", you could have
686
	 *		"Registration.Attendee.ATT_ID" as a field on a query for events (because events are related to Registrations, which are related to Attendees).
687
	 *		You can take it even further with "Registration.Transaction.Payment.PAY_amount" etc.
688
	 *		To change the operator (from the default of '='), change the value to an numerically-indexed array, where the
689
	 *		first item in the list is the operator.
690
	 *		eg: array( 'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34), 'QST_wp_user' => array('in',array(1,2,7,23)))
691
	 *		becomes
692
	 *		SQL >> "...WHERE QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN (1,2,7,23)...".
693
	 *        Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT LIKE, IN (followed by numeric-indexed array),
694
	 *          NOT IN (dido), BETWEEN (followed by an array with exactly 2 date strings), IS NULL, and IS NOT NULL
695
     *		Values can be a string, int, or float. They can also be arrays IFF the operator is IN.
696
	 *        Also, values can actually be field names. To indicate the value is a field,
697
	 *          simply provide a third array item (true) to the operator-value array like so:
698
	 *		eg: array( 'DTT_reg_limit' => array('>', 'DTT_sold', TRUE) )
699
	 *		becomes
700
	 *		SQL >> "...WHERE DTT_reg_limit > DTT_sold"
701
	 *		Note: you can also use related model field names like you would any other field name.
702
	 *		eg: array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE)
703
	 *		could be used if you were querying EEM_Tickets (because Datetime is directly related to tickets)
704
     *		Also, by default all the where conditions are AND'd together.
705
	 *		To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together
706
	 *		eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' => 345678912))
707
	 *		becomes
708
	 *		SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp = 345678912...".
709
	 * 		Also, to negate an entire set of conditions, use 'NOT' as an array key.
710
	 *		eg: array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)
711
	 *		becomes
712
	 *		SQL >> "...where ! (TXN_total =50 AND TXN_paid =23)
713
	 *		Note: the 'glue' used to join each condition will continue to be what you last specified. IE, "AND"s by default,
714
	 *		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"
715
	 *		to join conditions, it will continue to "stick" until you specify an AND.
716
	 *		eg array('OR'=>array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN')
717
	 *		becomes
718
	 *		SQL >> "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND STS_ID='TIN'"
719
     *		They can be nested indefinitely.
720
	 *		eg: array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN'))))
721
	 *		becomes
722
	 *		SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..."
723
     *		GOTCHA:
724
	 *		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.
725
	 *		eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)),
726
	 *		as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'.
727
	 *		becomes
728
	 *		SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions).
729
     *		To overcome this, you can add a '*' character to the end of the field's name, followed by anything.
730
	 *		These will be removed when generating the SQL string, but allow for the array keys to be unique.
731
	 *		eg: you could rewrite the previous query as:
732
	 *		array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date))
733
	 *		which correctly becomes
734
	 *		SQL >> "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND PAY_timestamp != 1241234123"
735
	 *		This can be applied to condition operators too,
736
	 *		eg: array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
737
	 *	@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
738
	 *		SQL "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
739
	 *		Remember when you provide two numbers for the limit, the 1st number is the OFFSET, the 2nd is the LIMIT
740
	 *	@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.
741
	 *		Send an array in the following format array('on_join_limit' => array( 'table_alias', array(1,2) ) ).
742
	 *	@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'),
743
	 *		which would becomes SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date DESC..." respectively.
744
	 *		Like the 'where' conditions, these fields can be on related models.
745
	 *		Eg 'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is perfectly valid from any model related to 'Registration' (like Event, Attendee, Price, Datetime, etc.)
746
	 *	@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
747
	 *		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.
748
	 *		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)
749
	 *		or EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
750
	 *
751
	 *	@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')
752
	 *		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
753
	 *		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
754
	 *
755
	 *	@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)
756
	 *
757
	 *	@var array $force_join forces a join with the models named. Should be a numerically-indexed array where values are models to be joined in the query.Eg
758
	 *		array('Attendee','Payment','Datetime'). You may join with transient models using period, eg "Registration.Transaction.Payment".
759
	 *		You will probably only want to do this in hopes of increasing efficiency, as related models which belongs to the current model
760
	 *		(ie, the current model has a foreign key to them, like how Registration belongs to Attendee) can be cached in order
761
	 *		to avoid future queries
762
     *	@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
763
	 *		if you want to include them, set this query param to 'none'. If you want to ONLY disable THIS model's default where conditions
764
	 *		set it to 'other_models_only'. If you only want this model's default where conditions added to the query, use 'this_model_only'.
765
	 *		If you want to use all default where conditions (default), set to 'all'.
766
	 *	@var string $caps controls what capability requirements to apply to the query; ie, should we just NOT
767
	 *		apply any capabilities/permissions/restrictions and return everything? Or should we only show the
768
	 *		current user items they should be able to view on the frontend, backend, edit, or delete?
769
	 *		can be set to 'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
770
	 * }
771
	 * @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)
772
	 * Some full examples:
773
	 * 		get 10 transactions which have Scottish attendees:
774
	 * 		EEM_Transaction::instance()->get_all( array(
775
	 *			array(
776
	 *				'OR'=>array(
777
	 *					'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
778
	 *					'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
779
	 *				)
780
	 * 			),
781
	 *			'limit'=>10,
782
	 *			'group_by'=>'TXN_ID'
783
	 * 		));
784
	 * 		get all the answers to the question titled "shirt size" for event with id 12, ordered by their answer
785
	 * 		EEM_Answer::instance()->get_all(array(
786
	 *			array(
787
	 *				'Question.QST_display_text'=>'shirt size',
788
	 *				'Registration.Event.EVT_ID'=>12
789
	 * 			),
790
	 *			'order_by'=>array('ANS_value'=>'ASC')
791
	 *		));
792
	 * @throws \EE_Error
793
	 */
794
	public function get_all($query_params = array()){
795
		if( isset( $query_params[ 'limit' ] )
796
			&& ! isset( $query_params[ 'group_by' ] ) ) {
797
			$query_params[ 'group_by' ] = array_keys( $this->get_combined_primary_key_fields() );
798
		}
799
		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, NULL));
800
	}
801
802
	/**
803
	 * Modifies the query parameters so we only get back model objects
804
	 * that "belong" to the current user
805
	 * @param array $query_params @see EEM_Base::get_all()
806
	 * @return array like EEM_Base::get_all
807
	 */
808
	public function alter_query_params_to_only_include_mine( $query_params = array() ) {
809
		$wp_user_field_name = $this->wp_user_field_name();
810
		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...
811
			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
812
		}
813
		return $query_params;
814
	}
815
816
	/**
817
	 * Returns the name of the field's name that points to the WP_User table
818
	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
819
	 * foreign key to the WP_User table)
820
	 * @return string|boolean string on success, boolean false when there is no
821
	 * foreign key to the WP_User table
822
	 */
823
	public function wp_user_field_name() {
824
		try{
825
			if( ! empty( $this->_model_chain_to_wp_user ) ) {
826
				$models_to_follow_to_wp_users = explode( '.', $this->_model_chain_to_wp_user );
827
				$last_model_name = end( $models_to_follow_to_wp_users );
828
				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model( $last_model_name );
829
				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
830
			}else{
831
				$model_with_fk_to_wp_users = $this;
832
				$model_chain_to_wp_user = '';
833
			}
834
			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to( 'WP_User' );
835
			return $model_chain_to_wp_user . $wp_user_field->get_name();
836
		}catch( EE_Error $e ) {
837
			return false;
838
		}
839
	}
840
841
	/**
842
	 * Returns the _model_chain_to_wp_user string, which indicates which related model
843
	 * (or transiently-related model) has a foreign key to the wp_users table;
844
	 * useful for finding if model objects of this type are 'owned' by the current user.
845
	 * This is an empty string when the foreign key is on this model and when it isn't,
846
	 * but is only non-empty when this model's ownership is indicated by a RELATED model
847
	 * (or transiently-related model)
848
	 * @return string
849
	 */
850
	public function model_chain_to_wp_user(){
851
		return $this->_model_chain_to_wp_user;
852
	}
853
854
	/**
855
	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
856
	 * like how registrations don't have a foreign key to wp_users, but the
857
	 * events they are for are), or is unrelated to wp users.
858
	 * generally available
859
	 * @return boolean
860
	 */
861
	public function is_owned() {
862
		if( $this->model_chain_to_wp_user() ){
863
			return true;
864
		}else{
865
			try{
866
				$this->get_foreign_key_to( 'WP_User' );
867
				return true;
868
			}catch( EE_Error $e ){
869
				return false;
870
			}
871
		}
872
	}
873
874
875
876
	/**
877
	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but may want to
878
	 * preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on the model)
879
	 *
880
	 * @param array  $query_params      like EEM_Base::get_all's $query_params
881
	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
882
	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the fields on the model,
883
	 *                                  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.
884
	 *                                  If you would like to use these custom selections in WHERE, GROUP_BY, or HAVING clauses, you must instead provide an array.
885
	 *                                  Array keys are the aliases used to refer to this selection, and values are to be numerically-indexed arrays, where 0 is the selection
886
	 *                                  and 1 is the data type. Eg, array('count'=>array('COUNT(REG_ID)','%d'))
887
	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
888
	 * @throws \EE_Error
889
	 */
890
	protected function  _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null){
891
		// remember the custom selections, if any, and type cast as array
892
		// (unless $columns_to_select is an object, then just set as an empty array)
893
		// Note: (array) 'some string' === array( 'some string' )
894
		$this->_custom_selections = ! is_object( $columns_to_select ) ? (array) $columns_to_select : array();
895
		$model_query_info = $this->_create_model_query_info_carrier( $query_params );
896
		$select_expressions = $columns_to_select !== null
897
			? $this->_construct_select_from_input( $columns_to_select )
898
			: $this->_construct_default_select_sql( $model_query_info );
899
		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query( $model_query_info );
900
		return $this->_do_wpdb_query( 'get_results', array( $SQL, $output ) );
901
	}
902
903
	/**
904
	 * Gets an array of rows from the database just like $wpdb->get_results would,
905
	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
906
	 * take care of joins, field preparation etc.
907
	 *
908
	 * @param array $query_params like EEM_Base::get_all's $query_params
909
	 * @param string $output ARRAY_A, OBJECT_K, etc. Just like
910
	 * @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...
911
	 * 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.
912
	 * If you would like to use these custom selections in WHERE, GROUP_BY, or HAVING clauses, you must instead provide an array.
913
	 * Array keys are the aliases used to refer to this selection, and values are to be numerically-indexed arrays, where 0 is the selection
914
	 * and 1 is the data type. Eg, array('count'=>array('COUNT(REG_ID)','%d'))
915
	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
916
	 * @throws \EE_Error
917
	 */
918
	public function  get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null){
919
		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
920
	}
921
922
923
	/**
924
	 * For creating a custom select statement
925
	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
926
	 * or an array where keys are aliases, and values are arrays where 0=>the selection SQL, and 1=>is the datatype
927
	 * @throws EE_Error
928
	 * @return string
929
	 */
930
	private function _construct_select_from_input($columns_to_select){
931
		if(is_array($columns_to_select)){
932
			$select_sql_array = array();
933
934
			foreach($columns_to_select as $alias => $selection_and_datatype){
935
				if( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])){
936
					throw new EE_Error(
937
						sprintf(
938
							__(
939
								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
940
								"event_espresso"
941
							),
942
							$selection_and_datatype,
943
							$alias
944
						)
945
					);
946
				}
947
				if( ! in_array( $selection_and_datatype[1],$this->_valid_wpdb_data_types)){
948
					throw new EE_Error(
949
						sprintf(
950
							__(
951
								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
952
								"event_espresso"
953
							),
954
							$selection_and_datatype[ 1 ],
955
							$selection_and_datatype[ 0 ],
956
							$alias,
957
							implode( ",", $this->_valid_wpdb_data_types )
958
						)
959
					);
960
				}
961
				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
962
			}
963
			$columns_to_select_string = implode(", ",$select_sql_array);
964
		}else{
965
			$columns_to_select_string = $columns_to_select;
966
		}
967
		return $columns_to_select_string;
968
969
	}
970
971
972
973
	/**
974
	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
975
	 *
976
	 * @return string
977
	 * @throws \EE_Error
978
	 */
979
	public function primary_key_name(){
980
		return $this->get_primary_key_field()->get_name();
981
	}
982
983
984
985
	/**
986
	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
987
	 * If there is no primary key on this model, $id is treated as primary key string
988
	 * @param mixed $id int or string, depending on the type of the model's primary key
989
	 * @return EE_Base_Class
990
	 */
991
	public function get_one_by_ID($id){
992
		if( $this->get_from_entity_map( $id ) ){
993
			return $this->get_from_entity_map( $id );
994
		}
995
		return $this->get_one(
996
			$this->alter_query_params_to_restrict_by_ID(
997
				$id,
998
				array( 'default_where_conditions' => 'minimum' )
999
			)
1000
		);
1001
	}
1002
1003
1004
1005
	/**
1006
	 * Alters query parameters to only get items with this ID are returned.
1007
	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1008
	 * or could just be a simple primary key ID
1009
	 *
1010
	 * @param int   $id
1011
	 * @param array $query_params
1012
	 * @return array of normal query params, @see EEM_Base::get_all
1013
	 * @throws \EE_Error
1014
	 */
1015
	public function alter_query_params_to_restrict_by_ID( $id, $query_params = array() ) {
1016
		if( ! isset( $query_params[ 0 ] ) ) {
1017
			$query_params[ 0 ] = array();
1018
		}
1019
		$conditions_from_id = $this->parse_index_primary_key_string( $id );
1020
		if( $conditions_from_id === null ) {
1021
			$query_params[ 0 ][ $this->primary_key_name() ] = $id ;
1022
		}else{
1023
			//no primary key, so the $id must be from the get_index_primary_key_string()
1024
			$query_params[0] = array_replace_recursive( $query_params[ 0 ], $this->parse_index_primary_key_string( $id ) );
1025
		}
1026
		return $query_params;
1027
	}
1028
1029
1030
1031
	/**
1032
	 * 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,
1033
	 * null is returned.
1034
1035
	 *
1036
*@param array $query_params like EEM_Base's $query_params variable.
1037
	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1038
	 * @throws \EE_Error
1039
	 */
1040 View Code Duplication
	public 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...
1041
		if( ! is_array( $query_params ) ){
1042
			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' );
1043
			$query_params = array();
1044
		}
1045
		$query_params['limit'] = 1;
1046
		$items = $this->get_all($query_params);
1047
		if(empty($items)){
1048
			return null;
1049
		}else{
1050
			return array_shift($items);
1051
		}
1052
	}
1053
1054
1055
1056
	/**
1057
	 * Returns the next x number of items in sequence from the given value as
1058
	 * found in the database matching the given query conditions.
1059
	 *
1060
	 * @param mixed $current_field_value    Value used for the reference point.
1061
	 * @param null  $field_to_order_by      What field is used for the
1062
	 *                                      reference point.
1063
	 * @param int   $limit                  How many to return.
1064
	 * @param array $query_params           Extra conditions on the query.
1065
	 * @param null  $columns_to_select      If left null, then an array of
1066
	 *                                      EE_Base_Class objects is returned,
1067
	 *                                      otherwise you can indicate just the
1068
	 *                                      columns you want returned.
1069
	 * @return EE_Base_Class[]|array
1070
	 * @throws \EE_Error
1071
	 */
1072
	public function next_x( $current_field_value, $field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null ) {
1073
		return $this->_get_consecutive( $current_field_value, '>', $field_to_order_by, $limit, $query_params, $columns_to_select );
1074
	}
1075
1076
1077
1078
	/**
1079
	 * Returns the previous x number of items in sequence from the given value
1080
	 * as found in the database matching the given query conditions.
1081
	 *
1082
	 * @param mixed $current_field_value    Value used for the reference point.
1083
	 * @param null  $field_to_order_by      What field is used for the
1084
	 *                                      reference point.
1085
	 * @param int   $limit                  How many to return.
1086
	 * @param array $query_params           Extra conditions on the query.
1087
	 * @param null  $columns_to_select      If left null, then an array of
1088
	 *                                      EE_Base_Class objects is returned,
1089
	 *                                      otherwise you can indicate just the
1090
	 *                                      columns you want returned.
1091
	 * @return EE_Base_Class[]|array
1092
	 * @throws \EE_Error
1093
	 */
1094
	public function previous_x( $current_field_value, $field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null ) {
1095
		return $this->_get_consecutive( $current_field_value, '<', $field_to_order_by, $limit, $query_params, $columns_to_select );
1096
	}
1097
1098
1099
1100
	/**
1101
	 * Returns the next item in sequence from the given value as found in the
1102
	 * database matching the given query conditions.
1103
	 *
1104
	 * @param mixed $current_field_value    Value used for the reference point.
1105
	 * @param null  $field_to_order_by      What field is used for the
1106
	 *                                      reference point.
1107
	 * @param array $query_params           Extra conditions on the query.
1108
	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1109
	 *                                      object is returned, otherwise you
1110
	 *                                      can indicate just the columns you
1111
	 *                                      want and a single array indexed by
1112
	 *                                      the columns will be returned.
1113
	 * @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...
1114
	 * @throws \EE_Error
1115
	 */
1116
	public function next( $current_field_value, $field_to_order_by = null, $query_params = array(), $columns_to_select = null ) {
1117
		$results = $this->_get_consecutive( $current_field_value, '>', $field_to_order_by, 1, $query_params, $columns_to_select );
1118
		return empty( $results ) ? null : reset( $results );
1119
	}
1120
1121
1122
1123
1124
	/**
1125
	 * Returns the previous item in sequence from the given value as found in
1126
	 * the database matching the given query conditions.
1127
	 *
1128
	 * @param mixed $current_field_value    Value used for the reference point.
1129
	 * @param null $field_to_order_by       What field is used for the
1130
	 *                                      reference point.
1131
	 * @param array $query_params           Extra conditions on the query.
1132
	 * @param null $columns_to_select       If left null, then an EE_Base_Class
1133
	 *                                      object is returned, otherwise you
1134
	 *                                      can indicate just the columns you
1135
	 *                                      want and a single array indexed by
1136
	 *                                      the columns will be returned.
1137
 * @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...
1138
	 * @throws EE_Error
1139
	 */
1140
	public function previous( $current_field_value, $field_to_order_by = null, $query_params = array(), $columns_to_select = null ) {
1141
		$results = $this->_get_consecutive( $current_field_value, '<', $field_to_order_by, 1, $query_params, $columns_to_select );
1142
		return empty( $results ) ? null : reset( $results );
1143
	}
1144
1145
1146
1147
1148
1149
	/**
1150
	 * Returns the a consecutive number of items in sequence from the given
1151
	 * value as found in the database matching the given query conditions.
1152
	 *
1153
	 * @param mixed $current_field_value    Value used for the reference point.
1154
	 * @param string $operand               What operand is used for the sequence.
1155
	 * @param string $field_to_order_by     What field is used for the reference point.
1156
	 * @param int $limit                    How many to return.
1157
	 * @param array $query_params           Extra conditions on the query.
1158
	 * @param null $columns_to_select       If left null, then an array of EE_Base_Class objects is returned,
1159
	 *                                      otherwise you can indicate just the columns you want returned.
1160
	 * @return EE_Base_Class[]|array
1161
	 * @throws EE_Error
1162
	 */
1163
	protected function _get_consecutive( $current_field_value, $operand = '>', $field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null ) {
1164
		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1165
		if ( empty( $field_to_order_by ) ) {
1166
			if ( $this->has_primary_key_field() ) {
1167
				$field_to_order_by = $this->get_primary_key_field()->get_name();
1168
			} else {
1169
1170
				if ( WP_DEBUG ) {
1171
					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' ) );
1172
				}
1173
				EE_Error::add_error( __('There was an error with the query.', 'event_espresso') );
1174
				return array();
1175
			}
1176
		}
1177
1178
		if( ! is_array( $query_params ) ){
1179
			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' );
1180
			$query_params = array();
1181
		}
1182
1183
		//let's add the where query param for consecutive look up.
1184
		$query_params[0][ $field_to_order_by ] = array( $operand, $current_field_value );
1185
		$query_params['limit'] = $limit;
1186
1187
		//set direction
1188
		$incoming_orderby = isset( $query_params['order_by'] ) ? (array)$query_params['order_by'] : array();
1189
		$query_params['order_by'] = $operand === '>'
1190
			? array( $field_to_order_by => 'ASC' ) + $incoming_orderby
1191
			: array( $field_to_order_by => 'DESC') + $incoming_orderby;
1192
1193
		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1194
		if ( empty( $columns_to_select ) ) {
1195
			return $this->get_all( $query_params );
1196
		} else {
1197
			//getting just the fields
1198
			return $this->_get_all_wpdb_results( $query_params, ARRAY_A, $columns_to_select );
1199
		}
1200
	}
1201
1202
1203
1204
1205
	/**
1206
	 * This sets the _timezone property after model object has been instantiated.
1207
	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1208
	 */
1209
	public function set_timezone( $timezone ) {
1210
		if ( $timezone !== null ) {
1211
			$this->_timezone = $timezone;
1212
		}
1213
		//note we need to loop through relations and set the timezone on those objects as well.
1214
		foreach ( $this->_model_relations as $relation ) {
1215
			$relation->set_timezone( $timezone );
1216
		}
1217
		//and finally we do the same for any datetime fields
1218
		foreach ( $this->_fields as $field ) {
1219
			if ( $field instanceof EE_Datetime_Field ) {
1220
				$field->set_timezone( $timezone );
1221
			}
1222
		}
1223
	}
1224
1225
1226
1227
	/**
1228
	 * This just returns whatever is set for the current timezone.
1229
	 *
1230
	 * @access public
1231
	 * @return string
1232
	 */
1233
	public function get_timezone() {
1234
		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1235
		if ( empty( $this->_timezone ) ) {
1236
			foreach( $this->_fields as $field ) {
1237
				if ( $field instanceof EE_Datetime_Field ) {
1238
					$this->set_timezone($field->get_timezone());
1239
					break;
1240
				}
1241
			}
1242
		}
1243
1244
		//if timezone STILL empty then return the default timezone for the site.
1245
		if ( empty( $this->_timezone ) ) {
1246
			$this->set_timezone( EEH_DTT_Helper::get_timezone() );
1247
		}
1248
		return $this->_timezone;
1249
	}
1250
1251
1252
1253
	/**
1254
	 * This returns the date formats set for the given field name and also ensures that
1255
	 * $this->_timezone property is set correctly.
1256
	 *
1257
	 * @since 4.6.x
1258
	 * @param string $field_name The name of the field the formats are being retrieved for.
1259
	 * @param bool   $pretty          Whether to return the pretty formats (true) or not (false).
1260
	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1261
	 *
1262
	 * @return array formats in an array with the date format first, and the time format last.
1263
	 */
1264
	public function get_formats_for( $field_name, $pretty = false ) {
1265
		$field_settings = $this->field_settings_for( $field_name );
1266
1267
		//if not a valid EE_Datetime_Field then throw error
1268
		if ( ! $field_settings instanceof EE_Datetime_Field ) {
1269
			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 ) );
1270
		}
1271
1272
		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1273
		//the field.
1274
		$this->_timezone = $field_settings->get_timezone();
1275
1276
		return array( $field_settings->get_date_format( $pretty ), $field_settings->get_time_format( $pretty ) );
1277
	}
1278
1279
1280
1281
	/**
1282
	 * This returns the current time in a format setup for a query on this model.
1283
	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1284
	 * it will return:
1285
	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for NOW
1286
	 *  - or a unix timestamp (equivalent to time())
1287
	 *
1288
	 * @since 4.6.x
1289
	 * @param string $field_name The field the current time is needed for.
1290
	 * @param bool   $timestamp  True means to return a unix timestamp. Otherwise a
1291
	 *                           		 formatted string matching the set format for the field in the set timezone will
1292
	 *                           		 be returned.
1293
	 * @param string $what         Whether to return the string in just the time format, the date format, or both.
1294
	 *
1295
	 * @throws EE_Error   	If the given field_name is not of the EE_Datetime_Field type.
1296
	 *
1297
	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1298
	 *                    	     exception is triggered.
1299
	 */
1300
	public function current_time_for_query( $field_name, $timestamp = false, $what = 'both' ) {
1301
		$formats = $this->get_formats_for( $field_name );
1302
1303
		$DateTime = new DateTime( "now", new DateTimeZone( $this->_timezone ) );
1304
1305
		if ( $timestamp ) {
1306
			return $DateTime->format( 'U' );
1307
		}
1308
1309
		//not returning timestamp, so return formatted string in timezone.
1310
		switch( $what ) {
1311
			case 'time' :
1312
				return $DateTime->format( $formats[1] );
1313
				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...
1314
			case 'date' :
1315
				return $DateTime->format( $formats[0] );
1316
				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...
1317
			default :
1318
				return $DateTime->format( implode( ' ', $formats ) );
1319
				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...
1320
		}
1321
	}
1322
1323
1324
1325
	/**
1326
	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1327
	 * for the model are.  Returns a DateTime object.
1328
	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1329
	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is ignored.
1330
	 *
1331
	 * @param string $field_name      The field being setup.
1332
	 * @param string $timestring      The date time string being used.
1333
	 * @param string $incoming_format The format for the time string.
1334
	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1335
	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming format is
1336
	 *                                'U', this is ignored.
1337
	 * @return DateTime
1338
	 * @throws \EE_Error
1339
	 */
1340
	public function convert_datetime_for_query( $field_name, $timestring, $incoming_format, $timezone = '' ) {
1341
1342
		//just using this to ensure the timezone is set correctly internally
1343
		$this->get_formats_for( $field_name );
1344
1345
		//load EEH_DTT_Helper
1346
		$set_timezone = empty( $timezone ) ? EEH_DTT_Helper::get_timezone() : $timezone;
1347
1348
		$incomingDateTime = date_create_from_format( $incoming_format, $timestring, new DateTimeZone( $set_timezone ) );
1349
1350
		return $incomingDateTime->setTimezone( new DateTimeZone( $this->_timezone ) );
1351
	}
1352
1353
1354
1355
1356
	/**
1357
	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1358
	 * @return EE_Table_Base[]
1359
	 */
1360
	public function get_tables(){
1361
		return $this->_tables;
1362
	}
1363
1364
1365
1366
	/**
1367
	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1368
	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1369
	 * 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,
1370
	 * it inserts an entry in the secondary table.
1371
	 * 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
1372
	 * (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.
1373
	 * 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,
1374
	 * the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which are not specified)
1375
	 *
1376
*@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.
1377
	 * 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,
1378
	 * we'd use this method as follows:
1379
	 * EEM_Transaction::instance()->update(
1380
	 *		array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1381
	 *		array(array('TXN_ID'=>34)));
1382
	 * @param array $query_params very much like EEM_Base::get_all's $query_params
1383
	 * 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
1384
	 * 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,
1385
	 * 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
1386
	 * 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
1387
	 * 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
1388
	 * escape HTML characters in the prepare_for_set method...)
1389
	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1390
	 * in this model's entity map according to $fields_n_values that match $query_params. This
1391
	 * obviously has some overhead, so you can disable it by setting this to FALSE, but
1392
	 * be aware that model objects being used could get out-of-sync with the database
1393
	 * @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)
1394
	 * @throws \EE_Error
1395
	 */
1396
	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = TRUE){
1397
		if( ! is_array( $query_params ) ){
1398
			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' );
1399
			$query_params = array();
1400
		}
1401
		/**
1402
		 * Action called before a model update call has been made.
1403
		 *
1404
		 * @param EEM_Base $model
1405
		 * @param array $fields_n_values the updated fields and their new values
1406
		 * @param array $query_params @see EEM_Base::get_all()
1407
		 */
1408
		do_action( 'AHEE__EEM_Base__update__begin',$this, $fields_n_values, $query_params );
1409
		/**
1410
		 * Filters the fields about to be updated given the query parameters. You can provide the
1411
		 * $query_params to $this->get_all() to find exactly which records will be updated
1412
		 * @param array $fields_n_values fields and their new values
1413
		 * @param EEM_Base $model the model being queried
1414
		 * @param array $query_params see EEM_Base::get_all()
1415
		 */
1416
		$fields_n_values = (array)apply_filters( 'FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this, $query_params );
1417
		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1418
		//to do that, for each table, verify that it's PK isn't null.
1419
		$tables= $this->get_tables();
1420
1421
		//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
1422
		//NOTE: we should make this code more efficient by NOT querying twice
1423
		//before the real update, but that needs to first go through ALPHA testing
1424
		//as it's dangerous. says Mike August 8 2014
1425
1426
			//we want to make sure the default_where strategy is ignored
1427
			$this->_ignore_where_strategy = TRUE;
1428
			$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1429
			foreach( $wpdb_select_results as $wpdb_result ){
1430
				// type cast stdClass as array
1431
				$wpdb_result = (array)$wpdb_result;
1432
				//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1433
				if( $this->has_primary_key_field() ){
1434
					$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1435
				}else{
1436
					//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)
1437
					$main_table_pk_value = null;
1438
				}
1439
				//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
1440
				//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
1441
				if(count($tables) > 1){
1442
					//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1443
					//in that table, and so we'll want to insert one
1444
					foreach($tables as $table_obj){
1445
						$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1446
						//if there is no private key for this table on the results, it means there's no entry
1447
						//in this table, right? so insert a row in the current table, using any fields available
1448
						if( ! ( array_key_exists( $this_table_pk_column, $wpdb_result) && $wpdb_result[ $this_table_pk_column ] )){
1449
							$success = $this->_insert_into_specific_table($table_obj, $fields_n_values, $main_table_pk_value);
1450
							//if we died here, report the error
1451
							if( ! $success ) {
1452
								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...
1453
							}
1454
						}
1455
					}
1456
				}
1457
1458
//				//and now check that if we have cached any models by that ID on the model, that
1459
//				//they also get updated properly
1460
//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1461
//				if( $model_object ){
1462
//					foreach( $fields_n_values as $field => $value ){
1463
//						$model_object->set($field, $value);
1464
			//let's make sure default_where strategy is followed now
1465
			$this->_ignore_where_strategy = FALSE;
1466
		}
1467
		//if we want to keep model objects in sync, AND
1468
		//if this wasn't called from a model object (to update itself)
1469
		//then we want to make sure we keep all the existing
1470
		//model objects in sync with the db
1471
		if( $keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object ){
1472
			if( $this->has_primary_key_field() ){
1473
				$model_objs_affected_ids = $this->get_col( $query_params );
1474
			}else{
1475
				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1476
				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A );
1477
				$model_objs_affected_ids = array();
1478
				foreach( $models_affected_key_columns as $row ){
1479
					$combined_index_key = $this->get_index_primary_key_string( $row );
1480
					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1481
				}
1482
1483
			}
1484
1485
			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...
1486
				//wait wait wait- if nothing was affected let's stop here
1487
				return 0;
1488
			}
1489
			foreach( $model_objs_affected_ids as $id ){
1490
				$model_obj_in_entity_map = $this->get_from_entity_map( $id );
1491
				if( $model_obj_in_entity_map ){
1492
					foreach( $fields_n_values as $field => $new_value ){
1493
						$model_obj_in_entity_map->set( $field, $new_value );
1494
					}
1495
				}
1496
			}
1497
			//if there is a primary key on this model, we can now do a slight optimization
1498
			if( $this->has_primary_key_field() ){
1499
				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1500
				$query_params = array(
1501
					array( $this->primary_key_name() => array( 'IN', $model_objs_affected_ids ) ),
1502
					'limit' => count( $model_objs_affected_ids ), 'default_where_conditions' => 'none' );
1503
			}
1504
		}
1505
1506
		$model_query_info = $this->_create_model_query_info_carrier( $query_params );
1507
		$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.
1508
		$rows_affected = $this->_do_wpdb_query('query', array( $SQL ) );
1509
		/**
1510
		 * Action called after a model update call has been made.
1511
		 *
1512
		 * @param EEM_Base $model
1513
		 * @param array $fields_n_values the updated fields and their new values
1514
		 * @param array $query_params @see EEM_Base::get_all()
1515
		 * @param int $rows_affected
1516
		 */
1517
		do_action( 'AHEE__EEM_Base__update__end',$this, $fields_n_values, $query_params, $rows_affected );
1518
		return $rows_affected;//how many supposedly got updated
1519
	}
1520
1521
1522
1523
	/**
1524
	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1525
	 * are teh values of the field specified (or by default the primary key field)
1526
	 * that matched the query params. Note that you should pass the name of the
1527
	 * model FIELD, not the database table's column name.
1528
	 *
1529
	 * @param array  $query_params @see EEM_Base::get_all()
1530
	 * @param string $field_to_select
1531
	 * @return array just like $wpdb->get_col()
1532
	 * @throws \EE_Error
1533
	 */
1534
	public function get_col( $query_params  = array(), $field_to_select = NULL ){
1535
1536
		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...
1537
			$field = $this->field_settings_for( $field_to_select );
1538
		}elseif( $this->has_primary_key_field ( ) ){
1539
			$field = $this->get_primary_key_field();
1540
		}else{
1541
			//no primary key, just grab the first column
1542
			$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...
1543
		}
1544
1545
1546
		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1547
		$select_expressions = $field->get_qualified_column();
1548
		$SQL ="SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1549
		return $this->_do_wpdb_query('get_col', array( $SQL ) );
1550
	}
1551
1552
1553
1554
	/**
1555
	 * Returns a single column value for a single row from the database
1556
	 *
1557
	 * @param array  $query_params    @see EEM_Base::get_all()
1558
	 * @param string $field_to_select @see EEM_Base::get_col()
1559
	 * @return string
1560
	 * @throws \EE_Error
1561
	 */
1562
	public function get_var( $query_params = array(), $field_to_select = NULL ) {
1563
		$query_params[ 'limit' ] = 1;
1564
		$col = $this->get_col( $query_params, $field_to_select );
1565
		if( ! empty( $col ) ) {
1566
			return reset( $col );
1567
		}else{
1568
			return NULL;
1569
		}
1570
	}
1571
1572
1573
1574
	/**
1575
	 * 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?',..."
1576
	 * Values are filtered through wpdb->prepare to avoid against SQL injection, but currently no further filtering is done
1577
	 *
1578
	 * @global      $wpdb
1579
	 * @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
1580
	 * @return string of SQL
1581
	 * @throws \EE_Error
1582
	 */
1583
	public function _construct_update_sql($fields_n_values){
1584
		/** @type WPDB $wpdb */
1585
		global $wpdb;
1586
		$cols_n_values = array();
1587
		foreach($fields_n_values as $field_name => $value){
1588
			$field_obj = $this->field_settings_for($field_name);
1589
			//if the value is NULL, we want to assign the value to that.
1590
			//wpdb->prepare doesn't really handle that properly
1591
			$prepared_value = $this->_prepare_value_or_use_default( $field_obj, $fields_n_values );
1592
			$value_sql = $prepared_value===NULL ? 'NULL' : $wpdb->prepare( $field_obj->get_wpdb_data_type(), $prepared_value );
1593
			$cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1594
		}
1595
		return implode(",",$cols_n_values);
1596
1597
	}
1598
1599
1600
1601
	/**
1602
	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1603
	 * Performs a HARD delete, meaning the database row should always be removed,
1604
	 * not just have a flag field on it switched
1605
	 * Wrapper for EEM_Base::delete_permanently()
1606
	 *
1607
	 * @param mixed $id
1608
	 * @return boolean whether the row got deleted or not
1609
	 * @throws \EE_Error
1610
	 */
1611
	public function delete_permanently_by_ID( $id ) {
1612
		return $this->delete_permanently(
1613
			array(
1614
				array( $this->get_primary_key_field()->get_name() => $id ),
1615
				'limit' 	=> 1
1616
			)
1617
		);
1618
	}
1619
1620
1621
1622
	/**
1623
	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1624
	 * Wrapper for EEM_Base::delete()
1625
	 *
1626
	 * @param mixed $id
1627
	 * @return boolean whether the row got deleted or not
1628
	 * @throws \EE_Error
1629
	 */
1630
	public function delete_by_ID( $id ){
1631
		return $this->delete(
1632
			array(
1633
				array( $this->get_primary_key_field()->get_name() => $id ),
1634
				'limit' 	=> 1
1635
			)
1636
		);
1637
	}
1638
1639
1640
1641
	/**
1642
	 * Identical to delete_permanently, but does a "soft" delete if possible,
1643
	 * meaning if the model has a field that indicates its been "trashed" or
1644
	 * "soft deleted", we will just set that instead of actually deleting the rows.
1645
	 *
1646
	 * @see EEM_Base::delete_permanently
1647
	 * @param array   $query_params
1648
	 * @param boolean $allow_blocking
1649
	 * @return int how many rows got deleted
1650
	 * @throws \EE_Error
1651
	 */
1652
	public function delete($query_params,$allow_blocking = true){
1653
		return $this->delete_permanently($query_params, $allow_blocking);
1654
	}
1655
1656
1657
1658
	/**
1659
	 * Deletes the model objects that meet the query params. Note: this method is overridden
1660
	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1661
	 * as archived, not actually deleted
1662
	 *
1663
	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1664
	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1665
	 *                                that blocks it (ie, there' sno other data that depends on this data); if false, deletes regardless of other objects
1666
	 *                                which may depend on it. Its generally advisable to always leave this as TRUE, otherwise you could easily corrupt your DB
1667
	 * @return int how many rows got deleted
1668
	 * @throws \EE_Error
1669
	 */
1670
	public function delete_permanently($query_params,$allow_blocking = true){
1671
		/**
1672
		 * Action called just before performing a real deletion query. You can use the
1673
		 * model and its $query_params to find exactly which items will be deleted
1674
		 * @param EEM_Base $model
1675
		 * @param array $query_params @see EEM_Base::get_all()
1676
		 * @param boolean $allow_blocking whether or not to allow related model objects
1677
		 * to block (prevent) this deletion
1678
		 */
1679
		do_action( 'AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking );
1680
		//some MySQL databases may be running safe mode, which may restrict
1681
		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1682
		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1683
		//to delete them
1684
		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1685
		$deletion_where = $this->_setup_ids_for_delete( $items_for_deletion, $allow_blocking);
1686
		if($deletion_where){
1687
			//echo "objects for deletion:";var_dump($objects_for_deletion);
1688
			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1689
			$table_aliases = array_keys( $this->_tables );
1690
			$SQL = "DELETE ".implode(", ",$table_aliases)." FROM ".$model_query_info->get_full_join_sql()." WHERE ".$deletion_where;
1691
1692
			//		/echo "delete sql:$SQL";
1693
			$rows_deleted = $this->_do_wpdb_query( 'query', array( $SQL ) );
1694
		}else{
1695
			$rows_deleted = 0;
1696
		}
1697
1698
		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1699
		if( $this->has_primary_key_field() ){
1700
			foreach($items_for_deletion as $item_for_deletion_row ){
1701
				$pk_value = $item_for_deletion_row[ $this->get_primary_key_field()->get_qualified_column() ];
1702 View Code Duplication
				if( isset( $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $pk_value ] ) ){
1703
					unset( $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $pk_value ] );
1704
				}
1705
			}
1706
		}
1707
1708
		/**
1709
		 * Action called just after performing a real deletion query. Although at this point the
1710
		 * items should have been deleted
1711
		 * @param EEM_Base $model
1712
		 * @param array $query_params @see EEM_Base::get_all()
1713
		 * @param int $rows_deleted
1714
		 */
1715
		do_action( 'AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted );
1716
		return $rows_deleted;//how many supposedly got deleted
1717
	}
1718
1719
1720
1721
	/**
1722
	 * Checks all the relations that throw error messages when there are blocking related objects
1723
	 * for related model objects. If there are any related model objects on those relations,
1724
	 * adds an EE_Error, and return true
1725
	 *
1726
	 * @param EE_Base_Class|int $this_model_obj_or_id
1727
	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which should be ignored when
1728
	 *                                                 determining whether there are related model objects which block this model object's deletion. Useful
1729
	 *                                                 if you know A is related to B and are considering deleting A, but want to see if A has any other objects
1730
	 *                                                 blocking its deletion before removing the relation between A and B
1731
	 * @return boolean
1732
	 * @throws \EE_Error
1733
	 */
1734
	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null){
1735
		//first, if $ignore_this_model_obj was supplied, get its model
1736
		if($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class){
1737
			$ignored_model = $ignore_this_model_obj->get_model();
1738
		}else{
1739
			$ignored_model = null;
1740
		}
1741
		//now check all the relations of $this_model_obj_or_id and see if there
1742
		//are any related model objects blocking it?
1743
		$is_blocked = false;
1744
		foreach($this->_model_relations as $relation_name => $relation_obj){
1745
			if( $relation_obj->block_delete_if_related_models_exist()){
1746
				//if $ignore_this_model_obj was supplied, then for the query
1747
				//on that model needs to be told to ignore $ignore_this_model_obj
1748
				if($ignored_model && $relation_name === $ignored_model->get_this_model_name()){
1749
					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id,array(
1750
					array($ignored_model->get_primary_key_field()->get_name() => array('!=',$ignore_this_model_obj->ID()))));
0 ignored issues
show
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...
1751
				}else{
1752
					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1753
				}
1754
1755
				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...
1756
					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1757
					$is_blocked = true;
1758
				}
1759
			}
1760
		}
1761
		return $is_blocked;
1762
	}
1763
1764
1765
1766
	/**
1767
	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as well.
1768
	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1769
	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model info
1770
	 * that blocks it (ie, there' sno other data that depends on this data); if false, deletes regardless of other objects
1771
	 * which may depend on it. Its generally advisable to always leave this as TRUE, otherwise you could easily corrupt your DB
1772
	 * @throws EE_Error
1773
	 * @return string    everything that comes after the WHERE statement.
1774
	 */
1775
	protected function _setup_ids_for_delete( $objects_for_deletion, $allow_blocking = true) {
1776
		if($this->has_primary_key_field()){
1777
			$primary_table = $this->_get_main_table();
1778
			$other_tables = $this->_get_other_tables();
1779
			$deletes = $query = array();
1780
			foreach ( $objects_for_deletion as $delete_object ) {
1781
				//before we mark this object for deletion,
1782
				//make sure there's no related objects blocking its deletion (if we're checking)
1783
				if (
1784
					$allow_blocking
1785
				    && $this->delete_is_blocked_by_related_models(
1786
						$delete_object[ $primary_table->get_fully_qualified_pk_column() ]
1787
					)
1788
				) {
1789
					continue;
1790
				}
1791
				//primary table deletes
1792
				if ( isset( $delete_object[ $primary_table->get_fully_qualified_pk_column() ] ) ) {
1793
					$deletes[ $primary_table->get_fully_qualified_pk_column() ][] = $delete_object[ $primary_table->get_fully_qualified_pk_column() ];
1794
				}
1795
				//other tables
1796
				if ( ! empty( $other_tables ) ) {
1797
					foreach ( $other_tables as $ot ) {
1798
						//first check if we've got the foreign key column here.
1799 View Code Duplication
						if ( isset( $delete_object[ $ot->get_fully_qualified_fk_column() ] ) ) {
1800
							$deletes[ $ot->get_fully_qualified_pk_column() ][] = $delete_object[ $ot->get_fully_qualified_fk_column() ];
1801
						}
1802
						// wait! it's entirely possible that we'll have a the primary key
1803
						// for this table in here, if it's a foreign key for one of the other secondary tables
1804 View Code Duplication
						if ( isset( $delete_object[ $ot->get_fully_qualified_pk_column() ] ) ) {
1805
							$deletes[ $ot->get_fully_qualified_pk_column() ][] = $delete_object[ $ot->get_fully_qualified_pk_column() ];
1806
						}
1807
						// finally, it is possible that the fk for this table is found
1808
						// in the fully qualified pk column for the fk table, so let's see if that's there!
1809 View Code Duplication
						if ( isset( $delete_object[ $ot->get_fully_qualified_pk_on_fk_table() ] ) ) {
1810
							$deletes[ $ot->get_fully_qualified_pk_column() ][] = $delete_object[ $ot->get_fully_qualified_pk_column() ];
1811
						}
1812
					}
1813
				}
1814
			}
1815
1816
			//we should have deletes now, so let's just go through and setup the where statement
1817
			foreach ( $deletes as $column => $values ) {
1818
				//make sure we have unique $values;
1819
				$values = array_unique($values);
1820
				$query[] = $column . ' IN(' . implode(",",$values) . ')';
1821
			}
1822
1823
			return !empty($query) ? implode(' AND ', $query ) : '';
1824
		}elseif(count($this->get_combined_primary_key_fields()) > 1){
1825
			$ways_to_identify_a_row = array();
1826
			$fields = $this->get_combined_primary_key_fields();
1827
			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
1828
			foreach($objects_for_deletion as  $delete_object){
1829
				$values_for_each_cpk_for_a_row = array();
1830
				foreach($fields as $cpk_field){
1831
					if ( $cpk_field instanceof EE_Model_Field_Base ){
1832
						$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
1833
						                                   . "="
1834
						                                   . $delete_object[ $cpk_field->get_qualified_column() ];
1835
					}
1836
				}
1837
				$ways_to_identify_a_row[] = "(".implode(" AND ",$values_for_each_cpk_for_a_row).")";
1838
			}
1839
			return implode(" OR ",$ways_to_identify_a_row);
1840
		}else{
1841
			//so there's no primary key and no combined key...
1842
			//sorry, can't help you
1843
			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)));
1844
		}
1845
	}
1846
1847
1848
1849
	/**
1850
	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
1851
	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's column
1852
	 *
1853
	 * @param array  $query_params   like EEM_Base::get_all's
1854
	 * @param string $field_to_count field on model to count by (not column name)
1855
	 * @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;
1856
	 * @return int
1857
	 * @throws \EE_Error
1858
	 */
1859
	public function count($query_params =array(),$field_to_count = NULL, $distinct = FALSE){
1860
		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1861
		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...
1862
			$field_obj = $this->field_settings_for($field_to_count);
1863
			$column_to_count = $field_obj->get_qualified_column();
1864
		}elseif($this->has_primary_key_field ()){
1865
			$pk_field_obj = $this->get_primary_key_field();
1866
			$column_to_count = $pk_field_obj->get_qualified_column();
1867
		}else{
1868
			//there's no primary key
1869
			//if we're counting distinct items, and there's no primary key,
1870
			//we need to list out the columns for distinction;
1871
			//otherwise we can just use star
1872
			if( $distinct ) {
1873
				$columns_to_use = array();
1874
				foreach( $this->get_combined_primary_key_fields() as $field_obj ) {
1875
					$columns_to_use[] = $field_obj->get_qualified_column();
1876
				}
1877
				$column_to_count = implode(',', $columns_to_use );
1878
			} else {
1879
				$column_to_count = '*';
1880
			}
1881
1882
		}
1883
1884
		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
1885
		$SQL ="SELECT COUNT(".$column_to_count.")" . $this->_construct_2nd_half_of_select_query($model_query_info);
1886
		return (int)$this->_do_wpdb_query( 'get_var', array( $SQL) );
1887
	}
1888
1889
1890
1891
	/**
1892
	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
1893
	 *
1894
	 * @param array  $query_params like EEM_Base::get_all
1895
	 * @param string $field_to_sum name of field (array key in $_fields array)
1896
	 * @return float
1897
	 * @throws \EE_Error
1898
	 */
1899
	public function sum($query_params, $field_to_sum = NULL){
1900
		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1901
1902
		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...
1903
			$field_obj = $this->field_settings_for($field_to_sum);
1904
1905
		}else{
1906
			$field_obj = $this->get_primary_key_field();
1907
		}
1908
		$column_to_count = $field_obj->get_qualified_column();
1909
1910
		$SQL ="SELECT SUM(".$column_to_count.")" . $this->_construct_2nd_half_of_select_query($model_query_info);
1911
		$return_value = $this->_do_wpdb_query('get_var',array( $SQL ) );
1912
		$data_type = $field_obj->get_wpdb_data_type();
1913
		if( $data_type === '%d' || $data_type === '%s' ){
1914
			return (float)$return_value;
1915
		}else{//must be %f
1916
			return (float)$return_value;
1917
		}
1918
	}
1919
1920
1921
1922
	/**
1923
	 * Just calls the specified method on $wpdb with the given arguments
1924
	 * Consolidates a little extra error handling code
1925
	 * @param string $wpdb_method
1926
	 * @param array  $arguments_to_provide
1927
	 * @throws EE_Error
1928
	 * @global wpdb $wpdb
1929
	 * @return mixed
1930
	 */
1931
	protected function _do_wpdb_query( $wpdb_method, $arguments_to_provide ){
1932
		//if we're in maintenance mode level 2, DON'T run any queries
1933
		//because level 2 indicates the database needs updating and
1934
		//is probably out of sync with the code
1935
		if( ! EE_Maintenance_Mode::instance()->models_can_query()){
1936
			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")));
1937
		}
1938
		/** @type WPDB $wpdb */
1939
		global $wpdb;
1940 View Code Duplication
		if( ! method_exists( $wpdb, $wpdb_method ) ){
1941
			throw new EE_Error( sprintf( __( 'There is no method named "%s" on Wordpress\' $wpdb object','event_espresso' ), $wpdb_method ) );
1942
		}
1943
		if( WP_DEBUG ){
1944
			$old_show_errors_value = $wpdb->show_errors;
1945
			$wpdb->show_errors( FALSE );
1946
		}
1947
		$result = $this->_process_wpdb_query( $wpdb_method, $arguments_to_provide );
1948
		$this->show_db_query_if_previously_requested( $wpdb->last_query );
1949
		if( WP_DEBUG ){
1950
			$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...
1951
			if( ! empty( $wpdb->last_error ) ){
1952
				throw new EE_Error( sprintf( __( 'WPDB Error: "%s"', 'event_espresso' ), $wpdb->last_error ) );
1953
			}elseif( $result === false ){
1954
				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 ) ) );
1955
			}
1956
		}elseif( $result === false ) {
1957
			EE_Error::add_error(
1958
				sprintf(
1959
					__( 'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"', 'event_espresso' ),
1960
					$wpdb_method,
1961
					var_export( $arguments_to_provide, true ),
1962
					$wpdb->last_error
1963
				),
1964
				__FILE__,
1965
				__FUNCTION__,
1966
				__LINE__
1967
			);
1968
		}
1969
		return $result;
1970
	}
1971
1972
1973
1974
	/**
1975
	 * Attempts to run the indicated WPDB method with the provided arguments,
1976
	 * and if there's an error tries to verify the DB is correct. Uses
1977
	 * the static property EEM_Base::$_db_verification_level to determine whether
1978
	 * we should try to fix the EE core db, the addons, or just give up
1979
	 * @param string $wpdb_method
1980
	 * @param array $arguments_to_provide
1981
	 * @return mixed
1982
	 */
1983
	private function _process_wpdb_query( $wpdb_method, $arguments_to_provide ) {
1984
		/** @type WPDB $wpdb */
1985
		global $wpdb;
1986
		$wpdb->last_error = null;
1987
		$result = call_user_func_array( array( $wpdb, $wpdb_method ), $arguments_to_provide );
1988
		// was there an error running the query? but we don't care on new activations
1989
		// (we're going to setup the DB anyway on new activations)
1990
		if ( ( $result === false || ! empty( $wpdb->last_error ) )
1991
			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
1992
		) {
1993
			switch ( EEM_Base::$_db_verification_level ) {
1994
1995
				case EEM_Base::db_verified_none :
1996
					// let's double-check core's DB
1997
					$error_message = $this->_verify_core_db( $wpdb_method, $arguments_to_provide );
1998
					break;
1999
2000
				case EEM_Base::db_verified_core :
2001
					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2002
					$error_message = $this->_verify_addons_db( $wpdb_method, $arguments_to_provide );
2003
					break;
2004
2005
				case EEM_Base::db_verified_addons :
2006
					// ummmm... you in trouble
2007
					return $result;
2008
					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...
2009
			}
2010
			if ( ! empty( $error_message ) ) {
2011
				EE_Log::instance()->log( __FILE__, __FUNCTION__, $error_message, 'error' );
2012
				trigger_error( $error_message );
2013
			}
2014
			return $this->_process_wpdb_query( $wpdb_method, $arguments_to_provide );
2015
2016
		}
2017
2018
		return $result;
2019
	}
2020
2021
2022
2023
	/**
2024
	 * Verifies the EE core database is up-to-date and records that we've done it on
2025
	 * EEM_Base::$_db_verification_level
2026
	 * @param string $wpdb_method
2027
	 * @param array $arguments_to_provide
2028
	 * @return string
2029
	 */
2030 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...
2031
		/** @type WPDB $wpdb */
2032
		global $wpdb;
2033
		//ok remember that we've already attempted fixing the core db, in case the problem persists
2034
		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2035
		$error_message = sprintf(
2036
			__( 'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB', 'event_espresso' ),
2037
			$wpdb->last_error,
2038
			$wpdb_method,
2039
			json_encode( $arguments_to_provide )
2040
		);
2041
		EE_System::instance()->initialize_db_if_no_migrations_required( false, true );
2042
		return $error_message;
2043
	}
2044
2045
2046
2047
	/**
2048
	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2049
	 * EEM_Base::$_db_verification_level
2050
	 * @param $wpdb_method
2051
	 * @param $arguments_to_provide
2052
	 * @return string
2053
	 */
2054 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...
2055
		/** @type WPDB $wpdb */
2056
		global $wpdb;
2057
		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2058
		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2059
		$error_message = sprintf(
2060
			__( 'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB', 'event_espresso' ),
2061
			$wpdb->last_error,
2062
			$wpdb_method,
2063
			json_encode( $arguments_to_provide )
2064
		);
2065
		EE_System::instance()->initialize_addons();
2066
		return $error_message;
2067
	}
2068
2069
2070
2071
	/**
2072
	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2073
	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2074
	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING ..."
2075
	 * @param EE_Model_Query_Info_Carrier $model_query_info
2076
	 * @return string
2077
	 */
2078
	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info){
2079
		return " FROM ".$model_query_info->get_full_join_sql().
2080
				$model_query_info->get_where_sql().
2081
				$model_query_info->get_group_by_sql().
2082
				$model_query_info->get_having_sql().
2083
				$model_query_info->get_order_by_sql().
2084
				$model_query_info->get_limit_sql();
2085
	}
2086
2087
	/**
2088
	 * Set to easily debug the next X queries ran from this model.
2089
	 * @param int $count
2090
	 */
2091
	public function show_next_x_db_queries($count = 1){
2092
		$this->_show_next_x_db_queries = $count;
2093
	}
2094
2095
2096
2097
	/**
2098
	 * @param $sql_query
2099
	 */
2100
	public function show_db_query_if_previously_requested($sql_query){
2101
		if($this->_show_next_x_db_queries > 0){
2102
			echo $sql_query;
2103
			$this->_show_next_x_db_queries--;
2104
		}
2105
	}
2106
2107
2108
2109
	/**
2110
	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2111
	 * There are the 3 cases:
2112
	 * '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.
2113
	 * '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.
2114
	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2115
	 * 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
2116
	 *
2117
	 * @param        EE_Base_Class                     /int $thisModelObject
2118
	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2119
	 * @param string $relationName                     , key in EEM_Base::_relations
2120
	 *                                                 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')
2121
	 * @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.
2122
	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2123
	 * @throws \EE_Error
2124
	 */
2125
	public function add_relationship_to($id_or_obj,$other_model_id_or_obj, $relationName, $extra_join_model_fields_n_values = array()){
2126
		$relation_obj = $this->related_settings_for($relationName);
2127
		return $relation_obj->add_relation_to( $id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2128
	}
2129
2130
2131
2132
	/**
2133
	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2134
	 * There are the 3 cases:
2135
	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an error
2136
	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws an error
2137
	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2138
	 *
2139
	 * @param        EE_Base_Class /int $id_or_obj
2140
	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2141
	 * @param string $relationName key in EEM_Base::_relations
2142
	 * @return boolean of success
2143
	 * @throws \EE_Error
2144
	 * @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.
2145
	 */
2146
	public function remove_relationship_to($id_or_obj,  $other_model_id_or_obj, $relationName, $where_query= array() ){
2147
		$relation_obj = $this->related_settings_for($relationName);
2148
		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query );
2149
	}
2150
2151
2152
2153
	/**
2154
	 * @param mixed           $id_or_obj
2155
	 * @param string          $relationName
2156
	 * @param array           $where_query_params
2157
	 * @param EE_Base_Class[] objects to which relations were removed
2158
	 * @return \EE_Base_Class[]
2159
	 * @throws \EE_Error
2160
	 */
2161
	public function remove_relations($id_or_obj,$relationName,$where_query_params = array()){
2162
		$relation_obj = $this->related_settings_for($relationName);
2163
		return $relation_obj->remove_relations($id_or_obj, $where_query_params );
2164
	}
2165
2166
2167
2168
	/**
2169
	 * Gets all the related items of the specified $model_name, using $query_params.
2170
	 * Note: by default, we remove the "default query params"
2171
	 * because we want to get even deleted items etc.
2172
	 *
2173
	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2174
	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2175
	 * @param array  $query_params like EEM_Base::get_all
2176
	 * @return EE_Base_Class[]
2177
	 * @throws \EE_Error
2178
	 */
2179
	public function get_all_related($id_or_obj, $model_name, $query_params = null){
2180
		$model_obj = $this->ensure_is_obj($id_or_obj);
2181
		$relation_settings = $this->related_settings_for($model_name);
2182
		return $relation_settings->get_all_related($model_obj,$query_params);
0 ignored issues
show
Bug introduced by
It seems like $model_obj defined by $this->ensure_is_obj($id_or_obj) on line 2180 can be null; however, EE_Model_Relation_Base::get_all_related() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
Bug introduced by
It seems like $query_params defined by parameter $query_params on line 2179 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...
2183
	}
2184
2185
2186
2187
	/**
2188
	 * Deletes all the model objects across the relation indicated by $model_name
2189
	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2190
	 * However, if the model objects can't be deleted because of blocking related model objects, then
2191
	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2192
	 *
2193
	 * @param EE_Base_Class|int|string $id_or_obj
2194
	 * @param string                   $model_name
2195
	 * @param array                    $query_params
2196
	 * @return int how many deleted
2197
	 * @throws \EE_Error
2198
	 */
2199
	public function delete_related($id_or_obj,$model_name, $query_params = array()){
2200
		$model_obj = $this->ensure_is_obj($id_or_obj);
2201
		$relation_settings = $this->related_settings_for($model_name);
2202
		return $relation_settings->delete_all_related($model_obj,$query_params);
0 ignored issues
show
Bug introduced by
It seems like $model_obj defined by $this->ensure_is_obj($id_or_obj) on line 2200 can be null; however, EE_Model_Relation_Base::delete_all_related() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2203
	}
2204
2205
2206
2207
	/**
2208
	 * Hard deletes all the model objects across the relation indicated by $model_name
2209
	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2210
	 * the model objects can't be hard deleted because of blocking related model objects,
2211
	 * just does a soft-delete on them instead.
2212
	 *
2213
	 * @param EE_Base_Class|int|string $id_or_obj
2214
	 * @param string                   $model_name
2215
	 * @param array                    $query_params
2216
	 * @return int how many deleted
2217
	 * @throws \EE_Error
2218
	 */
2219
	public function delete_related_permanently($id_or_obj,$model_name, $query_params = array()){
2220
		$model_obj = $this->ensure_is_obj($id_or_obj);
2221
		$relation_settings = $this->related_settings_for($model_name);
2222
		return $relation_settings->delete_related_permanently($model_obj,$query_params);
0 ignored issues
show
Bug introduced by
It seems like $model_obj defined by $this->ensure_is_obj($id_or_obj) on line 2220 can be null; however, EE_Model_Relation_Base::...e_related_permanently() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2223
	}
2224
2225
2226
2227
	/**
2228
	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2229
	 * unless otherwise specified in the $query_params
2230
	 *
2231
	 * @param        int             /EE_Base_Class $id_or_obj
2232
	 * @param string $model_name     like 'Event', or 'Registration'
2233
	 * @param array  $query_params   like EEM_Base::get_all's
2234
	 * @param string $field_to_count name of field to count by. By default, uses primary key
2235
	 * @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;
2236
	 * @return int
2237
	 * @throws \EE_Error
2238
	 */
2239
	public function count_related($id_or_obj,$model_name,$query_params = array(),$field_to_count = null, $distinct = FALSE){
2240
		$related_model = $this->get_related_model_obj($model_name);
2241
		//we're just going to use the query params on the related model's normal get_all query,
2242
		//except add a condition to say to match the current mod
2243
		if( ! isset($query_params['default_where_conditions'])){
2244
			$query_params['default_where_conditions']='none';
2245
		}
2246
		$this_model_name = $this->get_this_model_name();
2247
		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2248
		$query_params[0][$this_model_name.".".$this_pk_field_name]=$id_or_obj;
2249
		return $related_model->count($query_params,$field_to_count,$distinct);
2250
	}
2251
2252
2253
2254
	/**
2255
	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2256
	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2257
	 *
2258
	 * @param        int           /EE_Base_Class $id_or_obj
2259
	 * @param string $model_name   like 'Event', or 'Registration'
2260
	 * @param array  $query_params like EEM_Base::get_all's
2261
	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2262
	 * @return float
2263
	 * @throws \EE_Error
2264
	 */
2265
	public function sum_related($id_or_obj,$model_name,$query_params,$field_to_sum = null){
2266
		$related_model = $this->get_related_model_obj($model_name);
2267
		if( ! is_array( $query_params ) ){
2268
			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' );
2269
			$query_params = array();
2270
		}
2271
		//we're just going to use the query params on the related model's normal get_all query,
2272
		//except add a condition to say to match the current mod
2273
		if( ! isset($query_params['default_where_conditions'])){
2274
			$query_params['default_where_conditions']='none';
2275
		}
2276
		$this_model_name = $this->get_this_model_name();
2277
		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2278
		$query_params[0][$this_model_name.".".$this_pk_field_name]=$id_or_obj;
2279
		return $related_model->sum($query_params,$field_to_sum);
2280
	}
2281
2282
2283
2284
	/**
2285
	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given $modelObject
2286
	 *
2287
	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2288
	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2289
	 * @param array               $query_params     like EEM_Base::get_all's
2290
	 * @return EE_Base_Class
2291
	 * @throws \EE_Error
2292
	 */
2293
	public function get_first_related( EE_Base_Class $id_or_obj, $other_model_name, $query_params ){
2294
		$query_params['limit']=1;
2295
		$results = $this->get_all_related($id_or_obj,$other_model_name,$query_params);
2296
		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...
2297
			return array_shift($results);
2298
		}else{
2299
			return null;
2300
		}
2301
2302
	}
2303
2304
	/**
2305
	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2306
	 * @return string
2307
	 */
2308
	public function get_this_model_name(){
2309
		return str_replace("EEM_","",get_class($this));
2310
	}
2311
2312
	/**
2313
	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2314
	 * @return EE_Any_Foreign_Model_Name_Field
2315
	 * @throws EE_Error
2316
	 */
2317
	public function get_field_containing_related_model_name(){
2318
		foreach($this->field_settings(true) as $field){
2319
			if($field instanceof EE_Any_Foreign_Model_Name_Field){
2320
				$field_with_model_name = $field;
2321
			}
2322
		}
2323 View Code Duplication
		if( !isset($field_with_model_name) || !$field_with_model_name ){
2324
			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"), $this->get_this_model_name() ));
2325
		}
2326
		return $field_with_model_name;
2327
	}
2328
2329
2330
2331
	/**
2332
	 * Inserts a new entry into the database, for each table.
2333
	 *
2334
	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2335
	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2336
	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2337
	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2338
	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2339
	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2340
	 * @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,
2341
	 * 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)
2342
	 * @return int new primary key on main table that got inserted
2343
	 * @throws EE_Error
2344
	 */
2345
	public function insert($field_n_values){
2346
		/**
2347
		 * Filters the fields and their values before inserting an item using the models
2348
		 * @param array $fields_n_values keys are the fields and values are their new values
2349
		 * @param EEM_Base $model the model used
2350
		 */
2351
		$field_n_values = (array)apply_filters( 'FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this );
2352
		if($this->_satisfies_unique_indexes($field_n_values)){
2353
			$main_table = $this->_get_main_table();
2354
			$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...
2355
			if( $new_id !== false ) {
2356
				foreach($this->_get_other_tables() as $other_table){
2357
					$this->_insert_into_specific_table($other_table, $field_n_values,$new_id);
2358
				}
2359
			}
2360
			/**
2361
			 * Done just after attempting to insert a new model object
2362
			 *
2363
			 * @param EEM_Base $model used
2364
			 * @param array $fields_n_values fields and their values
2365
			 * @param int|string the ID of the newly-inserted model object
2366
			 */
2367
			do_action( 'AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id );
2368
			return $new_id;
2369
		}else{
2370
			return FALSE;
2371
		}
2372
	}
2373
2374
2375
2376
	/**
2377
	 * Checks that the result would satisfy the unique indexes on this model
2378
	 *
2379
	 * @param array  $field_n_values
2380
	 * @param string $action
2381
	 * @return boolean
2382
	 * @throws \EE_Error
2383
	 */
2384
	protected function _satisfies_unique_indexes($field_n_values,$action = 'insert'){
2385
		foreach($this->unique_indexes() as $index_name => $index){
2386
			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2387
			if($this->exists(array($uniqueness_where_params))){
2388
				EE_Error::add_error(
2389
					sprintf(
2390
						__(
2391
							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2392
							"event_espresso"
2393
						),
2394
						$action,
2395
						$this->_get_class_name(),
2396
						$index_name,
2397
						implode( ",", $index->field_names() ),
2398
						http_build_query( $uniqueness_where_params )
2399
					),
2400
					__FILE__,
2401
					__FUNCTION__,
2402
					__LINE__
2403
				);
2404
				return false;
2405
			}
2406
		}
2407
		return true;
2408
	}
2409
2410
2411
2412
	/**
2413
	 * Checks the database for an item that conflicts (ie, if this item were
2414
	 * saved to the DB would break some uniqueness requirement, like a primary key
2415
	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2416
	 * can be either an EE_Base_Class or an array of fields n values
2417
	 *
2418
	 * @param EE_Base_Class|array $obj_or_fields_array
2419
	 * @param boolean       $include_primary_key       whether to use the model object's primary key
2420
	 *                                                 when looking for conflicts
2421
	 *                                                 (ie, if false, we ignore the model object's primary key
2422
	 *                                                 when finding "conflicts". If true, it's also considered).
2423
	 *                                                 Only works for INT primary key,
2424
	 *                                                 STRING primary keys cannot be ignored
2425
	 * @throws EE_Error
2426
	 * @return EE_Base_Class|array
2427
	 */
2428
	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true ){
2429 View Code Duplication
		if($obj_or_fields_array instanceof EE_Base_Class){
2430
			$fields_n_values = $obj_or_fields_array->model_field_array();
2431
		}elseif( is_array($obj_or_fields_array)){
2432
			$fields_n_values = $obj_or_fields_array;
2433
		}else{
2434
			throw new EE_Error(
2435
				sprintf(
2436
					__(
2437
						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2438
						"event_espresso"
2439
					),
2440
					get_class( $this ),
2441
					$obj_or_fields_array
2442
				)
2443
			);
2444
		}
2445
		$query_params = array();
2446
		if( $this->has_primary_key_field() &&
2447
				( $include_primary_key || $this->get_primary_key_field() instanceof EE_Primary_Key_String_Field) &&
2448
				isset($fields_n_values[$this->primary_key_name()])){
2449
			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2450
		}
2451
		foreach($this->unique_indexes() as $unique_index_name=>$unique_index){
2452
			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2453
			$query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2454
		}
2455
		//if there is nothing to base this search on, then we shouldn't find anything
2456
		if( empty( $query_params ) ){
2457
			return array();
2458
		}else{
2459
			return $this->get_one($query_params);
2460
		}
2461
	}
2462
2463
2464
2465
	/**
2466
	 * Like count, but is optimized and returns a boolean instead of an int
2467
	 *
2468
	 * @param array $query_params
2469
	 * @return boolean
2470
	 * @throws \EE_Error
2471
	 */
2472
	public function exists($query_params){
2473
		$query_params['limit'] = 1;
2474
		return $this->count($query_params) > 0;
2475
	}
2476
2477
2478
2479
	/**
2480
	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2481
	 *
2482
	 * @param int|string $id
2483
	 * @return boolean
2484
	 * @throws \EE_Error
2485
	 */
2486
	public function exists_by_ID($id){
2487
		return $this->exists(array('default_where_conditions'=>'none', array($this->primary_key_name() => $id)));
2488
	}
2489
2490
2491
2492
	/**
2493
	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2494
	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2495
	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2496
	 * on the main table)
2497
	 * 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().
2498
	 * @access   protected
2499
	 * @param EE_Table_Base $table
2500
	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or float
2501
	 * @param int  $new_id 	for now we assume only int keys
2502
	 * @throws EE_Error
2503
	 * @global WPDB $wpdb only used to get the $wpdb->insert_id after performing an insert
2504
	 * @return int ID of new row inserted, or FALSE on failure
2505
	 */
2506
	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0 ){
2507
		global $wpdb;
2508
		$insertion_col_n_values = array();
2509
		$format_for_insertion = array();
2510
		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2511
		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...
2512
			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2513
			if($field_obj->is_auto_increment()){
2514
				continue;
2515
			}
2516
			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2517
			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2518
			if( $prepared_value !== NULL ){
2519
				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2520
				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2521
			}
2522
		}
2523
2524
		if($table instanceof EE_Secondary_Table && $new_id){
2525
			//its not the main table, so we should have already saved the main table's PK which we just inserted
2526
			//so add the fk to the main table as a column
2527
			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2528
			$format_for_insertion[]='%d';//yes right now we're only allowing these foreign keys to be INTs
2529
		}
2530
		//insert the new entry
2531
		$result = $this->_do_wpdb_query( 'insert', array( $table->get_table_name(), $insertion_col_n_values, $format_for_insertion ) );
2532
		if( $result === false ) {
2533
			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...
2534
		}
2535
		//ok, now what do we return for the ID of the newly-inserted thing?
2536
		if($this->has_primary_key_field()){
2537
			if($this->get_primary_key_field()->is_auto_increment()){
2538
				return $wpdb->insert_id;
2539
			}else{
2540
				//it's not an auto-increment primary key, so
2541
				//it must have been supplied
2542
				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2543
			}
2544
		}else{
2545
			//we can't return a  primary key because there is none. instead return
2546
			//a unique string indicating this model
2547
			return $this->get_index_primary_key_string($fields_n_values);
2548
		}
2549
	}
2550
2551
2552
2553
	/**
2554
	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2555
	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2556
	 * and there is no default, we pass it along. WPDB will take care of it)
2557
	 *
2558
	 * @param EE_Model_Field_Base $field_obj
2559
	 * @param array               $fields_n_values
2560
	 * @return mixed string|int|float depending on what the table column will be expecting
2561
	 * @throws \EE_Error
2562
	 */
2563
	protected function _prepare_value_or_use_default( $field_obj, $fields_n_values ){
2564
		//if this field doesn't allow nullable, don't allow it
2565
		if( ! $field_obj->is_nullable() && (
2566
				! isset( $fields_n_values[ $field_obj->get_name() ] ) ||
2567
				$fields_n_values[ $field_obj->get_name() ] === NULL ) ){
2568
			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
2569
		}
2570
		$unprepared_value = isset( $fields_n_values[ $field_obj->get_name() ] ) ? $fields_n_values[ $field_obj->get_name() ] : NULL;
2571
		return $this->_prepare_value_for_use_in_db( $unprepared_value, $field_obj);
2572
	}
2573
2574
2575
	/**
2576
	 * 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,
2577
	 * and depending on $value_already_prepare_by_model_obj, may also call the field's prepare_for_set() method.
2578
	 * @param mixed $value value in the client code domain if $value_already_prepared_by_model_object is false, otherwise a value
2579
	 * in the model object's domain (see lengthy comment at top of file)
2580
	 * @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
2581
	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2582
	 */
2583
	private function _prepare_value_for_use_in_db($value, $field){
2584
		if($field && $field instanceof EE_Model_Field_Base){
2585
			switch( $this->_values_already_prepared_by_model_object ){
2586
				/** @noinspection PhpMissingBreakStatementInspection */
2587
				case self::not_prepared_by_model_object:
2588
					$value = $field->prepare_for_set($value);
2589
					//purposefully left out "return"
2590
				case self::prepared_by_model_object:
2591
					$value = $field->prepare_for_use_in_db($value);
2592
				case self::prepared_for_use_in_db:
2593
					//leave the value alone
2594
			}
2595
			return $value;
2596
		}else{
2597
			return $value;
2598
		}
2599
	}
2600
2601
	/**
2602
	 * Returns the main table on this model
2603
	 * @return EE_Primary_Table
2604
	 * @throws EE_Error
2605
	 */
2606
	protected function _get_main_table(){
2607
		foreach($this->_tables as $table){
2608
			if($table instanceof EE_Primary_Table){
2609
				return $table;
2610
			}
2611
		}
2612
		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)));
2613
	}
2614
2615
2616
2617
	/**
2618
	 * table
2619
	 * returns EE_Primary_Table table name
2620
	 *
2621
	 * @return string
2622
	 * @throws \EE_Error
2623
	 */
2624
	public function table() {
2625
		return $this->_get_main_table()->get_table_name();
2626
	}
2627
2628
	/**
2629
	 * table
2630
	 * returns first EE_Secondary_Table table name
2631
	 * @return string
2632
	 */
2633
	public function second_table() {
2634
		// grab second table from tables array
2635
		$second_table = end( $this->_tables );
2636
		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : NULL;
2637
	}
2638
2639
2640
2641
	/**
2642
	 * get_table_obj_by_alias
2643
	 * returns table name given it's alias
2644
	 *
2645
	 * @param string $table_alias
2646
	 * @return EE_Primary_Table | EE_Secondary_Table
2647
	 */
2648
	public function get_table_obj_by_alias( $table_alias = '' ) {
2649
		return isset( $this->_tables[ $table_alias ] ) ? $this->_tables[ $table_alias ] : NULL;
2650
	}
2651
2652
2653
2654
	/**
2655
	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
2656
	 * @return EE_Secondary_Table[]
2657
	 */
2658
	protected function _get_other_tables(){
2659
		$other_tables =array();
2660
		foreach($this->_tables as $table_alias => $table){
2661
			if($table instanceof EE_Secondary_Table){
2662
				$other_tables[$table_alias] = $table;
2663
			}
2664
		}
2665
		return $other_tables;
2666
	}
2667
2668
	/**
2669
	 * Finds all the fields that correspond to the given table
2670
	 * @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...
2671
	 * @return EE_Model_Field_Base[]
2672
	 */
2673
	public function _get_fields_for_table($table_alias){
2674
		return $this->_fields[$table_alias];
2675
	}
2676
2677
2678
2679
	/**
2680
	 * Recurses through all the where parameters, and finds all the related models we'll need
2681
	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't need any
2682
	 * related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related Registration model.
2683
	 * If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the related Registration, Transaction, and Payment models.
2684
	 *
2685
	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
2686
	 * @return EE_Model_Query_Info_Carrier
2687
	 * @throws \EE_Error
2688
	 */
2689
	public function _extract_related_models_from_query($query_params){
2690
		$query_info_carrier = new EE_Model_Query_Info_Carrier();
2691
		if ( array_key_exists( 0, $query_params ) ) {
2692
			$this->_extract_related_models_from_sub_params_array_keys( $query_params[0], $query_info_carrier, 0 );
2693
		}
2694 View Code Duplication
		if ( array_key_exists( 'group_by', $query_params ) ) {
2695
			if ( is_array( $query_params['group_by'] ) ) {
2696
				$this->_extract_related_models_from_sub_params_array_values(
2697
					$query_params['group_by'],
2698
					$query_info_carrier,
2699
					'group_by'
2700
				);
2701
			} elseif ( ! empty ( $query_params['group_by'] ) ) {
2702
				$this->_extract_related_model_info_from_query_param(
2703
					$query_params['group_by'],
2704
					$query_info_carrier,
2705
					'group_by'
2706
				);
2707
			}
2708
		}
2709
		if ( array_key_exists( 'having', $query_params ) ) {
2710
			$this->_extract_related_models_from_sub_params_array_keys(
2711
				$query_params[0],
2712
				$query_info_carrier,
2713
				'having'
2714
			);
2715
		}
2716 View Code Duplication
		if ( array_key_exists( 'order_by', $query_params ) ) {
2717
			if ( is_array( $query_params['order_by'] ) ) {
2718
				$this->_extract_related_models_from_sub_params_array_keys(
2719
					$query_params['order_by'],
2720
					$query_info_carrier,
2721
					'order_by'
2722
				);
2723
			} elseif ( ! empty( $query_params['order_by'] ) ) {
2724
				$this->_extract_related_model_info_from_query_param(
2725
					$query_params['order_by'],
2726
					$query_info_carrier,
2727
					'order_by'
2728
				);
2729
			}
2730
		}
2731
		if ( array_key_exists( 'force_join', $query_params ) ) {
2732
			$this->_extract_related_models_from_sub_params_array_values(
2733
				$query_params['force_join'],
2734
				$query_info_carrier,
2735
				'force_join'
2736
			);
2737
		}
2738
		return $query_info_carrier;
2739
	}
2740
2741
	/**
2742
	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
2743
	 * @param array $sub_query_params like EEM_Base::get_all's $query_params[0] or $query_params['having']
2744
	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
2745
	 * @param string                      $query_param_type one of $this->_allowed_query_params
2746
	 * @throws EE_Error
2747
	 * @return \EE_Model_Query_Info_Carrier
2748
	 */
2749
	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){
2750
		if (!empty($sub_query_params)){
2751
			$sub_query_params = (array) $sub_query_params;
2752
			foreach($sub_query_params as $param => $possibly_array_of_params){
2753
				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
2754
				$this->_extract_related_model_info_from_query_param( $param, $model_query_info_carrier,$query_param_type);
2755
2756
				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
2757
				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
2758
				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
2759
				//of array('Registration.TXN_ID'=>23)
2760
				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
2761
				if(in_array($query_param_sans_stars, $this->_logic_query_param_keys,true)){
2762
					if (! is_array($possibly_array_of_params)){
2763
						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"),
2764
							$param,$possibly_array_of_params));
2765
					}else{
2766
						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params, $model_query_info_carrier,$query_param_type);
2767
					}
2768
				}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...
2769
						&& is_array($possibly_array_of_params)
2770
						&& isset($possibly_array_of_params[2])
2771
						&& $possibly_array_of_params[2] == true){
2772
					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
2773
					//indicating that $possible_array_of_params[1] is actually a field name,
2774
					//from which we should extract query parameters!
2775 View Code Duplication
					if( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1] ) ) {
2776
						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)));
2777
					}
2778
					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1], $model_query_info_carrier, $query_param_type);
2779
				}
2780
			}
2781
		}
2782
		return $model_query_info_carrier;
2783
	}
2784
2785
2786
	/**
2787
	 * For extracting related models from forced_joins, where the array values contain the info about what
2788
	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
2789
	 * @param array $sub_query_params like EEM_Base::get_all's $query_params[0] or $query_params['having']
2790
	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
2791
	 * @param string                      $query_param_type one of $this->_allowed_query_params
2792
	 * @throws EE_Error
2793
	 * @return \EE_Model_Query_Info_Carrier
2794
	 */
2795
	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){
2796
		if (!empty($sub_query_params)){
2797
			if(!is_array($sub_query_params)){
2798
				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),$sub_query_params));
2799
			}
2800
			foreach($sub_query_params as $param){
2801
				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
2802
				$this->_extract_related_model_info_from_query_param( $param, $model_query_info_carrier, $query_param_type);
2803
			}
2804
		}
2805
		return $model_query_info_carrier;
2806
	}
2807
2808
2809
2810
	/**
2811
	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
2812
	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
2813
	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
2814
	 * but use them in a different order. Eg, we need to know what models we are querying
2815
	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on other
2816
	 * models before we can finalize the where clause SQL.
2817
	 * @param array $query_params
2818
	 * @throws EE_Error
2819
	 * @return EE_Model_Query_Info_Carrier
2820
	 */
2821
	public function _create_model_query_info_carrier($query_params){
2822
		if ( ! is_array( $query_params ) ) {
2823
			EE_Error::doing_it_wrong(
2824
				'EEM_Base::_create_model_query_info_carrier',
2825
				sprintf(
2826
					__(
2827
						'$query_params should be an array, you passed a variable of type %s',
2828
						'event_espresso'
2829
					),
2830
					gettype( $query_params )
2831
				),
2832
				'4.6.0'
2833
			);
2834
			$query_params = array();
2835
		}
2836
		$where_query_params = isset( $query_params[0] ) ? $query_params[0] : array();
2837
		//first check if we should alter the query to account for caps or not
2838
		//because the caps might require us to do extra joins
2839
		if ( isset( $query_params['caps'] ) && $query_params['caps'] !== 'none' ) {
2840
			$query_params[0] = $where_query_params = array_replace_recursive(
2841
				$where_query_params,
2842
				$this->caps_where_conditions(
2843
					$query_params['caps']
2844
				)
2845
			);
2846
		}
2847
		$query_object = $this->_extract_related_models_from_query( $query_params );
2848
		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
2849
		foreach ( $where_query_params as $key => $value ) {
2850
			if ( is_int( $key ) ) {
2851
				throw new EE_Error(
2852
					sprintf(
2853
						__(
2854
							"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.",
2855
							"event_espresso"
2856
						),
2857
						$key,
2858
						var_export( $value, true ),
2859
						var_export( $query_params, true ),
2860
						get_class( $this )
2861
					)
2862
				);
2863
			}
2864
		}
2865
		if (
2866
			array_key_exists( 'default_where_conditions', $query_params )
2867
			&& ! empty( $query_params['default_where_conditions'] )
2868
		) {
2869
			$use_default_where_conditions = $query_params['default_where_conditions'];
2870
		} else {
2871
			$use_default_where_conditions = 'all';
2872
		}
2873
		$where_query_params = array_merge(
2874
			$this->_get_default_where_conditions_for_models_in_query(
2875
				$query_object,
2876
				$use_default_where_conditions,
2877
				$where_query_params
2878
			),
2879
			$where_query_params
2880
		);
2881
		$query_object->set_where_sql( $this->_construct_where_clause( $where_query_params ) );
2882
		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
2883
		// So we need to setup a subquery and use that for the main join.
2884
		// Note for now this only works on the primary table for the model.
2885
		// So for instance, you could set the limit array like this:
2886
		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
2887
		if ( array_key_exists( 'on_join_limit', $query_params ) && ! empty( $query_params['on_join_limit'] ) ) {
2888
			$query_object->set_main_model_join_sql(
2889
				$this->_construct_limit_join_select(
2890
					$query_params['on_join_limit'][0],
2891
					$query_params['on_join_limit'][1]
2892
				)
2893
			);
2894
		}
2895
		//set limit
2896
		if ( array_key_exists( 'limit', $query_params ) ) {
2897
			if ( is_array( $query_params['limit'] ) ) {
2898
				if ( ! isset( $query_params['limit'][0], $query_params['limit'][1] ) ) {
2899
					$e = sprintf(
2900
						__(
2901
							"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)",
2902
							"event_espresso"
2903
						),
2904
						http_build_query( $query_params['limit'] )
2905
					);
2906
					throw new EE_Error( $e . "|" . $e );
2907
				}
2908
				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
2909
				$query_object->set_limit_sql( " LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1] );
2910
			} elseif ( ! empty ( $query_params['limit'] ) ) {
2911
				$query_object->set_limit_sql( " LIMIT " . $query_params['limit'] );
2912
			}
2913
		}
2914
		//set order by
2915
		if ( array_key_exists( 'order_by', $query_params ) ) {
2916
			if ( is_array( $query_params['order_by'] ) ) {
2917
				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
2918
				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
2919
				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
2920
				if ( array_key_exists( 'order', $query_params ) ) {
2921
					throw new EE_Error(
2922
						sprintf(
2923
							__(
2924
								"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 ",
2925
								"event_espresso"
2926
							),
2927
							get_class( $this ),
2928
							implode( ", ", array_keys( $query_params['order_by'] ) ),
2929
							implode( ", ", $query_params['order_by'] ),
2930
							$query_params['order']
2931
						)
2932
					);
2933
				}
2934
				$this->_extract_related_models_from_sub_params_array_keys(
2935
					$query_params['order_by'],
2936
					$query_object,
2937
					'order_by'
2938
				);
2939
				//assume it's an array of fields to order by
2940
				$order_array = array();
2941
				foreach ( $query_params['order_by'] as $field_name_to_order_by => $order ) {
2942
					$order = $this->_extract_order( $order );
2943
					$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...
2944
				}
2945
				$query_object->set_order_by_sql( " ORDER BY " . implode( ",", $order_array ) );
2946
			} elseif ( ! empty ( $query_params['order_by'] ) ) {
2947
				$this->_extract_related_model_info_from_query_param(
2948
					$query_params['order_by'],
2949
					$query_object,
2950
					'order',
2951
					$query_params['order_by']
2952
				);
2953
				$order = isset( $query_params['order'] )
2954
					? $this->_extract_order( $query_params['order'] )
2955
					: 'DESC';
2956
				$query_object->set_order_by_sql(
2957
					" ORDER BY " . $this->_deduce_column_name_from_query_param( $query_params['order_by'] ) . SP . $order
2958
				);
2959
			}
2960
		}
2961
		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
2962
		if ( ! array_key_exists( 'order_by', $query_params )
2963
		     && array_key_exists( 'order', $query_params )
2964
		     && ! empty( $query_params['order'] )
2965
		) {
2966
			$pk_field = $this->get_primary_key_field();
2967
			$order = $this->_extract_order( $query_params['order'] );
2968
			$query_object->set_order_by_sql( " ORDER BY " . $pk_field->get_qualified_column() . SP . $order );
2969
		}
2970
		//set group by
2971
		if ( array_key_exists( 'group_by', $query_params ) ) {
2972
			if ( is_array( $query_params['group_by'] ) ) {
2973
				//it's an array, so assume we'll be grouping by a bunch of stuff
2974
				$group_by_array = array();
2975
				foreach ( $query_params['group_by'] as $field_name_to_group_by ) {
2976
					$group_by_array[] = $this->_deduce_column_name_from_query_param( $field_name_to_group_by );
2977
				}
2978
				$query_object->set_group_by_sql( " GROUP BY " . implode( ", ", $group_by_array ) );
2979
			} elseif ( ! empty ( $query_params['group_by'] ) ) {
2980
				$query_object->set_group_by_sql(
2981
					" GROUP BY " . $this->_deduce_column_name_from_query_param( $query_params['group_by'] )
2982
				);
2983
			}
2984
		}
2985
		//set having
2986
		if ( array_key_exists( 'having', $query_params ) && $query_params['having'] ) {
2987
			$query_object->set_having_sql( $this->_construct_having_clause( $query_params['having'] ) );
2988
		}
2989
		//now, just verify they didn't pass anything wack
2990
		foreach ( $query_params as $query_key => $query_value ) {
2991 View Code Duplication
			if ( ! in_array( $query_key, $this->_allowed_query_params, true ) ) {
2992
				throw new EE_Error(
2993
					sprintf(
2994
						__(
2995
							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
2996
							'event_espresso'
2997
						),
2998
						$query_key,
2999
						get_class( $this ),
3000
//						print_r( $this->_allowed_query_params, TRUE )
3001
						implode( ',', $this->_allowed_query_params )
3002
					)
3003
				);
3004
			}
3005
		}
3006
		$main_model_join_sql = $query_object->get_main_model_join_sql();
3007
		if ( empty( $main_model_join_sql ) ) {
3008
			$query_object->set_main_model_join_sql( $this->_construct_internal_join() );
3009
		}
3010
		return $query_object;
3011
	}
3012
3013
3014
3015
	/**
3016
	 * Gets the where conditions that should be imposed on the query based on the
3017
	 * context (eg reading frontend, backend, edit or delete).
3018
	 *
3019
	 * @param string $context one of EEM_Base::valid_cap_contexts()
3020
	 * @return array like EEM_Base::get_all() 's $query_params[0]
3021
	 * @throws \EE_Error
3022
	 */
3023
	public function caps_where_conditions( $context = self::caps_read ) {
3024
		EEM_Base::verify_is_valid_cap_context( $context );
3025
		$cap_where_conditions = array();
3026
		$cap_restrictions = $this->caps_missing( $context );
3027
		/**
3028
		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3029
		 */
3030
		foreach( $cap_restrictions as $cap => $restriction_if_no_cap ) {
3031
				$cap_where_conditions = array_replace_recursive( $cap_where_conditions, $restriction_if_no_cap->get_default_where_conditions() );
3032
		}
3033
		return apply_filters( 'FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context, $cap_restrictions );
3034
	}
3035
3036
	/**
3037
	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3038
	 * otherwise throws an exception
3039
	 * @param string $should_be_order_string
3040
	 * @return string either ASC, asc, DESC or desc
3041
	 * @throws EE_Error
3042
	 */
3043 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...
3044
		if(in_array($should_be_order_string, $this->_allowed_order_values)){
3045
			return $should_be_order_string;
3046
		}else{
3047
			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));
3048
		}
3049
	}
3050
3051
3052
3053
	/**
3054
	 * Looks at all the models which are included in this query, and asks each
3055
	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3056
	 * so they can be merged
3057
	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3058
	 * @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.
3059
	 * 'other_models_only' means default where conditions from other models will be used, but not for this primary model. 'all', the default, means
3060
	 * default where conditions will apply as normal
3061
	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3062
	 * @throws EE_Error
3063
	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3064
	 */
3065
	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()){
3066
		$allowed_used_default_where_conditions_values = array(
3067
				'all',
3068
				'this_model_only',
3069
				'other_models_only',
3070
				'minimum',
3071
				'none'
3072
			);
3073 View Code Duplication
		if( ! in_array($use_default_where_conditions,$allowed_used_default_where_conditions_values)){
3074
			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)));
3075
		}
3076
		$universal_query_params = array();
3077
		if( $use_default_where_conditions === 'all' || $use_default_where_conditions === 'this_model_only' ){
3078
			$universal_query_params = $this->_get_default_where_conditions();
3079
		} else if( $use_default_where_conditions === 'minimum' ) {
3080
			$universal_query_params = $this->_get_minimum_where_conditions();
3081
		}
3082
		if(in_array($use_default_where_conditions,array('all','other_models_only'))){
3083
			foreach($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name){
3084
				$related_model = $this->get_related_model_obj($model_name);
3085
				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3086
				$overrides = $this->_override_defaults_or_make_null_friendly(
3087
					$related_model_universal_where_params,
3088
					$where_query_params,
3089
					$related_model,
3090
					$model_relation_path
3091
				);
3092
				$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3093
					$universal_query_params,
3094
					$overrides
3095
				);
3096
			}
3097
		}
3098
		return $universal_query_params;
3099
	}
3100
3101
3102
3103
	/**
3104
	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3105
	 * then we also add a special where condition which allows for that model's primary key
3106
	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3107
	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3108
	 *
3109
	 * @param array    $default_where_conditions
3110
	 * @param array    $provided_where_conditions
3111
	 * @param EEM_Base $model
3112
	 * @param string   $model_relation_path like 'Transaction.Payment.'
3113
	 * @return array like EEM_Base::get_all's $query_params[0]
3114
	 * @throws \EE_Error
3115
	 */
3116
	private function _override_defaults_or_make_null_friendly($default_where_conditions,$provided_where_conditions,$model,$model_relation_path){
3117
		$null_friendly_where_conditions = array();
3118
		$none_overridden = true;
3119
		$or_condition_key_for_defaults = 'OR*'.get_class($model);
3120
3121
		foreach($default_where_conditions as $key => $val){
3122
			if( isset($provided_where_conditions[$key])){
3123
				$none_overridden = false;
3124
			}else{
3125
				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3126
			}
3127
		}
3128
		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...
3129
			if($model->has_primary_key_field()){
3130
				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path.".".$model->primary_key_name()] = array('IS NULL');
3131
			}/*else{
3132
				//@todo NO PK, use other defaults
3133
			}*/
3134
		}
3135
		return $null_friendly_where_conditions;
3136
	}
3137
3138
	/**
3139
	 * Uses the _default_where_conditions_strategy set during __construct() to get
3140
	 * default where conditions on all get_all, update, and delete queries done by this model.
3141
	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3142
	 * NOT array('Event_CPT.post_type'=>'esp_event').
3143
	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3144
	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3145
	 */
3146
	private function _get_default_where_conditions($model_relation_path = null){
3147
		if ( $this->_ignore_where_strategy ){
3148
			return array();
3149
		}
3150
		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3151
	}
3152
	/**
3153
	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3154
	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3155
	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3156
	 * NOT array('Event_CPT.post_type'=>'esp_event').
3157
	 * Similar to _get_default_where_conditions
3158
	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3159
	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3160
	 */
3161
	protected function _get_minimum_where_conditions($model_relation_path = null){
3162
		if ( $this->_ignore_where_strategy ){
3163
			return array();
3164
		}
3165
		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3166
	}
3167
3168
3169
3170
	/**
3171
	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3172
	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3173
	 *
3174
	 * @param EE_Model_Query_Info_Carrier $model_query_info
3175
	 * @return string
3176
	 * @throws \EE_Error
3177
	 */
3178
	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info){
3179
		$selects = $this->_get_columns_to_select_for_this_model();
3180
		foreach($model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included){
3181
			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3182
			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model( $model_relation_chain );
3183
			foreach ( $other_model_selects as $key => $value ) {
3184
				$selects[] = $value;
3185
			}
3186
		}
3187
		return implode(", ",$selects);
3188
	}
3189
3190
	/**
3191
	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3192
	 * So that's going to be the columns for all the fields on the model
3193
	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3194
	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3195
	 */
3196
	public function _get_columns_to_select_for_this_model($model_relation_chain = ''){
3197
		$fields = $this->field_settings();
3198
		$selects = array();
3199
		$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());
3200
		foreach($fields as $field_obj){
3201
			$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()."'";
3202
		}
3203
		//make sure we are also getting the PKs of each table
3204
		$tables = $this->get_tables();
3205
		if(count($tables) > 1){
3206
			foreach($tables as $table_obj){
3207
				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix . $table_obj->get_fully_qualified_pk_column();
3208
				if( ! in_array($qualified_pk_column,$selects)){
3209
					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3210
				}
3211
			}
3212
		}
3213
		return $selects;
3214
	}
3215
3216
3217
3218
	/**
3219
	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3220
	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3221
	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the SQL
3222
	 * for joining, and the data types
3223
	 * @param null|string 	$original_query_param
3224
	 * @param string $query_param like Registration.Transaction.TXN_ID
3225
	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3226
	 * @param 	string $query_param_type like Registration.Transaction.TXN_ID
3227
	 * 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
3228
	 * @param string $original_query_param what it originally was (eg Registration.Transaction.TXN_ID). If null, we assume it matches $query_param
3229
	 * @throws EE_Error
3230
	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3231
	 */
3232
	private function _extract_related_model_info_from_query_param(
3233
		$query_param,
3234
		EE_Model_Query_Info_Carrier $passed_in_query_info,
3235
		$query_param_type,
3236
		$original_query_param = null
3237
	) {
3238
		if( $original_query_param === null ){
3239
			$original_query_param = $query_param;
3240
		}
3241
		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3242
		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3243
		$allow_logic_query_params = in_array($query_param_type,array('where','having'));
3244
		$allow_fields = in_array($query_param_type,array('where','having','order_by','group_by','order'));
3245
		//check to see if we have a field on this model
3246
		$this_model_fields = $this->field_settings(true);
3247
		if(array_key_exists($query_param,$this_model_fields)){
3248
			if($allow_fields){
3249
				return;
3250
			}else{
3251
				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"),
3252
						$query_param,get_class($this),$query_param_type,$original_query_param));
3253
			}
3254
		}
3255
		//check if this is a special logic query param
3256
		elseif(in_array($query_param, $this->_logic_query_param_keys, TRUE)){
3257
			if($allow_logic_query_params){
3258
				return;
3259
			}else{
3260
				throw new EE_Error(
3261
					sprintf(
3262
						__( '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' ),
3263
						implode( '", "', $this->_logic_query_param_keys ),
3264
						$query_param ,
3265
						get_class( $this ),
3266
						'<br />',
3267
						"\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
3268
					)
3269
				);
3270
			}
3271
		}
3272
3273
		//check if it's a custom selection
3274
		elseif(array_key_exists($query_param,$this->_custom_selections)){
3275
			return;
3276
		}
3277
3278
		//check if has a model name at the beginning
3279
		//and
3280
		//check if it's a field on a related model
3281
		foreach($this->_model_relations as $valid_related_model_name=>$relation_obj){
3282
			if(strpos($query_param, $valid_related_model_name.".") === 0){
3283
				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info,$original_query_param);
3284
				$query_param = substr($query_param, strlen($valid_related_model_name."."));
3285
				if($query_param === ''){
3286
					//nothing left to $query_param
3287
					//we should actually end in a field name, not a model like this!
3288
					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ", "event_espresso"),
3289
					$query_param,$query_param_type,get_class($this),$valid_related_model_name));
3290
				}else{
3291
					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3292
					$related_model_obj->_extract_related_model_info_from_query_param($query_param, $passed_in_query_info, $query_param_type, $original_query_param);
3293
					return;
3294
				}
3295
			}elseif($query_param === $valid_related_model_name){
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of $query_param (string) and $valid_related_model_name (integer) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
3296
				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info,$original_query_param);
3297
				return;
3298
			}
3299
		}
3300
3301
3302
		//ok so $query_param didn't start with a model name
3303
		//and we previously confirmed it wasn't a logic query param or field on the current model
3304
		//it's wack, that's what it is
3305
		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"),
3306
				$query_param,get_class($this),$query_param_type,$original_query_param));
3307
3308
	}
3309
3310
3311
3312
	/**
3313
	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3314
	 * and store it on $passed_in_query_info
3315
	 *
3316
	 * @param string                      $model_name
3317
	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3318
	 * @param string                      $original_query_param used to extract the relation chain between the queried model and $model_name.
3319
	 *                                                          Eg, if we are querying Event, and are adding a join to 'Payment' with the original query param key 'Registration.Transaction.Payment.PAY_amount',
3320
	 *                                                          we want to extract 'Registration.Transaction.Payment', in case Payment wants to add default query params so that it will know
3321
	 *                                                          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)
3322
	 * @return void
3323
	 * @throws \EE_Error
3324
	 */
3325
	private function _add_join_to_model($model_name, EE_Model_Query_Info_Carrier $passed_in_query_info,$original_query_param){
3326
		$relation_obj = $this->related_settings_for($model_name);
3327
3328
		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3329
		//check if the relation is HABTM, because then we're essentially doing two joins
3330
		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3331
		if($relation_obj instanceof EE_HABTM_Relation){
3332
			$join_model_obj = $relation_obj->get_join_model();
3333
			//replace the model specified with the join model for this relation chain, whi
3334
			$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);
3335
			$new_query_info = new EE_Model_Query_Info_Carrier(
3336
					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3337
					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3338
			$passed_in_query_info->merge( $new_query_info  );
3339
		}
3340
		//now just join to the other table pointed to by the relation object, and add its data types
3341
		$new_query_info = new EE_Model_Query_Info_Carrier(
3342
				array($model_relation_chain=>$model_name),
3343
				$relation_obj->get_join_statement($model_relation_chain));
3344
		$passed_in_query_info->merge( $new_query_info  );
3345
	}
3346
3347
3348
3349
	/**
3350
	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3351
	 *
3352
	 * @param array $where_params like EEM_Base::get_all
3353
	 * @return string of SQL
3354
	 * @throws \EE_Error
3355
	 */
3356
	private function _construct_where_clause($where_params){
3357
		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3358
		if($SQL){
3359
			return " WHERE ". $SQL;
3360
		}else{
3361
			return '';
3362
		}
3363
	}
3364
3365
3366
3367
	/**
3368
	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3369
	 * and should be passed HAVING parameters, not WHERE parameters
3370
	 *
3371
	 * @param array $having_params
3372
	 * @return string
3373
	 * @throws \EE_Error
3374
	 */
3375
	private function _construct_having_clause($having_params){
3376
		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3377
		if($SQL){
3378
			return " HAVING ". $SQL;
3379
		}else{
3380
			return '';
3381
		}
3382
3383
	}
3384
3385
	/**
3386
	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3387
	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on EEM_Attendee.
3388
	 * @param string $field_name
3389
	 * @param string $model_name
3390
	 * @return EE_Model_Field_Base
3391
	 * @throws EE_Error
3392
	 */
3393
	protected function _get_field_on_model($field_name,$model_name){
3394
		$model_class = 'EEM_'.$model_name;
3395
		$model_filepath = $model_class.".model.php";
3396
		if ( is_readable($model_filepath)){
3397
			require_once($model_filepath);
3398
			$model_instance=call_user_func($model_name."::instance");
3399
			/* @var $model_instance EEM_Base */
3400
			return $model_instance->field_settings_for($field_name);
3401
		}else{
3402
			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s','event_espresso'),$model_name,$model_class,$model_filepath));
3403
		}
3404
	}
3405
3406
3407
3408
	/**
3409
	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND Event_Meta.meta_value = 'foo'))"
3410
	 * @param array  $where_params see EEM_Base::get_all for documentation
3411
	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3412
	 * @throws EE_Error
3413
	 * @return string of SQL
3414
	 */
3415
	private function _construct_condition_clause_recursive($where_params, $glue = ' AND'){
3416
		$where_clauses=array();
3417
		foreach($where_params as $query_param => $op_and_value_or_sub_condition){
3418
			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3419
			if(in_array($query_param,$this->_logic_query_param_keys)){
3420
				switch($query_param){
3421
					case 'not':
3422
					case 'NOT':
3423
						$where_clauses[] = "! (". $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition, $glue).")";
3424
						break;
3425
					case 'and':
3426
					case 'AND':
3427
						$where_clauses[] = " (". $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition, ' AND ') .")";
3428
						break;
3429
					case 'or':
3430
					case 'OR':
3431
						$where_clauses[] = " (". $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition, ' OR ') .")";
3432
						break;
3433
				}
3434
			}else{
3435
				$field_obj = $this->_deduce_field_from_query_param($query_param);
3436
3437
				//if it's not a normal field, maybe it's a custom selection?
3438
				if( ! $field_obj){
3439
					if(isset( $this->_custom_selections[$query_param][1])){
3440
						$field_obj = $this->_custom_selections[$query_param][1];
3441
					}else{
3442
						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection", "event_espresso"),$query_param));
3443
					}
3444
				}
3445
				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3446
				$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...
3447
			}
3448
		}
3449
		return $where_clauses ? implode( $glue, $where_clauses ) : '';
3450
	}
3451
3452
3453
3454
	/**
3455
	 * Takes the input parameter and extract the table name (alias) and column name
3456
	 * @param array $query_param  like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3457
	 * @throws EE_Error
3458
	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3459
	 */
3460
	private function _deduce_column_name_from_query_param($query_param){
3461
		$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...
3462
3463
		if( $field ){
3464
			$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...
3465
			return $table_alias_prefix . $field->get_qualified_column();
3466
		}elseif(array_key_exists($query_param,$this->_custom_selections)){
3467
			//maybe it's custom selection item?
3468
			//if so, just use it as the "column name"
3469
			return $query_param;
3470
		}else{
3471
			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)));
3472
		}
3473
	}
3474
3475
	/**
3476
	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition query
3477
	 * param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get overwritten
3478
	 * Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
3479
	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
3480
	 * @param string $condition_query_param_key
3481
	 * @return string
3482
	 */
3483 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...
3484
		$pos_of_star = strpos($condition_query_param_key, '*');
3485
		if($pos_of_star === FALSE){
3486
			return $condition_query_param_key;
3487
		}else{
3488
			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
3489
			return $condition_query_param_sans_star;
3490
		}
3491
	}
3492
3493
3494
3495
	/**
3496
	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
3497
	 * @param mixed array | string 	$op_and_value
3498
	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
3499
	 * @throws EE_Error
3500
	 * @return string
3501
	 */
3502
	private function _construct_op_and_value($op_and_value, $field_obj){
3503
		if ( is_array( $op_and_value ) ) {
3504
			$operator = isset( $op_and_value[0] ) ? $this->_prepare_operator_for_sql( $op_and_value[0] ) : null;
3505
			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...
3506
				$php_array_like_string = array();
3507
				foreach ( $op_and_value as $key => $value ) {
3508
					$php_array_like_string[] = "$key=>$value";
3509
				}
3510
				throw new EE_Error(
3511
					sprintf(
3512
						__(
3513
							"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))",
3514
							"event_espresso"
3515
						),
3516
						implode( ",", $php_array_like_string )
3517
					)
3518
				);
3519
			}
3520
			$value = isset( $op_and_value[1] ) ? $op_and_value[1] : null;
3521
		} else {
3522
			$operator = '=';
3523
			$value = $op_and_value;
3524
		}
3525
		//check to see if the value is actually another field
3526
		if ( is_array( $op_and_value ) && isset( $op_and_value[2] ) && $op_and_value[2] == true ) {
3527
			return $operator . SP . $this->_deduce_column_name_from_query_param( $value );
3528
		} elseif ( in_array( $operator, $this->_in_style_operators ) && is_array( $value ) ) {
3529
			//in this case, the value should be an array, or at least a comma-separated list
3530
			//it will need to handle a little differently
3531
			$cleaned_value = $this->_construct_in_value( $value, $field_obj );
3532
			//note: $cleaned_value has already been run through $wpdb->prepare()
3533
			return $operator . SP . $cleaned_value;
3534
		} elseif ( in_array( $operator, $this->_between_style_operators ) && is_array( $value ) ) {
3535
			//the value should be an array with count of two.
3536
			if ( count( $value ) !== 2 ) {
3537
				throw new EE_Error(
3538
					sprintf(
3539
						__(
3540
							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
3541
							'event_espresso'
3542
						),
3543
						"BETWEEN"
3544
					)
3545
				);
3546
			}
3547
			$cleaned_value = $this->_construct_between_value( $value, $field_obj );
3548
			return $operator . SP . $cleaned_value;
3549 View Code Duplication
		} elseif ( in_array( $operator, $this->_null_style_operators ) ) {
3550
			if ( $value !== null ) {
3551
				throw new EE_Error(
3552
					sprintf(
3553
						__(
3554
							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
3555
							"event_espresso"
3556
						),
3557
						$value,
3558
						$operator
3559
					)
3560
				);
3561
			}
3562
			return $operator;
3563
		} elseif ( $operator === 'LIKE' && ! is_array( $value ) ) {
3564
			//if the operator is 'LIKE', we want to allow percent signs (%) and not
3565
			//remove other junk. So just treat it as a string.
3566
			return $operator . SP . $this->_wpdb_prepare_using_field( $value, '%s' );
3567
		} elseif ( ! in_array( $operator, $this->_in_style_operators ) && ! is_array( $value ) ) {
3568
			return $operator . SP . $this->_wpdb_prepare_using_field( $value, $field_obj );
3569 View Code Duplication
		} elseif ( in_array( $operator, $this->_in_style_operators ) && ! is_array( $value ) ) {
3570
			throw new EE_Error(
3571
				sprintf(
3572
					__(
3573
						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
3574
						'event_espresso'
3575
					),
3576
					$operator,
3577
					$operator
3578
				)
3579
			);
3580
		} elseif ( ! in_array( $operator, $this->_in_style_operators ) && is_array( $value ) ) {
3581
			throw new EE_Error(
3582
				sprintf(
3583
					__(
3584
						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
3585
						'event_espresso'
3586
					),
3587
					$operator,
3588
					$operator
3589
				)
3590
			);
3591
		} else {
3592
			throw new EE_Error(
3593
				sprintf(
3594
					__(
3595
						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
3596
						"event_espresso"
3597
					),
3598
					http_build_query( $op_and_value )
3599
				)
3600
			);
3601
		}
3602
	}
3603
3604
3605
3606
	/**
3607
	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
3608
	 *
3609
	 * @param array                      $values
3610
	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg '%s'
3611
	 * @return string
3612
	 * @throws \EE_Error
3613
	 */
3614
	public function _construct_between_value( $values, $field_obj ) {
3615
		$cleaned_values = array();
3616
		foreach ( $values as $value ) {
3617
			$cleaned_values[] = $this->_wpdb_prepare_using_field($value,$field_obj);
3618
		}
3619
		return  $cleaned_values[0] . " AND " . $cleaned_values[1];
3620
	}
3621
3622
3623
3624
	/**
3625
	 * Takes an array or a comma-separated list of $values and cleans them
3626
	 * according to $data_type using $wpdb->prepare, and then makes the list a
3627
	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
3628
	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
3629
	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
3630
	 *
3631
	 * @param mixed                      $values    array or comma-separated string
3632
	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
3633
	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
3634
	 * @throws \EE_Error
3635
	 */
3636
	public function _construct_in_value($values,  $field_obj){
3637
		//check if the value is a CSV list
3638
		if(is_string($values)){
3639
			//in which case, turn it into an array
3640
			$values = explode(",",$values);
3641
		}
3642
		$cleaned_values = array();
3643
		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...
3644
			$cleaned_values[] = $this->_wpdb_prepare_using_field($value,$field_obj);
3645
		}
3646
		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
3647
		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
3648
		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
3649
		if(empty($cleaned_values)){
3650
			$all_fields = $this->field_settings();
3651
			$a_field = array_shift($all_fields);
3652
			$main_table = $this->_get_main_table();
3653
			$cleaned_values[] = "SELECT ".$a_field->get_table_column()." FROM ".$main_table->get_table_name()." WHERE FALSE";
3654
		}
3655
		return "(".implode(",",$cleaned_values).")";
3656
	}
3657
3658
3659
3660
	/**
3661
	 *
3662
	 * @param mixed 	$value
3663
	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
3664
	 * @throws EE_Error
3665
	 * @return false|null|string
3666
	 */
3667
	private function _wpdb_prepare_using_field($value,$field_obj){
3668
		/** @type WPDB $wpdb */
3669
		global $wpdb;
3670
		if($field_obj instanceof EE_Model_Field_Base){
3671
			return $wpdb->prepare($field_obj->get_wpdb_data_type(),$this->_prepare_value_for_use_in_db($value, $field_obj));
3672
		}else{//$field_obj should really just be a data type
3673 View Code Duplication
			if( ! in_array($field_obj,$this->_valid_wpdb_data_types)){
3674
				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)));
3675
			}
3676
			return $wpdb->prepare($field_obj,$value);
3677
		}
3678
	}
3679
3680
3681
3682
	/**
3683
	 * Takes the input parameter and finds the model field that it indicates.
3684
	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3685
	 * @throws EE_Error
3686
	 * @return EE_Model_Field_Base
3687
	 */
3688
	protected function _deduce_field_from_query_param($query_param_name){
3689
		//ok, now proceed with deducing which part is the model's name, and which is the field's name
3690
		//which will help us find the database table and column
3691
3692
		$query_param_parts = explode(".",$query_param_name);
3693
		if(empty($query_param_parts)){
3694
			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));
3695
		}
3696
		$number_of_parts = count($query_param_parts);
3697
		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
3698
		if($number_of_parts === 1){
3699
			$field_name = $last_query_param_part;
3700
			$model_obj = $this;
3701
		}else{// $number_of_parts >= 2
3702
			//the last part is the column name, and there are only 2parts. therefore...
3703
			$field_name = $last_query_param_part;
3704
			$model_obj = $this->get_related_model_obj( $query_param_parts[ $number_of_parts - 2 ]);
3705
		}
3706
		try{
3707
			return $model_obj->field_settings_for($field_name);
3708
		}catch(EE_Error $e){
3709
			return null;
3710
		}
3711
	}
3712
3713
3714
3715
	/**
3716
	 * 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
3717
	 * which corresponds to it
3718
	 * @param string $field_name
3719
	 * @throws EE_Error
3720
	 * @return string
3721
	 */
3722
	public function _get_qualified_column_for_field($field_name){
3723
		$all_fields = $this->field_settings();
3724
		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : FALSE;
3725
		if($field){
3726
			return $field->get_qualified_column();
3727
		}else{
3728
			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)));
3729
		}
3730
	}
3731
3732
3733
3734
	/**
3735
	 * constructs the select use on special limit joins
3736
	 * 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).
3737
	 *
3738
	 * @param  string $table_alias The table the select is being built for
3739
	 * @param  mixed|string $limit The limit for this select
3740
	 * @return string                The final select join element for the query.
3741
	 */
3742
	public function _construct_limit_join_select( $table_alias, $limit ) {
3743
		$SQL = '';
3744
		foreach ( $this->_tables as $table_obj ) {
3745
			if ( $table_obj instanceof EE_Primary_Table ) {
3746
				$SQL .= $table_alias === $table_obj->get_table_alias()
3747
					? $table_obj->get_select_join_limit( $limit )
3748
					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
3749
			} elseif ( $table_obj instanceof EE_Secondary_Table ) {
3750
				$SQL .= $table_alias === $table_obj->get_table_alias()
3751
					? $table_obj->get_select_join_limit_join( $limit )
3752
					: SP . $table_obj->get_join_sql( $table_alias ) . SP;
3753
			}
3754
		}
3755
		return $SQL;
3756
	}
3757
3758
3759
3760
	/**
3761
	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
3762
	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
3763
	 *
3764
	 * @return string SQL
3765
	 * @throws \EE_Error
3766
	 */
3767
	public function _construct_internal_join(){
3768
		$SQL = $this->_get_main_table()->get_table_sql();
3769
		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
3770
		return $SQL;
3771
	}
3772
3773
3774
3775
	/**
3776
	 * Constructs the SQL for joining all the tables on this model.
3777
	 * Normally $alias should be the primary table's alias, but in cases where
3778
	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the primary table)
3779
	 * then we should provide that secondary table's alias.
3780
	 * Eg, with $alias being the primary table's alias, this will construct SQL like:
3781
	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
3782
	 * With $alias being a secondary table's alias, this will construct SQL like:
3783
	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
3784
	 *
3785
	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
3786
	 * @return string
3787
	 */
3788
	public function _construct_internal_join_to_table_with_alias($alias_prefixed){
3789
		$SQL = '';
3790
		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
3791
		foreach($this->_tables as $table_obj){
3792
			if($table_obj instanceof EE_Secondary_Table){//table is secondary table
3793
				if($alias_sans_prefix === $table_obj->get_table_alias()){
3794
					//so we're joining to this table, meaning the table is already in
3795
					//the FROM statement, BUT the primary table isn't. So we want
3796
					//to add the inverse join sql
3797
					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
3798
				}else{
3799
					//just add a regular JOIN to this table from the primary table
3800
					$SQL .= $table_obj->get_join_sql($alias_prefixed);
3801
				}
3802
			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
3803
		}
3804
		return $SQL;
3805
	}
3806
3807
	/**
3808
	 * Gets an array for storing all the data types on the next-to-be-executed-query.
3809
	 * 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)
3810
	 * @return array
3811
	 */
3812
	public function _get_data_types(){
3813
		$data_types = array();
3814
		foreach( $this->field_settings() as $field_obj){
3815
			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
3816
			/** @var $field_obj EE_Model_Field_Base */
3817
			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
3818
		}
3819
		return $data_types;
3820
	}
3821
3822
3823
3824
	/**
3825
	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
3826
	 * @param string $model_name
3827
	 * @throws EE_Error
3828
	 * @return EEM_Base
3829
	 */
3830
	public function get_related_model_obj($model_name){
3831
		$model_classname = "EEM_".$model_name;
3832
		if(!class_exists($model_classname)){
3833
			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));
3834
		}
3835
		return call_user_func($model_classname."::instance");
3836
	}
3837
3838
3839
	/**
3840
	 * Returns the array of EE_ModelRelations for this model.
3841
	 * @return EE_Model_Relation_Base[]
3842
	 */
3843
	public function relation_settings(){
3844
		return $this->_model_relations;
3845
	}
3846
3847
	/**
3848
	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
3849
	 * because without THOSE models, this model probably doesn't have much purpose.
3850
	 * (Eg, without an event, datetimes have little purpose.)
3851
	 * @return EE_Belongs_To_Relation[]
3852
	 */
3853
	public function belongs_to_relations(){
3854
		$belongs_to_relations = array();
3855
		foreach($this->relation_settings() as $model_name => $relation_obj){
3856
			if($relation_obj instanceof EE_Belongs_To_Relation){
3857
				$belongs_to_relations[$model_name] = $relation_obj;
3858
			}
3859
		}
3860
		return $belongs_to_relations;
3861
	}
3862
3863
3864
3865
	/**
3866
	 * Returns the specified EE_Model_Relation, or throws an exception
3867
	 * @param string $relation_name name of relation, key in $this->_relatedModels
3868
	 * @throws EE_Error
3869
	 * @return EE_Model_Relation_Base
3870
	 */
3871
	public function related_settings_for($relation_name){
3872
		$relatedModels=$this->relation_settings();
3873 View Code Duplication
		if(!array_key_exists($relation_name,$relatedModels)){
3874
			throw new EE_Error(
3875
				sprintf(
3876
					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...','event_espresso'),
3877
					$relation_name,
3878
					$this->_get_class_name(),
3879
					implode( ', ', array_keys( $relatedModels ))
3880
				)
3881
			);
3882
		}
3883
		return $relatedModels[$relation_name];
3884
	}
3885
3886
3887
3888
	/**
3889
	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all fields
3890
	 * @param string $fieldName
3891
	 * @throws EE_Error
3892
	 * @return EE_Model_Field_Base
3893
	 */
3894 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...
3895
		$fieldSettings=$this->field_settings(true);
3896
		if( ! array_key_exists($fieldName,$fieldSettings)){
3897
			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'",'event_espresso'),$fieldName,get_class($this)));
3898
		}
3899
		return $fieldSettings[$fieldName];
3900
	}
3901
3902
	/**
3903
	 * Checks if this field exists on this model
3904
	 * @param string $fieldName a key in the model's _field_settings array
3905
	 * @return boolean
3906
	 */
3907
	public function has_field($fieldName){
3908
		$fieldSettings = $this->field_settings(true);
3909
		if( isset($fieldSettings[$fieldName])){
3910
			return true;
3911
		}else{
3912
			return false;
3913
		}
3914
	}
3915
3916
	/**
3917
	 * Returns whether or not this model has a relation to the specified model
3918
	 * @param string $relation_name possibly one of the keys in the relation_settings array
3919
	 * @return boolean
3920
	 */
3921
	public function has_relation($relation_name){
3922
		$relations = $this->relation_settings();
3923
		if(isset($relations[$relation_name])){
3924
			return true;
3925
		}else{
3926
			return false;
3927
		}
3928
	}
3929
3930
3931
	/**
3932
	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
3933
	 * Eg, on EE_Answer that would be ANS_ID field object
3934
	 * @param $field_obj
3935
	 * @return boolean
3936
	 */
3937
	public function is_primary_key_field( $field_obj ){
3938
		return $field_obj instanceof EE_Primary_Key_Field_Base ? TRUE : FALSE;
3939
	}
3940
3941
3942
3943
	/**
3944
	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
3945
	 * Eg, on EE_Answer that would be ANS_ID field object
3946
	 * @return EE_Model_Field_Base
3947
	 * @throws EE_Error
3948
	 */
3949
	public function get_primary_key_field(){
3950
		if( $this->_primary_key_field === NULL ){
3951
			foreach( $this->field_settings( TRUE ) as $field_obj ){
3952
				if( $this->is_primary_key_field( $field_obj )){
3953
					$this->_primary_key_field = $field_obj;
3954
					break;
3955
				}
3956
			}
3957
			if( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base ){
3958
				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s",'event_espresso'),get_class($this)));
3959
			}
3960
		}
3961
		return $this->_primary_key_field;
3962
	}
3963
3964
3965
3966
	/**
3967
	 * Returns whether or not not there is a primary key on this model.
3968
	 * Internally does some caching.
3969
	 * @return boolean
3970
	 */
3971
	public function has_primary_key_field(){
3972
		if($this->_has_primary_key_field === null){
3973
			try{
3974
				$this->get_primary_key_field();
3975
				$this->_has_primary_key_field = true;
3976
			}catch(EE_Error $e){
3977
				$this->_has_primary_key_field = false;
3978
			}
3979
		}
3980
		return $this->_has_primary_key_field;
3981
	}
3982
3983
3984
3985
	/**
3986
	 * Finds the first field of type $field_class_name.
3987
	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field, EE_Foreign_Key_Field, etc
3988
	 * @return EE_Model_Field_Base or null if none is found
3989
	 */
3990
	public function get_a_field_of_type($field_class_name){
3991
		foreach($this->field_settings() as $field){
3992
			if( $field instanceof $field_class_name ){
3993
				return $field;
3994
			}
3995
		}
3996
		return null;
3997
	}
3998
3999
4000
	/**
4001
	 * Gets a foreign key field pointing to model.
4002
	 * @param string $model_name eg Event, Registration, not EEM_Event
4003
	 * @return EE_Foreign_Key_Field_Base
4004
	 * @throws EE_Error
4005
	 */
4006
	public function get_foreign_key_to($model_name){
4007
		if( ! isset( $this->_cache_foreign_key_to_fields[ $model_name ] ) ){
4008
			foreach($this->field_settings() as $field){
4009
				if(
4010
					$field instanceof EE_Foreign_Key_Field_Base
4011
					&& in_array($model_name,$field->get_model_names_pointed_to() )
4012
				) {
4013
					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
4014
					break;
4015
				}
4016
			}
4017 View Code Duplication
			if( ! isset( $this->_cache_foreign_key_to_fields[ $model_name ] ) ){
4018
				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)));
4019
			}
4020
		}
4021
		return $this->_cache_foreign_key_to_fields[ $model_name ];
4022
	}
4023
4024
4025
4026
	/**
4027
	 * Gets the actual table for the table alias
4028
	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4029
	 * a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'. Either one works
4030
	 * @return EE_Table_Base
4031
	 */
4032
	public function get_table_for_alias($table_alias){
4033
		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4034
		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4035
	}
4036
4037
4038
4039
	/**
4040
	 * Returns a flat array of all field son this model, instead of organizing them
4041
	 * by table_alias as they are in the constructor.
4042
	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4043
	 * @return EE_Model_Field_Base[] where the keys are the field's name
4044
	 */
4045
	public function field_settings($include_db_only_fields = false){
4046
		if( $include_db_only_fields ){
4047 View Code Duplication
			if( $this->_cached_fields === NULL ){
4048
				$this->_cached_fields = array();
4049
				foreach($this->_fields as $fields_corresponding_to_table){
4050
					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...
4051
						$this->_cached_fields[$field_name]=$field_obj;
4052
					}
4053
				}
4054
			}
4055
			return $this->_cached_fields;
4056 View Code Duplication
		}else{
4057
			if( $this->_cached_fields_non_db_only === NULL ){
4058
				$this->_cached_fields_non_db_only = array();
4059
				foreach($this->_fields as $fields_corresponding_to_table){
4060
					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...
4061
						/** @var $field_obj EE_Model_Field_Base */
4062
						if( ! $field_obj->is_db_only_field() ){
4063
							$this->_cached_fields_non_db_only[$field_name]=$field_obj;
4064
						}
4065
					}
4066
				}
4067
			}
4068
			return $this->_cached_fields_non_db_only;
4069
		}
4070
	}
4071
4072
4073
4074
	/**
4075
	 *        cycle though array of attendees and create objects out of each item
4076
	 *
4077
	 * @access        private
4078
	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4079
	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not, numerically indexed)
4080
	 * @throws \EE_Error
4081
	 */
4082
	protected function _create_objects( $rows = array() ) {
4083
		$array_of_objects=array();
4084
		if(empty($rows)){
4085
			return array();
4086
		}
4087
		$count_if_model_has_no_primary_key = 0;
4088
		$has_primary_key = $this->has_primary_key_field();
4089
		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4090
		foreach ( (array)$rows as $row ) {
4091
			if(empty($row)){
4092
				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4093
				return array();
4094
			}
4095
			//check if we've already set this object in the results array,
4096
			//in which case there's no need to process it further (again)
4097
			if( $has_primary_key ) {
4098
				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4099
					$row,
4100
					$primary_key_field->get_qualified_column(),
4101
					$primary_key_field->get_table_column()
4102
				);
4103
				if( $table_pk_value && isset( $array_of_objects[ $table_pk_value ] ) ) {
4104
					continue;
4105
				}
4106
			}
4107
			$classInstance = $this->instantiate_class_from_array_or_object($row);
4108 View Code Duplication
			if( ! $classInstance ) {
4109
				throw new EE_Error(
4110
					sprintf(
4111
						__( 'Could not create instance of class %s from row %s', 'event_espresso' ),
4112
						$this->get_this_model_name(),
4113
						http_build_query( $row )
4114
					)
4115
				);
4116
			}
4117
			//set the timezone on the instantiated objects
4118
			$classInstance->set_timezone( $this->_timezone );
4119
			//make sure if there is any timezone setting present that we set the timezone for the object
4120
			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4121
			$array_of_objects[ $key ] = $classInstance;
4122
			//also, for all the relations of type BelongsTo, see if we can cache
4123
			//those related models
4124
			//(we could do this for other relations too, but if there are conditions
4125
			//that filtered out some fo the results, then we'd be caching an incomplete set
4126
			//so it requires a little more thought than just caching them immediately...)
4127
			foreach($this->_model_relations as $modelName => $relation_obj){
4128
				if( $relation_obj instanceof EE_Belongs_To_Relation){
4129
					//check if this model's INFO is present. If so, cache it on the model
4130
					$other_model = $relation_obj->get_other_model();
4131
					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4132
					//if we managed to make a model object from the results, cache it on the main model object
4133
					if( $other_model_obj_maybe ){
4134
						//set timezone on these other model objects if they are present
4135
						$other_model_obj_maybe->set_timezone( $this->_timezone );
4136
						$classInstance->cache($modelName, $other_model_obj_maybe);
4137
					}
4138
				}
4139
			}
4140
		}
4141
		return $array_of_objects;
4142
	}
4143
4144
4145
4146
	/**
4147
	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default values.
4148
	 * 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!).
4149
	 *
4150
	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4151
	 */
4152
	public function create_default_object() {
4153
4154
		$this_model_fields_and_values = array();
4155
		//setup the row using default values;
4156
		foreach ( $this->field_settings() as $field_name => $field_obj ) {
4157
			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4158
		}
4159
4160
		$className = $this->_get_class_name();
4161
		$classInstance = EE_Registry::instance()->load_class( $className, array( $this_model_fields_and_values ), FALSE, FALSE );
4162
4163
		return $classInstance;
4164
	}
4165
4166
4167
4168
	/**
4169
	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4170
	 *                             or an stdClass where each property is the name of a column,
4171
	 * @return EE_Base_Class
4172
	 * @throws \EE_Error
4173
	 */
4174
	public function instantiate_class_from_array_or_object($cols_n_values){
4175
		if( ! is_array( $cols_n_values ) && is_object( $cols_n_values )) {
4176
			$cols_n_values = get_object_vars( $cols_n_values );
4177
		}
4178
		$primary_key = NULL;
4179
		//make sure the array only has keys that are fields/columns on this model
4180
		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values( $cols_n_values );
4181
		if( $this->has_primary_key_field() && isset( $this_model_fields_n_values[ $this->primary_key_name() ] ) ){
4182
			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
4183
		}
4184
		$className=$this->_get_class_name();
4185
4186
		//check we actually found results that we can use to build our model object
4187
		//if not, return null
4188
		if( $this->has_primary_key_field()){
4189
			if(empty( $this_model_fields_n_values[$this->primary_key_name()] )){
4190
				return NULL;
4191
			}
4192
		}else if($this->unique_indexes()){
4193
			$first_column = reset($this_model_fields_n_values);
4194
			if(empty($first_column)){
4195
				return NULL;
4196
			}
4197
		}
4198
4199
		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4200
		if ( $primary_key){
4201
			$classInstance = $this->get_from_entity_map( $primary_key );
4202
			if( ! $classInstance) {
4203
				$classInstance = EE_Registry::instance()->load_class( $className, array( $this_model_fields_n_values, $this->_timezone ), TRUE, FALSE );
4204
				// add this new object to the entity map
4205
				$classInstance = $this->add_to_entity_map( $classInstance );
0 ignored issues
show
Bug introduced by
It seems like $classInstance can be null; however, add_to_entity_map() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
4206
			}
4207
		}else{
4208
			$classInstance = EE_Registry::instance()->load_class( $className, array( $this_model_fields_n_values, $this->_timezone ), TRUE, FALSE );
4209
		}
4210
4211
			//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.
4212
		$this->set_timezone( $classInstance->get_timezone() );
4213
		return $classInstance;
4214
	}
4215
	/**
4216
	 * Gets the model object from the  entity map if it exists
4217
	 * @param int|string $id the ID of the model object
4218
	 * @return EE_Base_Class
4219
	 */
4220
	public function get_from_entity_map( $id ){
4221
		return isset( $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] ) ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : NULL;
4222
	}
4223
4224
4225
4226
	/**
4227
	 * add_to_entity_map
4228
	 *
4229
	 * Adds the object to the model's entity mappings
4230
	 * 		Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4231
	 * 		and for the remainder of the request, it's even more up-to-date than what's in the database.
4232
	 * 		So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4233
	 * 		If the database gets updated directly and you want the entity mapper to reflect that change,
4234
	 * 		then this method should be called immediately after the update query
4235
	 *
4236
	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is so
4237
	 * on multisite, the entity map is specific to the query being done for a specific site.
4238
	 *
4239
	 * @param 	EE_Base_Class $object
4240
	 * @throws EE_Error
4241
	 * @return \EE_Base_Class
4242
	 */
4243
	public function add_to_entity_map( EE_Base_Class $object) {
4244
		$className = $this->_get_class_name();
4245
		if( ! $object instanceof $className ){
4246
			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 ) );
4247
		}
4248
		/** @var $object EE_Base_Class */
4249
		if ( ! $object->ID() ){
4250
			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.", "event_espresso"),get_class($this)));
4251
		}
4252
		// double check it's not already there
4253
		$classInstance = $this->get_from_entity_map( $object->ID() );
4254
		if ( $classInstance ) {
4255
			return $classInstance;
4256
		} else {
4257
			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
4258
			return $object;
4259
		}
4260
	}
4261
4262
4263
4264
	/**
4265
	 * if a valid identifier is provided, then that entity is unset from the entity map,
4266
	 * if no identifier is provided, then the entire entity map is emptied
4267
	 *
4268
	 * @param int|string $id the ID of the model object
4269
	 * @return boolean
4270
	 */
4271
	public function clear_entity_map( $id = null ) {
4272
		if ( empty( $id ) ) {
4273
			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
4274
			return true;
4275
		}
4276 View Code Duplication
		if ( isset( $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] ) ) {
4277
			unset( $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] );
4278
			return true;
4279
		}
4280
		return false;
4281
	}
4282
4283
4284
4285
	/**
4286
	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4287
	 *
4288
	 * Given an array where keys are column (or column alias) names and values,
4289
	 * returns an array of their corresponding field names and database values
4290
	 * @param array $cols_n_values
4291
	 * @return array
4292
	 */
4293
	public function deduce_fields_n_values_from_cols_n_values( $cols_n_values ) {
4294
		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...
4295
	}
4296
4297
4298
	/**
4299
	 * _deduce_fields_n_values_from_cols_n_values
4300
	 *
4301
	 * Given an array where keys are column (or column alias) names and values,
4302
	 * returns an array of their corresponding field names and database values
4303
	 *
4304
	 * @param string $cols_n_values
4305
	 * @return array
4306
	 */
4307
	protected function _deduce_fields_n_values_from_cols_n_values( $cols_n_values ){
4308
		$this_model_fields_n_values = array();
4309
		foreach( $this->get_tables() as $table_alias => $table_obj ) {
4310
			$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() );
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $table_pk_value is correct as $this->_get_column_value...e_obj->get_pk_column()) (which targets EEM_Base::_get_column_va...th_table_alias_or_not()) 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...
4311
			//there is a primary key on this table and its not set. Use defaults for all its columns
4312
			if( $table_pk_value === null && $table_obj->get_pk_column() ){
4313
				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...
4314
					if( ! $field_obj->is_db_only_field() ){
4315
						//prepare field as if its coming from db
4316
						$prepared_value = $field_obj->prepare_for_set( $field_obj->get_default_value() );
4317
						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db( $prepared_value );
4318
					}
4319
				}
4320
			}else{
4321
				//the table's rows existed. Use their values
4322
				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...
4323
					if( ! $field_obj->is_db_only_field() ){
4324
						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $this_model_fields_n_values[$field_name] is correct as $this->_get_column_value...bj->get_table_column()) (which targets EEM_Base::_get_column_va...th_table_alias_or_not()) 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...
4325
							$cols_n_values, $field_obj->get_qualified_column(),
4326
							$field_obj->get_table_column()
4327
						);
4328
					}
4329
				}
4330
			}
4331
		}
4332
		return $this_model_fields_n_values;
4333
	}
4334
4335
4336
4337
	/**
4338
	 * @param $cols_n_values
4339
	 * @param $qualified_column
4340
	 * @param $regular_column
4341
	 * @return null
4342
	 */
4343
	protected function _get_column_value_with_table_alias_or_not( $cols_n_values, $qualified_column, $regular_column ){
4344
		$value = null;
4345
		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4346
		//does the field on the model relate to this column retrieved from the db?
4347
		//or is it a db-only field? (not relating to the model)
4348
		if( isset( $cols_n_values[ $qualified_column ] ) ){
4349
			$value = $cols_n_values[ $qualified_column ];
4350
		}elseif( isset( $cols_n_values[ $regular_column ] ) ){
4351
			$value = $cols_n_values[ $regular_column ];
4352
		}
4353
		return $value;
4354
	}
4355
4356
4357
4358
	/**
4359
	 * refresh_entity_map_from_db
4360
	 * Makes sure the model object in the entity map at $id assumes the values
4361
	 * of the database (opposite of EE_base_Class::save())
4362
	 *
4363
	 * @param int|string $id
4364
	 * @return EE_Base_Class
4365
	 * @throws \EE_Error
4366
	 */
4367
	public function refresh_entity_map_from_db( $id ){
4368
		$obj_in_map = $this->get_from_entity_map( $id );
4369
		if( $obj_in_map ){
4370
			$wpdb_results = $this->_get_all_wpdb_results(
4371
				array( array( $this->get_primary_key_field()->get_name() => $id ), 'limit' => 1 )
4372
			);
4373
			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...
4374
				$one_row = reset( $wpdb_results );
4375
				foreach( $this->_deduce_fields_n_values_from_cols_n_values($one_row ) as $field_name => $db_value ) {
4376
					$obj_in_map->set_from_db( $field_name, $db_value );
4377
				}
4378
				//clear the cache of related model objects
4379
				foreach ( $this->relation_settings() as $relation_name => $relation_obj ){
4380
					$obj_in_map->clear_cache($relation_name, NULL, TRUE );
4381
				}
4382
			}
4383
			return $obj_in_map;
4384
		}else{
4385
			return $this->get_one_by_ID( $id );
4386
		}
4387
	}
4388
4389
4390
4391
	/**
4392
	 * refresh_entity_map_with
4393
	 * Leaves the entry in the entity map alone, but updates it to match the provided
4394
	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
4395
	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
4396
	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
4397
	 *
4398
	 * @param int|string    $id
4399
	 * @param EE_Base_Class $replacing_model_obj
4400
	 * @return \EE_Base_Class
4401
	 * @throws \EE_Error
4402
	 */
4403
	public function refresh_entity_map_with( $id, $replacing_model_obj ) {
4404
		$obj_in_map = $this->get_from_entity_map( $id );
4405
		if( $obj_in_map ){
4406
			if( $replacing_model_obj instanceof EE_Base_Class ){
4407
				foreach( $replacing_model_obj->model_field_array() as $field_name => $value ) {
4408
					$obj_in_map->set( $field_name, $value );
4409
				}
4410
				//make the model object in the entity map's cache match the $replacing_model_obj
4411
				foreach ( $this->relation_settings() as $relation_name => $relation_obj ){
4412
					$obj_in_map->clear_cache($relation_name, NULL, TRUE );
4413
					foreach( $replacing_model_obj->get_all_from_cache( $relation_name ) as $cache_id => $cached_obj ) {
4414
						$obj_in_map->cache( $relation_name, $cached_obj, $cache_id );
4415
					}
4416
				}
4417
			}
4418
			return $obj_in_map;
4419
		}else{
4420
			$this->add_to_entity_map( $replacing_model_obj );
4421
			return $replacing_model_obj;
4422
		}
4423
	}
4424
4425
4426
4427
	/**
4428
	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
4429
	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
4430
	 * require_once($this->_getClassName().".class.php");
4431
	 * @return string
4432
	 */
4433
	private function _get_class_name(){
4434
		return "EE_".$this->get_this_model_name();
4435
	}
4436
4437
4438
4439
	/**
4440
	 * Get the name of the items this model represents, for the quantity specified. Eg,
4441
	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
4442
	 * it would be 'Events'.
4443
	 * @param int $quantity
4444
	 * @return string
4445
	 */
4446
	public function item_name($quantity = 1){
4447
		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
4448
	}
4449
4450
4451
4452
	/**
4453
	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
4454
	 * 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)
4455
	 * and passed the method's name and arguments.
4456
	 * Instead of requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that happen?)
4457
	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg, filters_hook_espresso__EE_Answer__my_great_function)
4458
	 * 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.
4459
	 * Example: in functions.php (or in a plugin):
4460
	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
4461
	 * function my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
4462
	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
4463
	 *        return $previousReturnValue.$returnString;
4464
	 * }
4465
	 * require('EEM_Answer.model.php');
4466
	 * $answer=EEM_Answer::instance();
4467
	 * echo $answer->my_callback('monkeys',100);
4468
	 * //will output "you called my_callback! and passed args:monkeys,100"
4469
	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
4470
	 * @param array  $args       array of original arguments passed to the function
4471
	 * @throws EE_Error
4472
	 * @return mixed whatever the plugin which calls add_filter decides
4473
	 */
4474 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...
4475
		$className=get_class($this);
4476
		$tagName="FHEE__{$className}__{$methodName}";
4477
		if(!has_filter($tagName)){
4478
			throw new EE_Error(
4479
				sprintf(
4480
					__( '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' ),
4481
					$methodName,
4482
					$className,
4483
					$tagName,
4484
					'<br />'
4485
				)
4486
			);
4487
		}
4488
4489
		return apply_filters($tagName,null,$this,$args);
4490
	}
4491
4492
4493
4494
	/**
4495
	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
4496
	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
4497
	 *
4498
	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
4499
	 *                                                       the EE_Base_Class object that corresponds to this Model,
4500
	 *                                                       the object's class name
4501
	 *                                                       or object's ID
4502
	 * @param boolean $ensure_is_in_db                       if set, we will also verify this model object
4503
	 *                                                       exists in the database. If it does not, we add it
4504
	 * @throws EE_Error
4505
	 * @return EE_Base_Class
4506
	 */
4507
	public function ensure_is_obj( $base_class_obj_or_id, $ensure_is_in_db = FALSE ){
4508
		$className = $this->_get_class_name();
4509
		if ( $base_class_obj_or_id instanceof $className ) {
4510
			$model_object = $base_class_obj_or_id;
4511
		} else {
4512
			$primary_key_field = $this->get_primary_key_field();
4513
			if (
4514
				$primary_key_field instanceof EE_Primary_Key_Int_Field
4515
				&& (
4516
					is_int( $base_class_obj_or_id )
4517
					|| is_string( $base_class_obj_or_id )
4518
				)
4519
			) {
4520
				// assume it's an ID.
4521
				// either a proper integer or a string representing an integer (eg "101" instead of 101)
4522
				$model_object = $this->get_one_by_ID( $base_class_obj_or_id );
4523
			} else if (
4524
				$primary_key_field instanceof EE_Primary_Key_String_Field
4525
			    && is_string( $base_class_obj_or_id )
4526
			) {
4527
				// assume its a string representation of the object
4528
				$model_object = $this->get_one_by_ID( $base_class_obj_or_id );
4529
			} else {
4530
				throw new EE_Error(
4531
					sprintf(
4532
						__(
4533
							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
4534
							'event_espresso'
4535
						),
4536
						$base_class_obj_or_id,
4537
						$this->_get_class_name(),
4538
						print_r( $base_class_obj_or_id, true )
4539
					)
4540
				);
4541
			}
4542
		}
4543
		if ( $ensure_is_in_db && $model_object->ID() !== null ) {
4544
			$model_object->save();
4545
		}
4546
		return $model_object;
4547
	}
4548
4549
4550
4551
	/**
4552
	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
4553
	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
4554
	 * returns it ID.
4555
	 * @param EE_Base_Class|int|string $base_class_obj_or_id
4556
	 * @return int|string depending on the type of this model object's ID
4557
	 * @throws EE_Error
4558
	 */
4559
	public function ensure_is_ID($base_class_obj_or_id){
4560
		$className = $this->_get_class_name();
4561
		if( $base_class_obj_or_id instanceof $className ){
4562
			/** @var $base_class_obj_or_id EE_Base_Class */
4563
			$id = $base_class_obj_or_id->ID();
4564
		}elseif(is_int($base_class_obj_or_id)){
4565
			//assume it's an ID
4566
			$id = $base_class_obj_or_id;
4567
		}elseif(is_string($base_class_obj_or_id)){
4568
			//assume its a string representation of the object
4569
			$id = $base_class_obj_or_id;
4570
		}else{
4571
			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)));
4572
		}
4573
		return $id;
4574
	}
4575
4576
4577
4578
	/**
4579
	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
4580
	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
4581
	 * been sanitized and converted into the appropriate domain.
4582
	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by the model
4583
	 * object/model field) is when making a method call from WITHIN a model object, which has direct access to its sanitized
4584
	 * values.
4585
	 * Note: after changing this setting, you should set it back to its previous value (using get_assumption_concerning_values_already_prepared_by_model_object())
4586
	 * eg.
4587
	 * $EVT = EEM_Event::instance(); $old_setting = $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
4588
	 * $EVT->assume_values_already_prepared_by_model_object(true);
4589
	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
4590
	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
4591
	 * @param int $values_already_prepared like one of the constants on EEM_Base
4592
	 * @return void
4593
	 */
4594
	public function assume_values_already_prepared_by_model_object($values_already_prepared = self::not_prepared_by_model_object){
4595
		$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...
4596
	}
4597
	/**
4598
	 * Read comments for assume_values_already_prepared_by_model_object()
4599
	 * @return int
4600
	 */
4601
	public function get_assumption_concerning_values_already_prepared_by_model_object(){
4602
		return $this->_values_already_prepared_by_model_object;
4603
	}
4604
4605
	/**
4606
	 * Gets all the indexes on this model
4607
	 * @return EE_Index[]
4608
	 */
4609
	public function indexes(){
4610
		return $this->_indexes;
4611
	}
4612
	/**
4613
	 * Gets all the Unique Indexes on this model
4614
	 * @return EE_Unique_Index[]
4615
	 */
4616
	public function unique_indexes(){
4617
		$unique_indexes = array();
4618
		foreach($this->_indexes as $name => $index){
4619
			if($index instanceof EE_Unique_Index){
4620
				$unique_indexes [$name] = $index;
4621
			}
4622
		}
4623
		return $unique_indexes;
4624
	}
4625
4626
4627
4628
	/**
4629
	 * Gets all the fields which, when combined, make the primary key.
4630
	 * This is usually just an array with 1 element (the primary key), but in cases
4631
	 * where there is no primary key, it's a combination of fields as defined
4632
	 * on a primary index
4633
	 *
4634
	 * @return EE_Model_Field_Base[] indexed by the field's name
4635
	 * @throws \EE_Error
4636
	 */
4637
	public function get_combined_primary_key_fields(){
4638
		foreach($this->indexes() as $index){
4639
			if($index instanceof EE_Primary_Key_Index){
4640
				return $index->fields();
4641
			}
4642
		}
4643
		return array( $this->primary_key_name() => $this->get_primary_key_field());
4644
	}
4645
4646
4647
4648
4649
	/**
4650
	 * Used to build a primary key string (when the model has no primary key),
4651
	 * which can be used a unique string to identify this model object.
4652
	 *
4653
	 * @param array $cols_n_values keys are field names, values are their values
4654
	 * @return string
4655
	 * @throws \EE_Error
4656
	 */
4657
	public function get_index_primary_key_string($cols_n_values){
4658
		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values, $this->get_combined_primary_key_fields());
4659
		return http_build_query($cols_n_values_for_primary_key_index);
4660
	}
4661
4662
4663
4664
	/**
4665
	 * Gets the field values from the primary key string
4666
	 *
4667
	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
4668
	 * @param string $index_primary_key_string
4669
	 * @return null|array
4670
	 * @throws \EE_Error
4671
	 */
4672
	public function parse_index_primary_key_string( $index_primary_key_string) {
4673
		$key_fields = $this->get_combined_primary_key_fields();
4674
		//check all of them are in the $id
4675
		$key_vals_in_combined_pk = array();
4676
		parse_str( $index_primary_key_string, $key_vals_in_combined_pk );
4677
		foreach( $key_fields as $key_field_name => $field_obj ) {
4678
			if( ! isset( $key_vals_in_combined_pk[ $key_field_name ] ) ){
4679
				return NULL;
4680
			}
4681
		}
4682
		return $key_vals_in_combined_pk;
4683
	}
4684
4685
4686
4687
	/**
4688
	 * verifies that an array of key-value pairs for model fields has a key
4689
	 * for each field comprising the primary key index
4690
	 *
4691
	 * @param array $key_vals
4692
	 * @return boolean
4693
	 * @throws \EE_Error
4694
	 */
4695
	public function has_all_combined_primary_key_fields( $key_vals ) {
4696
		$keys_it_should_have = array_keys( $this->get_combined_primary_key_fields() );
4697
		foreach( $keys_it_should_have as $key ){
4698
			if( ! isset( $key_vals[ $key ] ) ){
4699
				return false;
4700
			}
4701
		}
4702
		return true;
4703
	}
4704
4705
4706
	/**
4707
	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
4708
	 * We consider something to be a copy if all the attributes match (except the ID, of course).
4709
	 * @param array|EE_Base_Class $model_object_or_attributes_array 	If its an array, it's field-value pairs
4710
	 * @param array                $query_params like EEM_Base::get_all's query_params.
4711
	 * @throws EE_Error
4712
	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically indexed)
4713
	 */
4714
	public function get_all_copies($model_object_or_attributes_array, $query_params = array()){
4715
4716 View Code Duplication
		if($model_object_or_attributes_array instanceof EE_Base_Class){
4717
			$attributes_array = $model_object_or_attributes_array->model_field_array();
4718
		}elseif(is_array($model_object_or_attributes_array)){
4719
			$attributes_array = $model_object_or_attributes_array;
4720
		}else{
4721
			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));
4722
		}
4723
		//even copies obviously won't have the same ID, so remove the primary key
4724
		//from the WHERE conditions for finding copies (if there is a primary key, of course)
4725
		if($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])){
4726
			unset($attributes_array[$this->primary_key_name()]);
4727
		}
4728
		if(isset($query_params[0])){
4729
			$query_params[0] = array_merge($attributes_array,$query_params);
4730
		}else{
4731
			$query_params[0] = $attributes_array;
4732
		}
4733
		return $this->get_all($query_params);
4734
	}
4735
4736
4737
4738
	/**
4739
	 * Gets the first copy we find. See get_all_copies for more details
4740
	 *
4741
	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
4742
	 * @param array $query_params
4743
	 * @return EE_Base_Class
4744
	 * @throws \EE_Error
4745
	 */
4746 View Code Duplication
	public 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...
4747
		if( ! is_array( $query_params ) ){
4748
			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' );
4749
			$query_params = array();
4750
		}
4751
		$query_params['limit'] = 1;
4752
		$copies = $this->get_all_copies($model_object_or_attributes_array,$query_params);
4753
		if(is_array($copies)){
4754
			return array_shift($copies);
4755
		}else{
4756
			return null;
4757
		}
4758
	}
4759
4760
4761
4762
	/**
4763
	 * Updates the item with the specified id. Ignores default query parameters because
4764
	 * we have specified the ID, and its assumed we KNOW what we're doing
4765
	 *
4766
	 * @param array      $fields_n_values keys are field names, values are their new values
4767
	 * @param int|string $id              the value of the primary key to update
4768
	 * @return int number of rows updated
4769
	 * @throws \EE_Error
4770
	 */
4771
	public function update_by_ID($fields_n_values,$id){
4772
		$query_params = array(0=>array($this->get_primary_key_field()->get_name() => $id),
4773
			'default_where_conditions'=>'other_models_only',);
4774
		return $this->update($fields_n_values,$query_params);
4775
	}
4776
4777
4778
4779
	/**
4780
	 * Changes an operator which was supplied to the models into one usable in SQL
4781
	 * @param string $operator_supplied
4782
	 * @return string an operator which can be used in SQL
4783
	 * @throws EE_Error
4784
	 */
4785
	private function _prepare_operator_for_sql($operator_supplied){
4786
		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied] : null;
4787 View Code Duplication
		if($sql_operator){
4788
			return $sql_operator;
4789
		}else{
4790
			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))));
4791
		}
4792
	}
4793
4794
4795
4796
	/**
4797
	 * Gets an array where keys are the primary keys and values are their 'names'
4798
	 * (as determined by the model object's name() function, which is often overridden)
4799
	 *
4800
	 * @param array $query_params like get_all's
4801
	 * @return string[]
4802
	 * @throws \EE_Error
4803
	 */
4804
	public function get_all_names($query_params = array()){
4805
		$objs = $this->get_all($query_params);
4806
		$names = array();
4807
		foreach($objs as $obj){
4808
			$names[$obj->ID()] = $obj->name();
4809
		}
4810
		return $names;
4811
	}
4812
4813
4814
4815
	/**
4816
	 * Gets an array of primary keys from the model objects. If you acquired the model objects
4817
	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
4818
	 * this is duplicated effort and reduces efficiency) you would be better to use
4819
	 * array_keys() on $model_objects.
4820
	 *
4821
	 * @param \EE_Base_Class[] $model_objects
4822
	 * @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
4823
	 * @return array
4824
	 * @throws \EE_Error
4825
	 */
4826
	public function get_IDs( $model_objects, $filter_out_empty_ids = false) {
4827
		if( ! $this->has_primary_key_field() ) {
4828
			if( WP_DEBUG ) {
4829
				EE_Error::add_error(
4830
					__( 'Trying to get IDs from a model than has no primary key', 'event_espresso' ),
4831
					__FILE__,
4832
					__FUNCTION__,
4833
					__LINE__
4834
				);
4835
			}
4836
		}
4837
		$IDs = array();
4838
		foreach( $model_objects as $model_object ) {
4839
			$id = $model_object->ID();
4840
			if( ! $id ) {
4841
				if( $filter_out_empty_ids ) {
4842
					continue;
4843
				}
4844
				if ( WP_DEBUG ) {
4845
					EE_Error::add_error(
4846
						__(
4847
							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
4848
							'event_espresso'
4849
						),
4850
						__FILE__,
4851
						__FUNCTION__,
4852
						__LINE__
4853
					);
4854
				}
4855
			}
4856
			$IDs[] = $id;
4857
		}
4858
		return $IDs;
4859
	}
4860
4861
	/**
4862
	 * Returns the string used in capabilities relating to this model. If there
4863
	 * are no capabilities that relate to this model returns false
4864
	 * @return string|false
4865
	 */
4866
	public function cap_slug(){
4867
		return apply_filters( 'FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
4868
	}
4869
4870
4871
4872
	/**
4873
	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
4874
	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
4875
	 * only returns the cap restrictions array in that context (ie, the array
4876
	 * at that key)
4877
	 *
4878
	 * @param string $context
4879
	 * @return EE_Default_Where_Conditions[] indexed by associated capability
4880
	 * @throws \EE_Error
4881
	 */
4882
	public function cap_restrictions( $context = EEM_Base::caps_read ) {
4883
		EEM_Base::verify_is_valid_cap_context( $context );
4884
		//check if we ought to run the restriction generator first
4885
		if(
4886
			isset( $this->_cap_restriction_generators[ $context ] )
4887
			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
4888
			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
4889
		) {
4890
			$this->_cap_restrictions[ $context ] = array_merge(
4891
				$this->_cap_restrictions[ $context ],
4892
				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
4893
			);
4894
		}
4895
		//and make sure we've finalized the construction of each restriction
4896
		foreach( $this->_cap_restrictions[ $context ] as $where_conditions_obj ) {
4897
			if ( $where_conditions_obj instanceof EE_Default_Where_Conditions ) {
4898
				$where_conditions_obj->_finalize_construct( $this );
4899
			}
4900
		}
4901
4902
		return $this->_cap_restrictions[ $context ];
4903
	}
4904
4905
	/**
4906
	 * Indicating whether or not this model thinks its a wp core model
4907
	 * @return boolean
4908
	 */
4909
	public function is_wp_core_model(){
4910
		return $this->_wp_core_model;
4911
	}
4912
4913
4914
4915
	/**
4916
	 * Gets all the caps that are missing which impose a restriction on
4917
	 * queries made in this context
4918
	 *
4919
	 * @param string $context one of EEM_Base::caps_ constants
4920
	 * @return EE_Default_Where_Conditions[] indexed by capability name
4921
	 * @throws \EE_Error
4922
	 */
4923
	public function caps_missing( $context = EEM_Base::caps_read ) {
4924
		$missing_caps = array();
4925
		$cap_restrictions = $this->cap_restrictions( $context );
4926
		foreach( $cap_restrictions as $cap => $restriction_if_no_cap ) {
4927
			if( ! EE_Capabilities::instance()->current_user_can( $cap, $this->get_this_model_name() . '_model_applying_caps') ) {
4928
				$missing_caps[ $cap ] = $restriction_if_no_cap;
4929
			}
4930
		}
4931
		return $missing_caps;
4932
	}
4933
4934
	/**
4935
	 * Gets the mapping from capability contexts to action strings used in capability names
4936
	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
4937
	 * one of 'read', 'edit', or 'delete'
4938
	 */
4939
	public function cap_contexts_to_cap_action_map() {
4940
		return apply_filters( 'FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map, $this );
4941
	}
4942
4943
4944
4945
	/**
4946
	 * Gets the action string for the specified capability context
4947
	 * @param string $context
4948
	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
4949
	 * @throws \EE_Error
4950
	 */
4951
	public function cap_action_for_context( $context ) {
4952
		$mapping = $this->cap_contexts_to_cap_action_map();
4953
		if( isset( $mapping[ $context ] ) ) {
4954
			return $mapping[ $context ];
4955
		}
4956
		if( $action = apply_filters( 'FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context ) ) {
4957
			return $action;
4958
		}
4959
		throw new EE_Error(
4960
			sprintf(
4961
				__( 'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso' ),
4962
				$context,
4963
				implode(',', array_keys( $this->cap_contexts_to_cap_action_map() ) )
4964
			)
4965
		);
4966
4967
	}
4968
4969
	/**
4970
	 * Returns all the capability contexts which are valid when querying models
4971
	 * @return array
4972
	 */
4973
	static public function valid_cap_contexts() {
4974
		return apply_filters( 'FHEE__EEM_Base__valid_cap_contexts', array(
4975
			self::caps_read,
4976
			self::caps_read_admin,
4977
			self::caps_edit,
4978
			self::caps_delete
4979
		));
4980
	}
4981
4982
4983
4984
	/**
4985
	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
4986
	 * @param string $context
4987
	 * @return bool
4988
	 * @throws \EE_Error
4989
	 */
4990
	static public function verify_is_valid_cap_context( $context ) {
4991
		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
4992 View Code Duplication
		if( in_array( $context, $valid_cap_contexts ) ) {
4993
			return true;
4994
		}else{
4995
			throw new EE_Error(
4996
				sprintf(
4997
					__( 'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s', 'event_espresso' ),
4998
					$context,
4999
					'EEM_Base' ,
5000
					implode(',', $valid_cap_contexts )
5001
				)
5002
			);
5003
		}
5004
	}
5005
5006
	/**
5007
	 * Clears all the models field caches. This is only useful when a sub-class
5008
	 * might have added a field or something and these caches might be invalidated
5009
	 */
5010
	protected function _invalidate_field_caches() {
5011
		$this->_cache_foreign_key_to_fields = array();
5012
		$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...
5013
		$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...
5014
	}
5015
5016
5017
5018
5019
}
5020