Completed
Branch FET/Gutenberg/11467/espresso-c... (b0019e)
by
unknown
49:48 queued 35:26
created
core/helpers/EEH_MSG_Template.helper.php 2 patches
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -492,7 +492,7 @@  discard block
 block discarded – undo
492 492
 		if ( ! empty( $sending_messenger ) ) {
493 493
 			$with_messengers = $message_type->with_messengers();
494 494
 			if ( ! isset( $with_messengers[$message->messenger()] )
495
-			     || ! in_array( $sending_messenger, $with_messengers[$message->messenger()] ) ) {
495
+				 || ! in_array( $sending_messenger, $with_messengers[$message->messenger()] ) ) {
496 496
 				throw new EE_Error(
497 497
 					sprintf(
498 498
 						__(
@@ -1202,14 +1202,14 @@  discard block
 block discarded – undo
1202 1202
 			return array();
1203 1203
 		}
1204 1204
 
1205
-        $excluded_fields_for_messenger = $message_type->excludedFieldsForMessenger($messenger_name);
1205
+		$excluded_fields_for_messenger = $message_type->excludedFieldsForMessenger($messenger_name);
1206 1206
 
1207 1207
 		//okay now let's assemble an array with the messenger template fields added to the message_type contexts.
1208 1208
 		foreach ( $message_type->get_contexts() as $context => $details ) {
1209 1209
 			foreach ( $messenger->get_template_fields() as $field => $value ) {
1210
-			    if (in_array($field, $excluded_fields_for_messenger, true)) {
1211
-			        continue;
1212
-                }
1210
+				if (in_array($field, $excluded_fields_for_messenger, true)) {
1211
+					continue;
1212
+				}
1213 1213
 				$template_fields[ $context ][ $field ] = $value;
1214 1214
 			}
1215 1215
 		}
Please login to merge, or discard this patch.
Spacing   +197 added lines, -197 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-if (!defined('EVENT_ESPRESSO_VERSION') )
3
+if ( ! defined('EVENT_ESPRESSO_VERSION'))
4 4
 	exit('NO direct script access allowed');
5 5
 
6 6
 /**
@@ -59,24 +59,24 @@  discard block
 block discarded – undo
59 59
 	 *                was not a new generated template but just reactivated (which only happens for global templates that
60 60
 	 *                already exist in the database.
61 61
 	 */
62
-	public static function generate_new_templates( $messenger, $message_types, $GRP_ID = 0, $global = false ) {
62
+	public static function generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false) {
63 63
 		//make sure message_type is an array.
64 64
 		$message_types = (array) $message_types;
65 65
 		$templates = array();
66 66
 
67
-		if ( empty( $messenger ) ) {
68
-			throw new EE_Error( __('We need a messenger to generate templates!', 'event_espresso') );
67
+		if (empty($messenger)) {
68
+			throw new EE_Error(__('We need a messenger to generate templates!', 'event_espresso'));
69 69
 		}
70 70
 
71 71
 		//if we STILL have empty $message_types then we need to generate an error message b/c we NEED message types to do the template files.
72
-		if ( empty( $message_types ) ) {
73
-			throw new EE_Error( __('We need at least one message type to generate templates!', 'event_espresso') );
72
+		if (empty($message_types)) {
73
+			throw new EE_Error(__('We need at least one message type to generate templates!', 'event_espresso'));
74 74
 		}
75 75
 
76 76
 		EEH_MSG_Template::_set_autoloader();
77
-		foreach ( $message_types as $message_type ) {
77
+		foreach ($message_types as $message_type) {
78 78
 			//if global then let's attempt to get the GRP_ID for this combo IF GRP_ID is empty.
79
-			if ( $global && empty( $GRP_ID ) ) {
79
+			if ($global && empty($GRP_ID)) {
80 80
 				$GRP_ID = EEM_Message_Template_Group::instance()->get_one(
81 81
 					array(
82 82
 						array(
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 			// if this is global template generation.
92 92
 			// First let's determine if we already HAVE global templates for this messenger and message_type combination.
93 93
 			//  If we do then NO generation!!
94
-			if ( $global && EEH_MSG_Template::already_generated( $messenger, $message_type, $GRP_ID ) ) {
94
+			if ($global && EEH_MSG_Template::already_generated($messenger, $message_type, $GRP_ID)) {
95 95
 				$templates[] = array(
96 96
 					'GRP_ID' => $GRP_ID,
97 97
 					'MTP_context' => '',
@@ -99,9 +99,9 @@  discard block
 block discarded – undo
99 99
 				//we already have generated templates for this so let's go to the next message type.
100 100
 				continue;
101 101
 			}
102
-			$new_message_template_group = EEH_MSG_Template::create_new_templates( $messenger, $message_type, $GRP_ID, $global );
102
+			$new_message_template_group = EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $global);
103 103
 
104
-			if ( ! $new_message_template_group ) {
104
+			if ( ! $new_message_template_group) {
105 105
 				continue;
106 106
 			}
107 107
 			$templates[] = $new_message_template_group;
@@ -118,10 +118,10 @@  discard block
 block discarded – undo
118 118
 	 * @param  int $GRP_ID        GRP ID ( if a custom template) (if not provided then we're just doing global template check)
119 119
 	 * @return bool                true = generated, false = hasn't been generated.
120 120
 	 */
121
-	public static function already_generated( $messenger, $message_type, $GRP_ID = 0 ) {
121
+	public static function already_generated($messenger, $message_type, $GRP_ID = 0) {
122 122
 		EEH_MSG_Template::_set_autoloader();
123 123
 		//what method we use depends on whether we have an GRP_ID or not
124
-		$count = empty( $GRP_ID )
124
+		$count = empty($GRP_ID)
125 125
 			? EEM_Message_Template::instance()->count(
126 126
 				array(
127 127
 					array(
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
 					)
132 132
 				)
133 133
 			)
134
-			: EEM_Message_Template::instance()->count( array( array( 'GRP_ID' => $GRP_ID ) ) );
134
+			: EEM_Message_Template::instance()->count(array(array('GRP_ID' => $GRP_ID)));
135 135
 
136 136
 		return $count > 0;
137 137
 	}
@@ -147,15 +147,15 @@  discard block
 block discarded – undo
147 147
 	 * @param  array  $message_type_names  Message type slug
148 148
 	 * @return  int 						count of updated records.
149 149
 	 */
150
-	public static function update_to_active( $messenger_names, $message_type_names ) {
151
-		$messenger_names = is_array( $messenger_names ) ? $messenger_names : array( $messenger_names );
152
-		$message_type_names = is_array( $message_type_names ) ? $message_type_names : array( $message_type_names );
150
+	public static function update_to_active($messenger_names, $message_type_names) {
151
+		$messenger_names = is_array($messenger_names) ? $messenger_names : array($messenger_names);
152
+		$message_type_names = is_array($message_type_names) ? $message_type_names : array($message_type_names);
153 153
 		return EEM_Message_Template_Group::instance()->update(
154
-			array( 'MTP_is_active' => 1 ),
154
+			array('MTP_is_active' => 1),
155 155
 			array(
156 156
 				array(
157
-					'MTP_messenger' 	=> array( 'IN', $messenger_names ),
158
-					'MTP_message_type'  => array( 'IN', $message_type_names )
157
+					'MTP_messenger' 	=> array('IN', $messenger_names),
158
+					'MTP_message_type'  => array('IN', $message_type_names)
159 159
 				)
160 160
 			)
161 161
 		);
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 	 *
177 177
 	 * @return int  count of updated records.
178 178
 	 */
179
-	public static function update_to_inactive( $messenger_names = array(), $message_type_names = array() ) {
179
+	public static function update_to_inactive($messenger_names = array(), $message_type_names = array()) {
180 180
 		return EEM_Message_Template_Group::instance()->deactivate_message_template_groups_for(
181 181
 			$messenger_names,
182 182
 			$message_type_names
@@ -193,9 +193,9 @@  discard block
 block discarded – undo
193 193
 	 * @param string $type
194 194
 	 * @return array array consisting of installed messenger objects and installed message type objects.
195 195
 	 */
196
-	public static function get_installed_message_objects( $type = 'all' ) {
196
+	public static function get_installed_message_objects($type = 'all') {
197 197
 		self::_set_autoloader();
198
-		$message_resource_manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
198
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
199 199
 		return array(
200 200
 			'messenger' => $message_resource_manager->installed_messengers(),
201 201
 			'message_type' => $message_resource_manager->installed_message_types()
@@ -231,74 +231,74 @@  discard block
 block discarded – undo
231 231
 		$context = 'admin',
232 232
 		$merged = false
233 233
 	) {
234
-		$messenger_name = str_replace( ' ', '_', ucwords( str_replace( '_', ' ', $messenger ) ) );
235
-		$mt_name = str_replace( ' ', '_', ucwords( str_replace( '_', ' ', $message_type ) ) );
234
+		$messenger_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $messenger)));
235
+		$mt_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $message_type)));
236 236
 		/** @var EE_Message_Resource_Manager $message_resource_manager */
237
-		$message_resource_manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
237
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
238 238
 		//convert slug to object
239
-		$messenger = $message_resource_manager->get_messenger( $messenger );
239
+		$messenger = $message_resource_manager->get_messenger($messenger);
240 240
 
241 241
 		//if messenger isn't a EE_messenger resource then bail.
242
-		if ( ! $messenger instanceof EE_messenger ) {
242
+		if ( ! $messenger instanceof EE_messenger) {
243 243
 			return array();
244 244
 		}
245 245
 
246 246
 		//validate class for getting our list of shortcodes
247
-		$classname = 'EE_Messages_' . $messenger_name . '_' . $mt_name . '_Validator';
248
-		if ( ! class_exists( $classname ) ) {
249
-			$msg[] = __( 'The Validator class was unable to load', 'event_espresso' );
247
+		$classname = 'EE_Messages_'.$messenger_name.'_'.$mt_name.'_Validator';
248
+		if ( ! class_exists($classname)) {
249
+			$msg[] = __('The Validator class was unable to load', 'event_espresso');
250 250
 			$msg[] = sprintf(
251
-				__( 'The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso' ),
251
+				__('The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso'),
252 252
 				$classname
253 253
 			);
254
-			throw new EE_Error( implode( '||', $msg ) );
254
+			throw new EE_Error(implode('||', $msg));
255 255
 		}
256 256
 
257 257
 		/** @type EE_Messages_Validator $_VLD */
258
-		$_VLD = new $classname( array(), $context );
258
+		$_VLD = new $classname(array(), $context);
259 259
 		$valid_shortcodes = $_VLD->get_validators();
260 260
 
261 261
 		//let's make sure we're only getting the shortcode part of the validators
262 262
 		$shortcodes = array();
263
-		foreach ( $valid_shortcodes as $field => $validators ) {
264
-			$shortcodes[ $field ] = $validators['shortcodes'];
263
+		foreach ($valid_shortcodes as $field => $validators) {
264
+			$shortcodes[$field] = $validators['shortcodes'];
265 265
 		}
266 266
 		$valid_shortcodes = $shortcodes;
267 267
 
268 268
 		//if not all fields let's make sure we ONLY include the shortcodes for the specified fields.
269
-		if ( ! empty( $fields ) ) {
269
+		if ( ! empty($fields)) {
270 270
 			$specified_shortcodes = array();
271
-			foreach ( $fields as $field ) {
272
-				if ( isset( $valid_shortcodes[ $field ] ) ) {
273
-					$specified_shortcodes[ $field ] = $valid_shortcodes[ $field ];
271
+			foreach ($fields as $field) {
272
+				if (isset($valid_shortcodes[$field])) {
273
+					$specified_shortcodes[$field] = $valid_shortcodes[$field];
274 274
 				}
275 275
 			}
276 276
 			$valid_shortcodes = $specified_shortcodes;
277 277
 		}
278 278
 
279 279
 		//if not merged then let's replace the fields with the localized fields
280
-		if ( ! $merged ) {
280
+		if ( ! $merged) {
281 281
 			//let's get all the fields for the set messenger so that we can get the localized label and use that in the returned array.
282 282
 			$field_settings = $messenger->get_template_fields();
283 283
 			$localized = array();
284
-			foreach ( $valid_shortcodes as $field => $shortcodes ) {
284
+			foreach ($valid_shortcodes as $field => $shortcodes) {
285 285
 				//get localized field label
286
-				if ( isset( $field_settings[ $field ] ) ) {
286
+				if (isset($field_settings[$field])) {
287 287
 					//possible that this is used as a main field.
288
-					if ( empty( $field_settings[ $field ] ) ) {
289
-						if ( isset( $field_settings['extra'][ $field ] ) ) {
290
-							$_field = $field_settings['extra'][ $field ]['main']['label'];
288
+					if (empty($field_settings[$field])) {
289
+						if (isset($field_settings['extra'][$field])) {
290
+							$_field = $field_settings['extra'][$field]['main']['label'];
291 291
 						} else {
292 292
 							$_field = $field;
293 293
 						}
294 294
 					} else {
295
-						$_field = $field_settings[ $field ]['label'];
295
+						$_field = $field_settings[$field]['label'];
296 296
 					}
297
-				} else if ( isset( $field_settings['extra'] ) ) {
297
+				} else if (isset($field_settings['extra'])) {
298 298
 					//loop through extra "main fields" and see if any of their children have our field
299
-					foreach ( $field_settings['extra'] as $main_field => $fields ) {
300
-						if ( isset( $fields[ $field ] ) ) {
301
-							$_field = $fields[ $field ]['label'];
299
+					foreach ($field_settings['extra'] as $main_field => $fields) {
300
+						if (isset($fields[$field])) {
301
+							$_field = $fields[$field]['label'];
302 302
 						} else {
303 303
 							$_field = $field;
304 304
 						}
@@ -306,22 +306,22 @@  discard block
 block discarded – undo
306 306
 				} else {
307 307
 					$_field = $field;
308 308
 				}
309
-				if ( isset( $_field ) ) {
310
-					$localized[ $_field ] = $shortcodes;
309
+				if (isset($_field)) {
310
+					$localized[$_field] = $shortcodes;
311 311
 				}
312 312
 			}
313 313
 			$valid_shortcodes = $localized;
314 314
 		}
315 315
 
316 316
 		//if $merged then let's merge all the shortcodes into one list NOT indexed by field.
317
-		if ( $merged ) {
317
+		if ($merged) {
318 318
 			$merged_codes = array();
319
-			foreach ( $valid_shortcodes as $field => $shortcode ) {
320
-				foreach ( $shortcode as $code => $label ) {
321
-					if ( isset( $merged_codes[ $code ] ) ) {
319
+			foreach ($valid_shortcodes as $field => $shortcode) {
320
+				foreach ($shortcode as $code => $label) {
321
+					if (isset($merged_codes[$code])) {
322 322
 						continue;
323 323
 					} else {
324
-						$merged_codes[ $code ] = $label;
324
+						$merged_codes[$code] = $label;
325 325
 					}
326 326
 				}
327 327
 			}
@@ -341,10 +341,10 @@  discard block
 block discarded – undo
341 341
 	 * @throws \EE_Error
342 342
 	 * @return EE_messenger
343 343
 	 */
344
-	public static function messenger_obj( $messenger ) {
344
+	public static function messenger_obj($messenger) {
345 345
 		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
346
-		$Message_Resource_Manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
347
-		return $Message_Resource_Manager->get_messenger( $messenger );
346
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
347
+		return $Message_Resource_Manager->get_messenger($messenger);
348 348
 	}
349 349
 
350 350
 
@@ -357,10 +357,10 @@  discard block
 block discarded – undo
357 357
 	 * @throws \EE_Error
358 358
 	 * @return EE_message_type
359 359
 	 */
360
-	public static function message_type_obj( $message_type ) {
360
+	public static function message_type_obj($message_type) {
361 361
 		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
362
-		$Message_Resource_Manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
363
-		return $Message_Resource_Manager->get_message_type( $message_type );
362
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
363
+		return $Message_Resource_Manager->get_message_type($message_type);
364 364
 	}
365 365
 
366 366
 
@@ -374,11 +374,11 @@  discard block
 block discarded – undo
374 374
 	 * @param  string   $message_type message type to check for.
375 375
 	 * @return boolean
376 376
 	 */
377
-	public static function is_mt_active( $message_type ) {
377
+	public static function is_mt_active($message_type) {
378 378
 		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
379
-		$Message_Resource_Manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
379
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
380 380
 		$active_mts = $Message_Resource_Manager->list_of_active_message_types();
381
-		return in_array( $message_type, $active_mts );
381
+		return in_array($message_type, $active_mts);
382 382
 	}
383 383
 
384 384
 
@@ -391,10 +391,10 @@  discard block
 block discarded – undo
391 391
 	 * @param  string  $messenger slug for messenger to check.
392 392
 	 * @return boolean
393 393
 	 */
394
-	public static function is_messenger_active( $messenger ) {
394
+	public static function is_messenger_active($messenger) {
395 395
 		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
396
-		$Message_Resource_Manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
397
-		$active_messenger = $Message_Resource_Manager->get_active_messenger( $messenger );
396
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
397
+		$active_messenger = $Message_Resource_Manager->get_active_messenger($messenger);
398 398
 		return $active_messenger instanceof EE_messenger ? true : false;
399 399
 	}
400 400
 
@@ -412,11 +412,11 @@  discard block
 block discarded – undo
412 412
 	public static function get_active_messengers_in_db() {
413 413
 		EE_Error::doing_it_wrong(
414 414
 			__METHOD__,
415
-			__( 'Please use EE_Message_Resource_Manager::get_active_messengers_option() instead.', 'event_espresso' ),
415
+			__('Please use EE_Message_Resource_Manager::get_active_messengers_option() instead.', 'event_espresso'),
416 416
 			'4.9.0'
417 417
 		);
418 418
 		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
419
-		$Message_Resource_Manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
419
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
420 420
 		return $Message_Resource_Manager->get_active_messengers_option();
421 421
 	}
422 422
 
@@ -433,15 +433,15 @@  discard block
 block discarded – undo
433 433
 	 *
434 434
 	 * @return bool FALSE if not updated, TRUE if updated.
435 435
 	 */
436
-	public static function update_active_messengers_in_db( $data_to_save ) {
436
+	public static function update_active_messengers_in_db($data_to_save) {
437 437
 		EE_Error::doing_it_wrong(
438 438
 			__METHOD__,
439
-			__( 'Please use EE_Message_Resource_Manager::update_active_messengers_option() instead.', 'event_espresso' ),
439
+			__('Please use EE_Message_Resource_Manager::update_active_messengers_option() instead.', 'event_espresso'),
440 440
 			'4.9.0'
441 441
 		);
442 442
 		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
443
-		$Message_Resource_Manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
444
-		return $Message_Resource_Manager->update_active_messengers_option( $data_to_save );
443
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
444
+		return $Message_Resource_Manager->update_active_messengers_option($data_to_save);
445 445
 	}
446 446
 
447 447
 
@@ -465,34 +465,34 @@  discard block
 block discarded – undo
465 465
 		$sending_messenger = ''
466 466
 	) {
467 467
 		//first determine if the url can be to the EE_Message object.
468
-		if ( ! $message_type->always_generate() ) {
469
-			return EEH_MSG_Template::generate_browser_trigger( $message );
468
+		if ( ! $message_type->always_generate()) {
469
+			return EEH_MSG_Template::generate_browser_trigger($message);
470 470
 		}
471 471
 
472 472
 		//if $registration object is not valid then exit early because there's nothing that can be generated.
473
-		if ( ! $registration instanceof EE_Registration ) {
473
+		if ( ! $registration instanceof EE_Registration) {
474 474
 			throw new EE_Error(
475
-				__( 'Incoming value for registration is not a valid EE_Registration object.', 'event_espresso' )
475
+				__('Incoming value for registration is not a valid EE_Registration object.', 'event_espresso')
476 476
 			);
477 477
 		}
478 478
 
479 479
 		//validate given context
480 480
 		$contexts = $message_type->get_contexts();
481
-		if ( $message->context() !== '' && ! isset( $contexts[$message->context()] ) ) {
481
+		if ($message->context() !== '' && ! isset($contexts[$message->context()])) {
482 482
 			throw new EE_Error(
483 483
 				sprintf(
484
-					__( 'The context %s is not a valid context for %s.', 'event_espresso' ),
484
+					__('The context %s is not a valid context for %s.', 'event_espresso'),
485 485
 					$message->context(),
486
-					get_class( $message_type )
486
+					get_class($message_type)
487 487
 				)
488 488
 			);
489 489
 		}
490 490
 
491 491
 		//valid sending messenger but only if sending messenger set.  Otherwise generating messenger is used.
492
-		if ( ! empty( $sending_messenger ) ) {
492
+		if ( ! empty($sending_messenger)) {
493 493
 			$with_messengers = $message_type->with_messengers();
494
-			if ( ! isset( $with_messengers[$message->messenger()] )
495
-			     || ! in_array( $sending_messenger, $with_messengers[$message->messenger()] ) ) {
494
+			if ( ! isset($with_messengers[$message->messenger()])
495
+			     || ! in_array($sending_messenger, $with_messengers[$message->messenger()])) {
496 496
 				throw new EE_Error(
497 497
 					sprintf(
498 498
 						__(
@@ -500,7 +500,7 @@  discard block
 block discarded – undo
500 500
 							'event_espresso'
501 501
 						),
502 502
 						$sending_messenger,
503
-						get_class( $message_type )
503
+						get_class($message_type)
504 504
 					)
505 505
 				);
506 506
 			}
@@ -523,14 +523,14 @@  discard block
 block discarded – undo
523 523
 	 * @param EE_Message $message
524 524
 	 * @return string.
525 525
 	 */
526
-	public static function generate_browser_trigger( EE_Message $message ) {
526
+	public static function generate_browser_trigger(EE_Message $message) {
527 527
 		$query_args = array(
528 528
 			'ee' => 'msg_browser_trigger',
529 529
 			'token' => $message->MSG_token()
530 530
 		);
531 531
 		return apply_filters(
532 532
 			'FHEE__EEH_MSG_Template__generate_browser_trigger',
533
-			add_query_arg( $query_args, site_url() ),
533
+			add_query_arg($query_args, site_url()),
534 534
 			$message
535 535
 		);
536 536
 	}
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
 	 * @param EE_Message $message
546 546
 	 * @return string
547 547
 	 */
548
-	public static function generate_error_display_trigger( EE_Message $message ) {
548
+	public static function generate_error_display_trigger(EE_Message $message) {
549 549
 		return apply_filters(
550 550
 			'FHEE__EEH_MSG_Template__generate_error_display_trigger',
551 551
 			add_query_arg(
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
 			'GRP_ID' => $message_template_group,
596 596
 			'id' => $data_id
597 597
 			);
598
-		$url = add_query_arg( $query_args, get_home_url() );
598
+		$url = add_query_arg($query_args, get_home_url());
599 599
 
600 600
 		//made it here so now we can just get the url and filter it.  Filtered globally and by message type.
601 601
 		$url = apply_filters(
@@ -623,9 +623,9 @@  discard block
 block discarded – undo
623 623
 	 * @param string $type  What action to return.
624 624
 	 * @return string
625 625
 	 */
626
-	public static function get_message_action_icon( $type ) {
626
+	public static function get_message_action_icon($type) {
627 627
 		$action_icons = self::get_message_action_icons();
628
-		return isset( $action_icons[ $type ] ) ? $action_icons[ $type ] : '';
628
+		return isset($action_icons[$type]) ? $action_icons[$type] : '';
629 629
 	}
630 630
 
631 631
 
@@ -637,34 +637,34 @@  discard block
 block discarded – undo
637 637
 	 * @return array
638 638
 	 */
639 639
 	public static function get_message_action_icons() {
640
-		return apply_filters( 'FHEE__EEH_MSG_Template__message_action_icons',
640
+		return apply_filters('FHEE__EEH_MSG_Template__message_action_icons',
641 641
 			array(
642 642
 				'view' => array(
643
-					'label' => __( 'View Message', 'event_espresso' ),
643
+					'label' => __('View Message', 'event_espresso'),
644 644
 					'css_class' => 'dashicons dashicons-welcome-view-site',
645 645
 				),
646 646
 				'error' => array(
647
-					'label' => __( 'View Error Message', 'event_espresso' ),
647
+					'label' => __('View Error Message', 'event_espresso'),
648 648
 					'css_class' => 'dashicons dashicons-info',
649 649
 				),
650 650
 				'see_notifications_for' => array(
651
-					'label' => __( 'View Related Messages', 'event_espresso' ),
651
+					'label' => __('View Related Messages', 'event_espresso'),
652 652
 					'css_class' => 'dashicons dashicons-megaphone',
653 653
 				),
654 654
 				'generate_now' => array(
655
-					'label' => __( 'Generate the message now.', 'event_espresso' ),
655
+					'label' => __('Generate the message now.', 'event_espresso'),
656 656
 					'css_class' => 'dashicons dashicons-admin-tools',
657 657
 				),
658 658
 				'send_now' => array(
659
-					'label' => __( 'Send Immediately', 'event_espresso' ),
659
+					'label' => __('Send Immediately', 'event_espresso'),
660 660
 					'css_class' => 'dashicons dashicons-controls-forward',
661 661
 				),
662 662
 				'queue_for_resending' => array(
663
-					'label' => __( 'Queue for Resending', 'event_espresso' ),
663
+					'label' => __('Queue for Resending', 'event_espresso'),
664 664
 					'css_class' => 'dashicons dashicons-controls-repeat',
665 665
 				),
666 666
 				'view_transaction' => array(
667
-					'label' => __( 'View related Transaction', 'event_espresso' ),
667
+					'label' => __('View related Transaction', 'event_espresso'),
668 668
 					'css_class' => 'dashicons dashicons-cart',
669 669
 				)
670 670
 			)
@@ -683,9 +683,9 @@  discard block
 block discarded – undo
683 683
 	 *
684 684
 	 * @return string
685 685
 	 */
686
-	public static function get_message_action_url( $type, EE_Message $message = null, $query_params = array() ) {
687
-		$action_urls = self::get_message_action_urls( $message, $query_params );
688
-		return isset( $action_urls[ $type ] )  ? $action_urls[ $type ] : '';
686
+	public static function get_message_action_url($type, EE_Message $message = null, $query_params = array()) {
687
+		$action_urls = self::get_message_action_urls($message, $query_params);
688
+		return isset($action_urls[$type]) ? $action_urls[$type] : '';
689 689
 	}
690 690
 
691 691
 
@@ -700,15 +700,15 @@  discard block
 block discarded – undo
700 700
 	 *
701 701
 	 * @return array
702 702
 	 */
703
-	public static function get_message_action_urls( EE_Message $message = null, $query_params = array() ) {
704
-		EE_Registry::instance()->load_helper( 'URL' );
703
+	public static function get_message_action_urls(EE_Message $message = null, $query_params = array()) {
704
+		EE_Registry::instance()->load_helper('URL');
705 705
 		//if $message is not an instance of EE_Message then let's just do a dummy.
706
-		$message = empty( $message ) ? EE_Message_Factory::create() : $message;
707
-		$action_urls =  apply_filters(
706
+		$message = empty($message) ? EE_Message_Factory::create() : $message;
707
+		$action_urls = apply_filters(
708 708
 			'FHEE__EEH_MSG_Template__get_message_action_url',
709 709
 			array(
710
-				'view' => EEH_MSG_Template::generate_browser_trigger( $message ),
711
-				'error' => EEH_MSG_Template::generate_error_display_trigger( $message ),
710
+				'view' => EEH_MSG_Template::generate_browser_trigger($message),
711
+				'error' => EEH_MSG_Template::generate_error_display_trigger($message),
712 712
 				'see_notifications_for' => EEH_URL::add_query_args_and_nonce(
713 713
 					array_merge(
714 714
 						array(
@@ -718,7 +718,7 @@  discard block
 block discarded – undo
718 718
 						),
719 719
 						$query_params
720 720
 					),
721
-					admin_url( 'admin.php' )
721
+					admin_url('admin.php')
722 722
 				),
723 723
 				'generate_now' => EEH_URL::add_query_args_and_nonce(
724 724
 					array(
@@ -726,7 +726,7 @@  discard block
 block discarded – undo
726 726
 						'action' => 'generate_now',
727 727
 						'MSG_ID' => $message->ID()
728 728
 					),
729
-					admin_url( 'admin.php' )
729
+					admin_url('admin.php')
730 730
 				),
731 731
 				'send_now' => EEH_URL::add_query_args_and_nonce(
732 732
 					array(
@@ -734,7 +734,7 @@  discard block
 block discarded – undo
734 734
 						'action' => 'send_now',
735 735
 						'MSG_ID' => $message->ID()
736 736
 					),
737
-					admin_url( 'admin.php' )
737
+					admin_url('admin.php')
738 738
 				),
739 739
 				'queue_for_resending' => EEH_URL::add_query_args_and_nonce(
740 740
 					array(
@@ -742,7 +742,7 @@  discard block
 block discarded – undo
742 742
 						'action' => 'queue_for_resending',
743 743
 						'MSG_ID' => $message->ID()
744 744
 					),
745
-					admin_url( 'admin.php' )
745
+					admin_url('admin.php')
746 746
 				),
747 747
 			)
748 748
 		);
@@ -760,7 +760,7 @@  discard block
 block discarded – undo
760 760
 					'action' => 'view_transaction',
761 761
 					'TXN_ID' => $message->TXN_ID()
762 762
 				),
763
-				admin_url( 'admin.php' )
763
+				admin_url('admin.php')
764 764
 			);
765 765
 		} else {
766 766
 			$action_urls['view_transaction'] = '';
@@ -781,26 +781,26 @@  discard block
 block discarded – undo
781 781
 	 *
782 782
 	 * @return string
783 783
 	 */
784
-	public static function get_message_action_link( $type, EE_Message $message = null, $query_params = array() ) {
785
-		$url = EEH_MSG_Template::get_message_action_url( $type, $message, $query_params );
786
-		$icon_css = EEH_MSG_Template::get_message_action_icon( $type );
787
-		$title = isset( $icon_css['label'] ) ? 'title="' . $icon_css['label'] . '"' : '';
784
+	public static function get_message_action_link($type, EE_Message $message = null, $query_params = array()) {
785
+		$url = EEH_MSG_Template::get_message_action_url($type, $message, $query_params);
786
+		$icon_css = EEH_MSG_Template::get_message_action_icon($type);
787
+		$title = isset($icon_css['label']) ? 'title="'.$icon_css['label'].'"' : '';
788 788
 
789
-		if ( empty( $url ) || empty( $icon_css ) || ! isset( $icon_css['css_class'] ) ) {
789
+		if (empty($url) || empty($icon_css) || ! isset($icon_css['css_class'])) {
790 790
 			return '';
791 791
 		}
792 792
 
793 793
 		$icon_css['css_class'] .= esc_attr(
794 794
 			apply_filters(
795 795
 				'FHEE__EEH_MSG_Template__get_message_action_link__icon_css_class',
796
-				' js-ee-message-action-link ee-message-action-link-' . $type,
796
+				' js-ee-message-action-link ee-message-action-link-'.$type,
797 797
 				$type,
798 798
 				$message,
799 799
 				$query_params
800 800
 			)
801 801
 		);
802 802
 
803
-		return '<a href="' . $url . '"' . $title . '><span class="' . esc_attr( $icon_css['css_class'] ) . '"></span></a>';
803
+		return '<a href="'.$url.'"'.$title.'><span class="'.esc_attr($icon_css['css_class']).'"></span></a>';
804 804
 
805 805
 	}
806 806
 
@@ -838,9 +838,9 @@  discard block
 block discarded – undo
838 838
 	 * @param $reg_status
839 839
 	 * @return string
840 840
 	 */
841
-	public static function convert_reg_status_to_message_type( $reg_status ) {
841
+	public static function convert_reg_status_to_message_type($reg_status) {
842 842
 		$reg_status_array = self::reg_status_to_message_type_array();
843
-		return isset( $reg_status_array[$reg_status] ) ? $reg_status_array[$reg_status] : '';
843
+		return isset($reg_status_array[$reg_status]) ? $reg_status_array[$reg_status] : '';
844 844
 	}
845 845
 
846 846
 
@@ -874,9 +874,9 @@  discard block
 block discarded – undo
874 874
 	 * @param $payment_status
875 875
 	 * @return string
876 876
 	 */
877
-	public static function convert_payment_status_to_message_type( $payment_status ) {
877
+	public static function convert_payment_status_to_message_type($payment_status) {
878 878
 		$payment_status_array = self::payment_status_to_message_type_array();
879
-		return isset( $payment_status_array[$payment_status] ) ? $payment_status_array[$payment_status] : '';
879
+		return isset($payment_status_array[$payment_status]) ? $payment_status_array[$payment_status] : '';
880 880
 	}
881 881
 
882 882
 
@@ -887,32 +887,32 @@  discard block
 block discarded – undo
887 887
 	 *
888 888
 	 * @return EE_Messages_Template_Pack
889 889
 	 */
890
-	public static function get_template_pack( $template_pack_name ) {
891
-		if ( ! self::$_template_pack_collection instanceof EE_Object_Collection ) {
890
+	public static function get_template_pack($template_pack_name) {
891
+		if ( ! self::$_template_pack_collection instanceof EE_Object_Collection) {
892 892
 			self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
893 893
 		}
894 894
 
895 895
 		//first see if in collection already
896
-		$template_pack = self::$_template_pack_collection->get_by_name( $template_pack_name );
896
+		$template_pack = self::$_template_pack_collection->get_by_name($template_pack_name);
897 897
 
898
-		if ( $template_pack instanceof EE_Messages_Template_Pack ) {
898
+		if ($template_pack instanceof EE_Messages_Template_Pack) {
899 899
 			return $template_pack;
900 900
 		}
901 901
 
902 902
 		//nope...let's get it.
903 903
 		//not set yet so let's attempt to get it.
904
-		$pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
904
+		$pack_class_name = 'EE_Messages_Template_Pack_'.str_replace(
905 905
 				' ',
906 906
 				'_',
907 907
 				ucwords(
908
-					str_replace( '_', ' ', $template_pack_name )
908
+					str_replace('_', ' ', $template_pack_name)
909 909
 				)
910 910
 			);
911
-		if ( ! class_exists( $pack_class_name ) && $template_pack_name !== 'default' ) {
912
-			return self::get_template_pack( 'default' );
911
+		if ( ! class_exists($pack_class_name) && $template_pack_name !== 'default') {
912
+			return self::get_template_pack('default');
913 913
 		} else {
914 914
 			$template_pack = new $pack_class_name;
915
-			self::$_template_pack_collection->add( $template_pack );
915
+			self::$_template_pack_collection->add($template_pack);
916 916
 			return $template_pack;
917 917
 		}
918 918
 	}
@@ -930,26 +930,26 @@  discard block
 block discarded – undo
930 930
 	 */
931 931
 	public static function get_template_pack_collection() {
932 932
 		$new_collection = false;
933
-		if ( ! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection ) {
933
+		if ( ! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
934 934
 			self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
935 935
 			$new_collection = true;
936 936
 		}
937 937
 
938 938
 		//glob the defaults directory for messages
939
-		$templates = glob( EE_LIBRARIES . 'messages/defaults/*', GLOB_ONLYDIR );
940
-		foreach( $templates as $template_path ) {
939
+		$templates = glob(EE_LIBRARIES.'messages/defaults/*', GLOB_ONLYDIR);
940
+		foreach ($templates as $template_path) {
941 941
 			//grab folder name
942
-			$template = basename( $template_path );
942
+			$template = basename($template_path);
943 943
 
944
-			if ( ! $new_collection ) {
944
+			if ( ! $new_collection) {
945 945
 				//already have it?
946
-				if ( self::$_template_pack_collection->get_by_name( $template ) instanceof EE_Messages_Template_Pack ) {
946
+				if (self::$_template_pack_collection->get_by_name($template) instanceof EE_Messages_Template_Pack) {
947 947
 					continue;
948 948
 				}
949 949
 			}
950 950
 
951 951
 			//setup classname.
952
-			$template_pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
952
+			$template_pack_class_name = 'EE_Messages_Template_Pack_'.str_replace(
953 953
 					' ',
954 954
 					'_',
955 955
 					ucwords(
@@ -960,20 +960,20 @@  discard block
 block discarded – undo
960 960
 						)
961 961
 					)
962 962
 				);
963
-			if ( ! class_exists( $template_pack_class_name ) ) {
963
+			if ( ! class_exists($template_pack_class_name)) {
964 964
 				continue;
965 965
 			}
966
-			self::$_template_pack_collection->add( new $template_pack_class_name );
966
+			self::$_template_pack_collection->add(new $template_pack_class_name);
967 967
 		}
968 968
 
969 969
 		/**
970 970
 		 * Filter for plugins to add in any additional template packs
971 971
 		 * Note the filter name here is for backward compat, this used to be found in EED_Messages.
972 972
 		 */
973
-		$additional_template_packs = apply_filters( 'FHEE__EED_Messages__get_template_packs__template_packs', array() );
974
-		foreach ( (array) $additional_template_packs as $template_pack ) {
975
-			if ( ! self::$_template_pack_collection->contains($template_pack ) ) {
976
-				self::$_template_pack_collection->add( $template_pack );
973
+		$additional_template_packs = apply_filters('FHEE__EED_Messages__get_template_packs__template_packs', array());
974
+		foreach ((array) $additional_template_packs as $template_pack) {
975
+			if ( ! self::$_template_pack_collection->contains($template_pack)) {
976
+				self::$_template_pack_collection->add($template_pack);
977 977
 			}
978 978
 		}
979 979
 		return self::$_template_pack_collection;
@@ -991,16 +991,16 @@  discard block
 block discarded – undo
991 991
 	 * @return array
992 992
 	 * @throws \EE_Error
993 993
 	 */
994
-	public static function create_new_templates( $messenger_name, $message_type_name, $GRP_ID = 0, $global = false ) {
994
+	public static function create_new_templates($messenger_name, $message_type_name, $GRP_ID = 0, $global = false) {
995 995
 		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
996
-		$Message_Resource_Manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
997
-		$messenger = $Message_Resource_Manager->valid_messenger( $messenger_name );
998
-		$message_type = $Message_Resource_Manager->valid_message_type( $message_type_name );
999
-		if ( ! EEH_MSG_Template::message_type_has_active_templates_for_messenger( $messenger, $message_type, $global ) ) {
996
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
997
+		$messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
998
+		$message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
999
+		if ( ! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1000 1000
 			return array();
1001 1001
 		}
1002 1002
 		//whew made it this far!  Okay, let's go ahead and create the templates then
1003
-		return EEH_MSG_Template::_create_new_templates( $messenger, $message_type, $GRP_ID, $global );
1003
+		return EEH_MSG_Template::_create_new_templates($messenger, $message_type, $GRP_ID, $global);
1004 1004
 	}
1005 1005
 
1006 1006
 
@@ -1012,15 +1012,15 @@  discard block
 block discarded – undo
1012 1012
 	 * @param                  $global
1013 1013
 	 * @return array|mixed
1014 1014
 	 */
1015
-	protected static function _create_new_templates( EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global ) {
1015
+	protected static function _create_new_templates(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global) {
1016 1016
 		//if we're creating a custom template then we don't need to use the defaults class
1017
-		if ( ! $global ) {
1018
-			return EEH_MSG_Template::_create_custom_template_group( $messenger, $message_type, $GRP_ID );
1017
+		if ( ! $global) {
1018
+			return EEH_MSG_Template::_create_custom_template_group($messenger, $message_type, $GRP_ID);
1019 1019
 		}
1020 1020
 		/** @type EE_Messages_Template_Defaults $Message_Template_Defaults */
1021 1021
 		$Message_Template_Defaults = EE_Registry::factory(
1022 1022
 			'EE_Messages_Template_Defaults',
1023
-			array( $messenger, $message_type, $GRP_ID )
1023
+			array($messenger, $message_type, $GRP_ID)
1024 1024
 		);
1025 1025
 		//generate templates
1026 1026
 		$success = $Message_Template_Defaults->create_new_templates();
@@ -1028,10 +1028,10 @@  discard block
 block discarded – undo
1028 1028
 		//if creating the template failed.  Then we should deactivate the related message_type for the messenger because
1029 1029
 		//its not active if it doesn't have a template.  Note this is only happening for GLOBAL template creation
1030 1030
 		//attempts.
1031
-		if ( ! $success ) {
1031
+		if ( ! $success) {
1032 1032
 			/** @var EE_Message_Resource_Manager $message_resource_manager */
1033
-			$message_resource_manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
1034
-			$message_resource_manager->deactivate_message_type_for_messenger( $message_type->name, $messenger->name );
1033
+			$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1034
+			$message_resource_manager->deactivate_message_type_for_messenger($message_type->name, $messenger->name);
1035 1035
 		}
1036 1036
 
1037 1037
 		/**
@@ -1059,11 +1059,11 @@  discard block
 block discarded – undo
1059 1059
 	 * 										)
1060 1060
 	 * @access private
1061 1061
 	 */
1062
-	private static function _create_custom_template_group( EE_messenger $messenger, EE_message_type $message_type, $GRP_ID ) {
1062
+	private static function _create_custom_template_group(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID) {
1063 1063
 		//defaults
1064
-		$success = array( 'GRP_ID' => null, 'MTP_context' => '' );
1064
+		$success = array('GRP_ID' => null, 'MTP_context' => '');
1065 1065
 		//get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
1066
-		$Message_Template_Group = empty( $GRP_ID )
1066
+		$Message_Template_Group = empty($GRP_ID)
1067 1067
 			? EEM_Message_Template_Group::instance()->get_one(
1068 1068
 				array(
1069 1069
 					array(
@@ -1073,9 +1073,9 @@  discard block
 block discarded – undo
1073 1073
 					)
1074 1074
 				)
1075 1075
 			)
1076
-			: EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
1076
+			: EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1077 1077
 		//if we don't have a mtg at this point then we need to bail.
1078
-		if ( ! $Message_Template_Group instanceof EE_Message_Template_Group ) {
1078
+		if ( ! $Message_Template_Group instanceof EE_Message_Template_Group) {
1079 1079
 			EE_Error::add_error(
1080 1080
 				sprintf(
1081 1081
 					__(
@@ -1094,42 +1094,42 @@  discard block
 block discarded – undo
1094 1094
 		$message_templates = $Message_Template_Group->message_templates();
1095 1095
 		//now we have what we need to setup the new template
1096 1096
 		$new_mtg = clone $Message_Template_Group;
1097
-		$new_mtg->set( 'GRP_ID', 0 );
1098
-		$new_mtg->set( 'MTP_is_global', false );
1099
-		$template_name = defined( 'DOING_AJAX' ) && ! empty( $_POST[ 'templateName' ] )
1100
-			? $_POST[ 'templateName' ]
1097
+		$new_mtg->set('GRP_ID', 0);
1098
+		$new_mtg->set('MTP_is_global', false);
1099
+		$template_name = defined('DOING_AJAX') && ! empty($_POST['templateName'])
1100
+			? $_POST['templateName']
1101 1101
 			: __(
1102 1102
 				'New Custom Template',
1103 1103
 				'event_espresso'
1104 1104
 			);
1105
-		$template_description = defined( "DOING_AJAX" ) && ! empty( $_POST[ 'templateDescription' ] )
1106
-			? $_POST[ 'templateDescription' ]
1105
+		$template_description = defined("DOING_AJAX") && ! empty($_POST['templateDescription'])
1106
+			? $_POST['templateDescription']
1107 1107
 			: sprintf(
1108 1108
 				__(
1109 1109
 					'This is a custom template that was created for the %s messenger and %s message type.',
1110 1110
 					'event_espresso'
1111 1111
 				),
1112
-				$new_mtg->messenger_obj()->label[ 'singular' ],
1113
-				$new_mtg->message_type_obj()->label[ 'singular' ]
1112
+				$new_mtg->messenger_obj()->label['singular'],
1113
+				$new_mtg->message_type_obj()->label['singular']
1114 1114
 			);
1115
-		$new_mtg->set( 'MTP_name', $template_name );
1116
-		$new_mtg->set( 'MTP_description', $template_description );
1115
+		$new_mtg->set('MTP_name', $template_name);
1116
+		$new_mtg->set('MTP_description', $template_description);
1117 1117
 		//remove ALL relations on this template group so they don't get saved!
1118
-		$new_mtg->_remove_relations( 'Message_Template' );
1118
+		$new_mtg->_remove_relations('Message_Template');
1119 1119
 		$new_mtg->save();
1120
-		$success[ 'GRP_ID' ] = $new_mtg->ID();
1121
-		$success[ 'template_name' ] = $template_name;
1120
+		$success['GRP_ID'] = $new_mtg->ID();
1121
+		$success['template_name'] = $template_name;
1122 1122
 		//add new message templates and add relation to.
1123
-		foreach ( $message_templates as $message_template ) {
1124
-			if ( ! $message_template instanceof EE_Message_Template ) {
1123
+		foreach ($message_templates as $message_template) {
1124
+			if ( ! $message_template instanceof EE_Message_Template) {
1125 1125
 				continue;
1126 1126
 			}
1127 1127
 			$new_message_template = clone $message_template;
1128
-			$new_message_template->set( 'MTP_ID', 0 );
1129
-			$new_message_template->set( 'GRP_ID', $new_mtg->ID() ); //relation
1128
+			$new_message_template->set('MTP_ID', 0);
1129
+			$new_message_template->set('GRP_ID', $new_mtg->ID()); //relation
1130 1130
 			$new_message_template->save();
1131
-			if ( empty( $success[ 'MTP_context' ] ) ) {
1132
-				$success[ 'MTP_context' ] = $new_message_template->get( 'MTP_context' );
1131
+			if (empty($success['MTP_context'])) {
1132
+				$success['MTP_context'] = $new_message_template->get('MTP_context');
1133 1133
 			}
1134 1134
 		}
1135 1135
 		return $success;
@@ -1151,7 +1151,7 @@  discard block
 block discarded – undo
1151 1151
 		$global = false
1152 1152
 	) {
1153 1153
 		//is given message_type valid for given messenger (if this is not a global save)
1154
-		if ( $global ) {
1154
+		if ($global) {
1155 1155
 			return true;
1156 1156
 		}
1157 1157
 		$active_templates = EEM_Message_Template_Group::instance()->count(
@@ -1163,7 +1163,7 @@  discard block
 block discarded – undo
1163 1163
 				)
1164 1164
 			)
1165 1165
 		);
1166
-		if ( $active_templates > 0 ) {
1166
+		if ($active_templates > 0) {
1167 1167
 			return true;
1168 1168
 		}
1169 1169
 		EE_Error::add_error(
@@ -1192,30 +1192,30 @@  discard block
 block discarded – undo
1192 1192
 	 * @param  string $message_type_name name of EE_message_type
1193 1193
 	 * @return array
1194 1194
 	 */
1195
-	public static function get_fields( $messenger_name, $message_type_name ) {
1195
+	public static function get_fields($messenger_name, $message_type_name) {
1196 1196
 		$template_fields = array();
1197 1197
 		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1198
-		$Message_Resource_Manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
1199
-		$messenger = $Message_Resource_Manager->valid_messenger( $messenger_name );
1200
-		$message_type = $Message_Resource_Manager->valid_message_type( $message_type_name );
1201
-		if ( ! EEH_MSG_Template::message_type_has_active_templates_for_messenger( $messenger, $message_type ) ) {
1198
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1199
+		$messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1200
+		$message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1201
+		if ( ! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1202 1202
 			return array();
1203 1203
 		}
1204 1204
 
1205 1205
         $excluded_fields_for_messenger = $message_type->excludedFieldsForMessenger($messenger_name);
1206 1206
 
1207 1207
 		//okay now let's assemble an array with the messenger template fields added to the message_type contexts.
1208
-		foreach ( $message_type->get_contexts() as $context => $details ) {
1209
-			foreach ( $messenger->get_template_fields() as $field => $value ) {
1208
+		foreach ($message_type->get_contexts() as $context => $details) {
1209
+			foreach ($messenger->get_template_fields() as $field => $value) {
1210 1210
 			    if (in_array($field, $excluded_fields_for_messenger, true)) {
1211 1211
 			        continue;
1212 1212
                 }
1213
-				$template_fields[ $context ][ $field ] = $value;
1213
+				$template_fields[$context][$field] = $value;
1214 1214
 			}
1215 1215
 		}
1216
-		if ( empty( $template_fields ) ) {
1216
+		if (empty($template_fields)) {
1217 1217
 			EE_Error::add_error(
1218
-				__( 'Something went wrong and we couldn\'t get any templates assembled', 'event_espresso' ),
1218
+				__('Something went wrong and we couldn\'t get any templates assembled', 'event_espresso'),
1219 1219
 				__FILE__,
1220 1220
 				__FUNCTION__,
1221 1221
 				__LINE__
Please login to merge, or discard this patch.
message_type/newsletter/EE_Messages_Email_Newsletter_Validator.class.php 1 patch
Indentation   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -13,72 +13,72 @@
 block discarded – undo
13 13
  */
14 14
 class EE_Messages_Email_Newsletter_Validator extends EE_Messages_Validator
15 15
 {
16
-    /**
17
-     * EE_Messages_Email_Newsletter_Validator constructor.
18
-     *
19
-     * @param array $fields
20
-     * @param string $context
21
-     * @throws EE_Error
22
-     * @throws ReflectionException
23
-     */
24
-    public function __construct(array $fields, $context)
25
-    {
26
-        $this->_m_name = 'email';
27
-        $this->_mt_name = 'newsletter';
16
+	/**
17
+	 * EE_Messages_Email_Newsletter_Validator constructor.
18
+	 *
19
+	 * @param array $fields
20
+	 * @param string $context
21
+	 * @throws EE_Error
22
+	 * @throws ReflectionException
23
+	 */
24
+	public function __construct(array $fields, $context)
25
+	{
26
+		$this->_m_name = 'email';
27
+		$this->_mt_name = 'newsletter';
28 28
 
29
-        parent::__construct($fields, $context);
30
-    }
29
+		parent::__construct($fields, $context);
30
+	}
31 31
 
32
-    /**
33
-     * custom validator (restricting what was originally set by the messenger)
34
-     */
35
-    protected function _modify_validator()
36
-    {
37
-        if ($this->_context === 'attendee') {
38
-            $this->_valid_shortcodes_modifier[$this->_context]['from'] = array(
39
-                'recipient_details',
40
-                'email',
41
-                'organization',
42
-            );
43
-        }
32
+	/**
33
+	 * custom validator (restricting what was originally set by the messenger)
34
+	 */
35
+	protected function _modify_validator()
36
+	{
37
+		if ($this->_context === 'attendee') {
38
+			$this->_valid_shortcodes_modifier[$this->_context]['from'] = array(
39
+				'recipient_details',
40
+				'email',
41
+				'organization',
42
+			);
43
+		}
44 44
 
45
-        //excluded shortcodes
46
-        $fields = array('to', 'from', 'subject', 'content', 'newsletter_content');
47
-        foreach ($fields as $field) {
48
-            $this->_specific_shortcode_excludes[$field] = array(
49
-                '[RECIPIENT_REGISTRATION_CODE]',
50
-                '[EVENT_AUTHOR_FORMATTED_EMAIL]',
51
-                '[EVENT_AUTHOR_EMAIL]',
52
-            );
53
-        }
54
-        $add_excludes = array(
55
-            '[RECIPIENT_FNAME]',
56
-            '[RECIPIENT_LNAME]',
57
-            '[RECIPIENT_EMAIL]',
58
-            '[COMPANY]',
59
-            '[CO_ADD1]',
60
-            '[CO_ADD2]',
61
-            '[CO_CITY]',
62
-            '[CO_STATE]',
63
-            '[CO_ZIP]',
64
-            '[CO_LOGO]',
65
-            '[CO_PHONE]',
66
-            '[CO_LOGO_URL]',
67
-            '[CO_FACEBOOK_URL]',
68
-            '[CO_TWITTER_URL]',
69
-            '[CO_PINTEREST_URL]',
70
-            '[CO_GOOGLE_URL]',
71
-            '[CO_LINKEDIN_URL]',
72
-            '[CO_INSTAGRAM_URL]',
73
-        );
74
-        $this->_specific_shortcode_excludes['from'] =
75
-            array_merge(
76
-                $this->_specific_shortcode_excludes['from'],
77
-                $add_excludes
78
-            );
79
-        $this->_specific_shortcode_excludes['content'] = array_merge(
80
-            $this->_specific_shortcode_excludes['content'],
81
-            array('[DISPLAY_PDF_URL]', '[DISPLAY_PDF_BUTTON]')
82
-        );
83
-    }
45
+		//excluded shortcodes
46
+		$fields = array('to', 'from', 'subject', 'content', 'newsletter_content');
47
+		foreach ($fields as $field) {
48
+			$this->_specific_shortcode_excludes[$field] = array(
49
+				'[RECIPIENT_REGISTRATION_CODE]',
50
+				'[EVENT_AUTHOR_FORMATTED_EMAIL]',
51
+				'[EVENT_AUTHOR_EMAIL]',
52
+			);
53
+		}
54
+		$add_excludes = array(
55
+			'[RECIPIENT_FNAME]',
56
+			'[RECIPIENT_LNAME]',
57
+			'[RECIPIENT_EMAIL]',
58
+			'[COMPANY]',
59
+			'[CO_ADD1]',
60
+			'[CO_ADD2]',
61
+			'[CO_CITY]',
62
+			'[CO_STATE]',
63
+			'[CO_ZIP]',
64
+			'[CO_LOGO]',
65
+			'[CO_PHONE]',
66
+			'[CO_LOGO_URL]',
67
+			'[CO_FACEBOOK_URL]',
68
+			'[CO_TWITTER_URL]',
69
+			'[CO_PINTEREST_URL]',
70
+			'[CO_GOOGLE_URL]',
71
+			'[CO_LINKEDIN_URL]',
72
+			'[CO_INSTAGRAM_URL]',
73
+		);
74
+		$this->_specific_shortcode_excludes['from'] =
75
+			array_merge(
76
+				$this->_specific_shortcode_excludes['from'],
77
+				$add_excludes
78
+			);
79
+		$this->_specific_shortcode_excludes['content'] = array_merge(
80
+			$this->_specific_shortcode_excludes['content'],
81
+			array('[DISPLAY_PDF_URL]', '[DISPLAY_PDF_BUTTON]')
82
+		);
83
+	}
84 84
 }
Please login to merge, or discard this patch.
messages/message_type/newsletter/EE_Newsletter_message_type.class.php 2 patches
Indentation   +190 added lines, -190 removed lines patch added patch discarded remove patch
@@ -14,196 +14,196 @@
 block discarded – undo
14 14
 class EE_Newsletter_message_type extends EE_message_type
15 15
 {
16 16
 
17
-    public function __construct()
18
-    {
19
-        $this->name = 'newsletter';
20
-        $this->description = esc_html__(
21
-            'Batch message type messages are triggered manually by the admin for sending notifications to a selected group of recipients. This should only be used for more general notification type messages that contain information specific for the recipients. For "newsletter" type messages we recommend using an email list service like MailChimp, because sending non-related mail-outs to contacts increases the risk of your site domain getting added to spam lists, which will prevent messages getting to users.',
22
-            'event_espresso'
23
-        );
24
-        $this->label = array(
25
-            'singular' => esc_html__('batch', 'event_espresso'),
26
-            'plural'   => esc_html__('batches', 'event_espresso'),
27
-        );
28
-        $this->_master_templates = array(
29
-            'email' => 'registration',
30
-        );
31
-
32
-        parent::__construct();
33
-    }
34
-
35
-
36
-    /**
37
-     * Sets admin_registered_pages property
38
-     */
39
-    protected function _set_admin_pages()
40
-    {
41
-        $this->admin_registered_pages = array(); //no admin pages to register this with.
42
-    }
43
-
44
-
45
-    /**
46
-     * Sets property related to data handler.
47
-     */
48
-    protected function _set_data_handler()
49
-    {
50
-        $this->_data_handler = 'Registrations';
51
-        $this->_single_message = $this->_data instanceof EE_Registration;
52
-    }
53
-
54
-
55
-    /**
56
-     * Returns the data for the given context for this message type.
57
-     * @param string          $context
58
-     * @param EE_Registration $registration
59
-     * @param int             $id
60
-     * @return array|mixed
61
-     */
62
-    protected function _get_data_for_context($context, EE_Registration $registration, $id)
63
-    {
64
-        //newsletter message type data handler is 'Registrations' and it expects an array of EE_Registration objects.
65
-        return array($registration);
66
-    }
67
-
68
-
69
-    /**
70
-     * Sets the admin settings fields property for this message type.
71
-     */
72
-    protected function _set_admin_settings_fields()
73
-    {
74
-        $this->_admin_settings_fields = array();
75
-    }
76
-
77
-
78
-    /**
79
-     * Sets the contexts for this message type.
80
-     */
81
-    protected function _set_contexts()
82
-    {
83
-        $this->_context_label = array(
84
-            'label'       => esc_html__('recipient', 'event_espresso'),
85
-            'plural'      => esc_html__('recipients', 'event_espresso'),
86
-            'description' => esc_html__('Recipient\'s are who will receive the message.', 'event_espresso'),
87
-        );
88
-
89
-        $this->_contexts = array(
90
-            'attendee' => array(
91
-                'label'       => esc_html__('Registrant', 'event_espresso'),
92
-                'description' => esc_html__('This template goes to selected registrants.', 'event_espresso'),
93
-            ),
94
-        );
95
-    }
96
-
97
-
98
-    /**
99
-     * used to set the valid shortcodes.
100
-     * For the newsletter message type we only have two valid shortcode libraries in use, recipient details and
101
-     * organization.  That's it!
102
-     *
103
-     * @since   4.3.0
104
-     * @return  void
105
-     */
106
-    protected function _set_valid_shortcodes()
107
-    {
108
-        parent::_set_valid_shortcodes();
109
-
110
-        $included_shortcodes = array(
111
-            'recipient_details',
112
-            'organization',
113
-            'newsletter',
114
-        );
115
-
116
-        foreach ($this->_valid_shortcodes as $context => $shortcodes) {
117
-            foreach ($shortcodes as $key => $shortcode) {
118
-                if (! in_array($shortcode, $included_shortcodes, true)) {
119
-                    unset($this->_valid_shortcodes[$context][$key]);
120
-                }
121
-            }
122
-            $this->_valid_shortcodes[$context][] = 'newsletter';
123
-        }
124
-    }
125
-
126
-
127
-    /**
128
-     * Override default _attendee_addressees in EE_message_type because we want to loop through the registrations
129
-     * for EE_message_type.
130
-     *
131
-     * @return array
132
-     * @throws EE_Error
133
-     * @throws InvalidArgumentException
134
-     * @throws ReflectionException
135
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
136
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
137
-     */
138
-    protected function _attendee_addressees()
139
-    {
140
-        $addressee = array();
141
-
142
-        //looping through registrations
143
-        foreach ($this->_data->registrations as $reg_id => $details) {
144
-            //set $attendee array to blank on each loop
145
-            $aee = array();
146
-
147
-            //need to get the attendee from this registration.
148
-            $attendee = isset($details['att_obj']) && $details['att_obj'] instanceof EE_Attendee
149
-                ? $details['att_obj']
150
-                : null;
151
-
152
-            if (! $attendee instanceof EE_Attendee) {
153
-                continue;
154
-            }
155
-
156
-            //set $aee from attendee object
157
-            $aee['att_obj'] = $attendee;
158
-            $aee['reg_objs'] = isset($this->_data->attendees[$attendee->ID()]['reg_objs'])
159
-                ? $this->_data->attendees[$attendee->ID()]['reg_objs']
160
-                : array();
161
-            $aee['attendee_email'] = $attendee->email();
162
-            $aee['tkt_objs'] = isset($this->_data->attendees[$attendee->ID()]['tkt_objs'])
163
-                ? $this->_data->attendees[$attendee->ID()]['tkt_objs']
164
-                : array();
165
-
166
-            if (isset($this->_data->attendees[$attendee->ID()]['evt_objs'])) {
167
-                $aee['evt_objs'] = $this->_data->attendees[$attendee->ID()]['evt_objs'];
168
-                $aee['events'] = $this->_data->attendees[$attendee->ID()]['evt_objs'];
169
-            } else {
170
-                $aee['evt_objs'] = $aee['events'] = array();
171
-            }
172
-
173
-            $aee['reg_obj'] = isset($details['reg_obj'])
174
-                ? $details['reg_obj']
175
-                : null;
176
-            $aee['attendees'] = $this->_data->attendees;
177
-
178
-            //merge in the primary attendee data
179
-            $aee = array_merge($this->_default_addressee_data, $aee);
180
-
181
-            //make sure txn is set
182
-            if (empty($aee['txn']) && $aee['reg_obj'] instanceof EE_Registration) {
183
-                $aee['txn'] = $aee['reg_obj']->transaction();
184
-            }
185
-
186
-            $addressee[] = new EE_Messages_Addressee($aee);
187
-        }
188
-        return $addressee;
189
-    }
190
-
191
-    /**
192
-     * Allows a message type to specifically exclude template fields for the provided messenger.
193
-     * Filtered so this can be programmatically altered as well.
194
-     *
195
-     * @param string $messenger_name name of messenger
196
-     * @return array
197
-     */
198
-    public function excludedFieldsForMessenger($messenger_name)
199
-    {
200
-        $excluded_fields = array(
201
-            'email' => array('cc')
202
-        );
203
-        return isset($excluded_fields[$messenger_name])
204
-            ? $excluded_fields[$messenger_name]
205
-            : parent::excludedFieldsForMessenger($messenger_name);
206
-    }
17
+	public function __construct()
18
+	{
19
+		$this->name = 'newsletter';
20
+		$this->description = esc_html__(
21
+			'Batch message type messages are triggered manually by the admin for sending notifications to a selected group of recipients. This should only be used for more general notification type messages that contain information specific for the recipients. For "newsletter" type messages we recommend using an email list service like MailChimp, because sending non-related mail-outs to contacts increases the risk of your site domain getting added to spam lists, which will prevent messages getting to users.',
22
+			'event_espresso'
23
+		);
24
+		$this->label = array(
25
+			'singular' => esc_html__('batch', 'event_espresso'),
26
+			'plural'   => esc_html__('batches', 'event_espresso'),
27
+		);
28
+		$this->_master_templates = array(
29
+			'email' => 'registration',
30
+		);
31
+
32
+		parent::__construct();
33
+	}
34
+
35
+
36
+	/**
37
+	 * Sets admin_registered_pages property
38
+	 */
39
+	protected function _set_admin_pages()
40
+	{
41
+		$this->admin_registered_pages = array(); //no admin pages to register this with.
42
+	}
43
+
44
+
45
+	/**
46
+	 * Sets property related to data handler.
47
+	 */
48
+	protected function _set_data_handler()
49
+	{
50
+		$this->_data_handler = 'Registrations';
51
+		$this->_single_message = $this->_data instanceof EE_Registration;
52
+	}
53
+
54
+
55
+	/**
56
+	 * Returns the data for the given context for this message type.
57
+	 * @param string          $context
58
+	 * @param EE_Registration $registration
59
+	 * @param int             $id
60
+	 * @return array|mixed
61
+	 */
62
+	protected function _get_data_for_context($context, EE_Registration $registration, $id)
63
+	{
64
+		//newsletter message type data handler is 'Registrations' and it expects an array of EE_Registration objects.
65
+		return array($registration);
66
+	}
67
+
68
+
69
+	/**
70
+	 * Sets the admin settings fields property for this message type.
71
+	 */
72
+	protected function _set_admin_settings_fields()
73
+	{
74
+		$this->_admin_settings_fields = array();
75
+	}
76
+
77
+
78
+	/**
79
+	 * Sets the contexts for this message type.
80
+	 */
81
+	protected function _set_contexts()
82
+	{
83
+		$this->_context_label = array(
84
+			'label'       => esc_html__('recipient', 'event_espresso'),
85
+			'plural'      => esc_html__('recipients', 'event_espresso'),
86
+			'description' => esc_html__('Recipient\'s are who will receive the message.', 'event_espresso'),
87
+		);
88
+
89
+		$this->_contexts = array(
90
+			'attendee' => array(
91
+				'label'       => esc_html__('Registrant', 'event_espresso'),
92
+				'description' => esc_html__('This template goes to selected registrants.', 'event_espresso'),
93
+			),
94
+		);
95
+	}
96
+
97
+
98
+	/**
99
+	 * used to set the valid shortcodes.
100
+	 * For the newsletter message type we only have two valid shortcode libraries in use, recipient details and
101
+	 * organization.  That's it!
102
+	 *
103
+	 * @since   4.3.0
104
+	 * @return  void
105
+	 */
106
+	protected function _set_valid_shortcodes()
107
+	{
108
+		parent::_set_valid_shortcodes();
109
+
110
+		$included_shortcodes = array(
111
+			'recipient_details',
112
+			'organization',
113
+			'newsletter',
114
+		);
115
+
116
+		foreach ($this->_valid_shortcodes as $context => $shortcodes) {
117
+			foreach ($shortcodes as $key => $shortcode) {
118
+				if (! in_array($shortcode, $included_shortcodes, true)) {
119
+					unset($this->_valid_shortcodes[$context][$key]);
120
+				}
121
+			}
122
+			$this->_valid_shortcodes[$context][] = 'newsletter';
123
+		}
124
+	}
125
+
126
+
127
+	/**
128
+	 * Override default _attendee_addressees in EE_message_type because we want to loop through the registrations
129
+	 * for EE_message_type.
130
+	 *
131
+	 * @return array
132
+	 * @throws EE_Error
133
+	 * @throws InvalidArgumentException
134
+	 * @throws ReflectionException
135
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
136
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
137
+	 */
138
+	protected function _attendee_addressees()
139
+	{
140
+		$addressee = array();
141
+
142
+		//looping through registrations
143
+		foreach ($this->_data->registrations as $reg_id => $details) {
144
+			//set $attendee array to blank on each loop
145
+			$aee = array();
146
+
147
+			//need to get the attendee from this registration.
148
+			$attendee = isset($details['att_obj']) && $details['att_obj'] instanceof EE_Attendee
149
+				? $details['att_obj']
150
+				: null;
151
+
152
+			if (! $attendee instanceof EE_Attendee) {
153
+				continue;
154
+			}
155
+
156
+			//set $aee from attendee object
157
+			$aee['att_obj'] = $attendee;
158
+			$aee['reg_objs'] = isset($this->_data->attendees[$attendee->ID()]['reg_objs'])
159
+				? $this->_data->attendees[$attendee->ID()]['reg_objs']
160
+				: array();
161
+			$aee['attendee_email'] = $attendee->email();
162
+			$aee['tkt_objs'] = isset($this->_data->attendees[$attendee->ID()]['tkt_objs'])
163
+				? $this->_data->attendees[$attendee->ID()]['tkt_objs']
164
+				: array();
165
+
166
+			if (isset($this->_data->attendees[$attendee->ID()]['evt_objs'])) {
167
+				$aee['evt_objs'] = $this->_data->attendees[$attendee->ID()]['evt_objs'];
168
+				$aee['events'] = $this->_data->attendees[$attendee->ID()]['evt_objs'];
169
+			} else {
170
+				$aee['evt_objs'] = $aee['events'] = array();
171
+			}
172
+
173
+			$aee['reg_obj'] = isset($details['reg_obj'])
174
+				? $details['reg_obj']
175
+				: null;
176
+			$aee['attendees'] = $this->_data->attendees;
177
+
178
+			//merge in the primary attendee data
179
+			$aee = array_merge($this->_default_addressee_data, $aee);
180
+
181
+			//make sure txn is set
182
+			if (empty($aee['txn']) && $aee['reg_obj'] instanceof EE_Registration) {
183
+				$aee['txn'] = $aee['reg_obj']->transaction();
184
+			}
185
+
186
+			$addressee[] = new EE_Messages_Addressee($aee);
187
+		}
188
+		return $addressee;
189
+	}
190
+
191
+	/**
192
+	 * Allows a message type to specifically exclude template fields for the provided messenger.
193
+	 * Filtered so this can be programmatically altered as well.
194
+	 *
195
+	 * @param string $messenger_name name of messenger
196
+	 * @return array
197
+	 */
198
+	public function excludedFieldsForMessenger($messenger_name)
199
+	{
200
+		$excluded_fields = array(
201
+			'email' => array('cc')
202
+		);
203
+		return isset($excluded_fields[$messenger_name])
204
+			? $excluded_fields[$messenger_name]
205
+			: parent::excludedFieldsForMessenger($messenger_name);
206
+	}
207 207
 
208 208
 
209 209
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
 
116 116
         foreach ($this->_valid_shortcodes as $context => $shortcodes) {
117 117
             foreach ($shortcodes as $key => $shortcode) {
118
-                if (! in_array($shortcode, $included_shortcodes, true)) {
118
+                if ( ! in_array($shortcode, $included_shortcodes, true)) {
119 119
                     unset($this->_valid_shortcodes[$context][$key]);
120 120
                 }
121 121
             }
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
                 ? $details['att_obj']
150 150
                 : null;
151 151
 
152
-            if (! $attendee instanceof EE_Attendee) {
152
+            if ( ! $attendee instanceof EE_Attendee) {
153 153
                 continue;
154 154
             }
155 155
 
Please login to merge, or discard this patch.
admin_pages/transactions/EE_Admin_Transactions_List_Table.class.php 1 patch
Indentation   +630 added lines, -630 removed lines patch added patch discarded remove patch
@@ -17,121 +17,121 @@  discard block
 block discarded – undo
17 17
 class EE_Admin_Transactions_List_Table extends EE_Admin_List_Table
18 18
 {
19 19
 
20
-    /**
21
-     * @var SessionLifespan $session_lifespan
22
-     */
23
-    private $session_lifespan;
24
-
25
-    private $_status;
26
-
27
-
28
-    /**
29
-     * @param \Transactions_Admin_Page $admin_page
30
-     * @param SessionLifespan          $lifespan
31
-     */
32
-    public function __construct(\Transactions_Admin_Page $admin_page, SessionLifespan $lifespan)
33
-    {
34
-        parent::__construct($admin_page);
35
-        $this->session_lifespan = $lifespan;
36
-        $this->_status = $this->_admin_page->get_transaction_status_array();
37
-    }
38
-
39
-
40
-    /**
41
-     *_setup_data
42
-     */
43
-    protected function _setup_data()
44
-    {
45
-        $this->_data           = $this->_admin_page->get_transactions($this->_per_page);
46
-        $status                = ! empty($this->_req_data['status']) ? $this->_req_data['status'] : 'all';
47
-        $this->_all_data_count = $this->_admin_page->get_transactions($this->_per_page, true, $status);
48
-    }
49
-
50
-
51
-    /**
52
-     *_set_properties
53
-     */
54
-    protected function _set_properties()
55
-    {
56
-        $this->_wp_list_args = array(
57
-            'singular' => __('transaction', 'event_espresso'),
58
-            'plural'   => __('transactions', 'event_espresso'),
59
-            'ajax'     => true,
60
-            'screen'   => $this->_admin_page->get_current_screen()->id,
61
-        );
62
-        $ID_column_name      = __('ID', 'event_espresso');
63
-        $ID_column_name      .= ' : <span class="show-on-mobile-view-only" style="float:none">';
64
-        $ID_column_name      .= __('Transaction Date', 'event_espresso');
65
-        $ID_column_name      .= '</span> ';
66
-        $this->_columns      = array(
67
-            'TXN_ID'        => $ID_column_name,
68
-            'TXN_timestamp' => __('Transaction Date', 'event_espresso'),
69
-            'TXN_total'     => __('Total', 'event_espresso'),
70
-            'TXN_paid'      => __('Paid', 'event_espresso'),
71
-            'ATT_fname'     => __('Primary Registrant', 'event_espresso'),
72
-            'event_name'    => __('Event', 'event_espresso'),
73
-            'actions'       => __('Actions', 'event_espresso'),
74
-        );
75
-
76
-        $this->_sortable_columns = array(
77
-            'TXN_ID'        => array('TXN_ID' => false),
78
-            'event_name'    => array('event_name' => false),
79
-            'ATT_fname'     => array('ATT_fname' => false),
80
-            'TXN_timestamp' => array('TXN_timestamp' => true) //true means its already sorted
81
-        );
82
-
83
-        $this->_primary_column = 'TXN_ID';
84
-
85
-        $this->_hidden_columns = array();
86
-    }
87
-
88
-
89
-    /**
90
-     * This simply sets up the row class for the table rows.
91
-     * Allows for easier overriding of child methods for setting up sorting.
92
-     *
93
-     * @param  EE_Transaction $transaction the current item
94
-     * @return string
95
-     * @throws \EE_Error
96
-     */
97
-    protected function _get_row_class($transaction)
98
-    {
99
-        $class = parent::_get_row_class($transaction);
100
-        //add status class
101
-        $class .= ' ee-status-strip txn-status-' . $transaction->status_ID();
102
-        if ($this->_has_checkbox_column) {
103
-            $class .= ' has-checkbox-column';
104
-        }
105
-        return $class;
106
-    }
107
-
108
-
109
-    /**
110
-     * _get_table_filters
111
-     * We use this to assemble and return any filters that are associated with this table that help further refine what
112
-     * get's shown in the table.
113
-     *
114
-     * @abstract
115
-     * @access protected
116
-     * @return array
117
-     */
118
-    protected function _get_table_filters()
119
-    {
120
-        $filters    = array();
121
-        $start_date = isset($this->_req_data['txn-filter-start-date'])
122
-            ? wp_strip_all_tags($this->_req_data['txn-filter-start-date'])
123
-            : date(
124
-                'm/d/Y',
125
-                strtotime('-10 year')
126
-            );
127
-        $end_date   = isset($this->_req_data['txn-filter-end-date'])
128
-            ? wp_strip_all_tags($this->_req_data['txn-filter-end-date'])
129
-            : date(
130
-                'm/d/Y',
131
-                current_time('timestamp')
132
-            );
133
-        ob_start();
134
-        ?>
20
+	/**
21
+	 * @var SessionLifespan $session_lifespan
22
+	 */
23
+	private $session_lifespan;
24
+
25
+	private $_status;
26
+
27
+
28
+	/**
29
+	 * @param \Transactions_Admin_Page $admin_page
30
+	 * @param SessionLifespan          $lifespan
31
+	 */
32
+	public function __construct(\Transactions_Admin_Page $admin_page, SessionLifespan $lifespan)
33
+	{
34
+		parent::__construct($admin_page);
35
+		$this->session_lifespan = $lifespan;
36
+		$this->_status = $this->_admin_page->get_transaction_status_array();
37
+	}
38
+
39
+
40
+	/**
41
+	 *_setup_data
42
+	 */
43
+	protected function _setup_data()
44
+	{
45
+		$this->_data           = $this->_admin_page->get_transactions($this->_per_page);
46
+		$status                = ! empty($this->_req_data['status']) ? $this->_req_data['status'] : 'all';
47
+		$this->_all_data_count = $this->_admin_page->get_transactions($this->_per_page, true, $status);
48
+	}
49
+
50
+
51
+	/**
52
+	 *_set_properties
53
+	 */
54
+	protected function _set_properties()
55
+	{
56
+		$this->_wp_list_args = array(
57
+			'singular' => __('transaction', 'event_espresso'),
58
+			'plural'   => __('transactions', 'event_espresso'),
59
+			'ajax'     => true,
60
+			'screen'   => $this->_admin_page->get_current_screen()->id,
61
+		);
62
+		$ID_column_name      = __('ID', 'event_espresso');
63
+		$ID_column_name      .= ' : <span class="show-on-mobile-view-only" style="float:none">';
64
+		$ID_column_name      .= __('Transaction Date', 'event_espresso');
65
+		$ID_column_name      .= '</span> ';
66
+		$this->_columns      = array(
67
+			'TXN_ID'        => $ID_column_name,
68
+			'TXN_timestamp' => __('Transaction Date', 'event_espresso'),
69
+			'TXN_total'     => __('Total', 'event_espresso'),
70
+			'TXN_paid'      => __('Paid', 'event_espresso'),
71
+			'ATT_fname'     => __('Primary Registrant', 'event_espresso'),
72
+			'event_name'    => __('Event', 'event_espresso'),
73
+			'actions'       => __('Actions', 'event_espresso'),
74
+		);
75
+
76
+		$this->_sortable_columns = array(
77
+			'TXN_ID'        => array('TXN_ID' => false),
78
+			'event_name'    => array('event_name' => false),
79
+			'ATT_fname'     => array('ATT_fname' => false),
80
+			'TXN_timestamp' => array('TXN_timestamp' => true) //true means its already sorted
81
+		);
82
+
83
+		$this->_primary_column = 'TXN_ID';
84
+
85
+		$this->_hidden_columns = array();
86
+	}
87
+
88
+
89
+	/**
90
+	 * This simply sets up the row class for the table rows.
91
+	 * Allows for easier overriding of child methods for setting up sorting.
92
+	 *
93
+	 * @param  EE_Transaction $transaction the current item
94
+	 * @return string
95
+	 * @throws \EE_Error
96
+	 */
97
+	protected function _get_row_class($transaction)
98
+	{
99
+		$class = parent::_get_row_class($transaction);
100
+		//add status class
101
+		$class .= ' ee-status-strip txn-status-' . $transaction->status_ID();
102
+		if ($this->_has_checkbox_column) {
103
+			$class .= ' has-checkbox-column';
104
+		}
105
+		return $class;
106
+	}
107
+
108
+
109
+	/**
110
+	 * _get_table_filters
111
+	 * We use this to assemble and return any filters that are associated with this table that help further refine what
112
+	 * get's shown in the table.
113
+	 *
114
+	 * @abstract
115
+	 * @access protected
116
+	 * @return array
117
+	 */
118
+	protected function _get_table_filters()
119
+	{
120
+		$filters    = array();
121
+		$start_date = isset($this->_req_data['txn-filter-start-date'])
122
+			? wp_strip_all_tags($this->_req_data['txn-filter-start-date'])
123
+			: date(
124
+				'm/d/Y',
125
+				strtotime('-10 year')
126
+			);
127
+		$end_date   = isset($this->_req_data['txn-filter-end-date'])
128
+			? wp_strip_all_tags($this->_req_data['txn-filter-end-date'])
129
+			: date(
130
+				'm/d/Y',
131
+				current_time('timestamp')
132
+			);
133
+		ob_start();
134
+		?>
135 135
         <label for="txn-filter-start-date">Display Transactions from </label>
136 136
         <input id="txn-filter-start-date" class="datepicker" type="text" value="<?php echo $start_date; ?>"
137 137
                name="txn-filter-start-date" size="15"/>
@@ -139,551 +139,551 @@  discard block
 block discarded – undo
139 139
         <input id="txn-filter-end-date" class="datepicker" type="text" value="<?php echo $end_date; ?>"
140 140
                name="txn-filter-end-date" size="15"/>
141 141
         <?php
142
-        $filters[] = ob_get_contents();
143
-        ob_end_clean();
144
-        return $filters;
145
-    }
146
-
147
-
148
-    /**
149
-     *_add_view_counts
150
-     */
151
-    protected function _add_view_counts()
152
-    {
153
-        $this->_views['all']['count']       = $this->_admin_page->get_transactions($this->_per_page, true, 'all');
154
-        $this->_views['abandoned']['count'] = $this->_admin_page->get_transactions($this->_per_page, true, 'abandoned');
155
-        $this->_views['failed']['count']    = $this->_admin_page->get_transactions($this->_per_page, true, 'failed');
156
-    }
157
-
158
-
159
-    /**
160
-     *    column TXN_ID
161
-     *
162
-     * @param \EE_Transaction $transaction
163
-     * @return string
164
-     * @throws \EE_Error
165
-     */
166
-    public function column_TXN_ID(EE_Transaction $transaction)
167
-    {
168
-        $view_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
169
-            'action' => 'view_transaction',
170
-            'TXN_ID' => $transaction->ID(),
171
-        ), TXN_ADMIN_URL);
172
-        $content      = '<a href="' . $view_lnk_url . '"'
173
-                        . ' title="' . esc_attr__('Go to Transaction Details', 'event_espresso') . '">'
174
-                        . $transaction->ID()
175
-                        . '</a>';
176
-
177
-        //txn timestamp
178
-        $content .= '  <span class="show-on-mobile-view-only">' . $this->_get_txn_timestamp($transaction) . '</span>';
179
-        return $content;
180
-    }
181
-
182
-
183
-    /**
184
-     * @param \EE_Transaction $transaction
185
-     * @return string
186
-     * @throws EE_Error
187
-     * @throws InvalidArgumentException
188
-     * @throws InvalidDataTypeException
189
-     * @throws InvalidInterfaceException
190
-     */
191
-    protected function _get_txn_timestamp(EE_Transaction $transaction)
192
-    {
193
-        // is TXN less than 2 hours old ?
194
-        if (($transaction->failed() || $transaction->is_abandoned())
195
-            && $this->session_lifespan->expiration() < $transaction->datetime(false, true)
196
-        ) {
197
-            $timestamp = esc_html__('TXN in progress...', 'event_espresso');
198
-        } else {
199
-            $timestamp = $transaction->get_i18n_datetime('TXN_timestamp');
200
-        }
201
-        return $timestamp;
202
-    }
203
-
204
-
205
-    /**
206
-     *    column_cb
207
-     *
208
-     * @param \EE_Transaction $transaction
209
-     * @return string
210
-     * @throws \EE_Error
211
-     */
212
-    public function column_cb($transaction)
213
-    {
214
-        return sprintf(
215
-            '<input type="checkbox" name="%1$s[]" value="%2$s" />',
216
-            $this->_wp_list_args['singular'],
217
-            $transaction->ID()
218
-        );
219
-    }
220
-
221
-
222
-    /**
223
-     *    column_TXN_timestamp
224
-     *
225
-     * @param \EE_Transaction $transaction
226
-     * @return string
227
-     * @throws \EE_Error
228
-     */
229
-    public function column_TXN_timestamp(EE_Transaction $transaction)
230
-    {
231
-        $view_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
232
-            'action' => 'view_transaction',
233
-            'TXN_ID' => $transaction->ID(),
234
-        ), TXN_ADMIN_URL);
235
-        $txn_date     = '<a href="' . $view_lnk_url . '"'
236
-                        . ' title="'
237
-                        . esc_attr__('View Transaction Details for TXN #', 'event_espresso') . $transaction->ID() . '">'
238
-                        . $this->_get_txn_timestamp($transaction)
239
-                        . '</a>';
240
-        //status
241
-        $txn_date .= '<br><span class="ee-status-text-small">'
242
-                     . EEH_Template::pretty_status(
243
-                         $transaction->status_ID(),
244
-                         false,
245
-                         'sentence'
246
-                     )
247
-                     . '</span>';
248
-        return $txn_date;
249
-    }
250
-
251
-
252
-    /**
253
-     *    column_TXN_total
254
-     *
255
-     * @param \EE_Transaction $transaction
256
-     * @return string
257
-     * @throws \EE_Error
258
-     */
259
-    public function column_TXN_total(EE_Transaction $transaction)
260
-    {
261
-        if ($transaction->get('TXN_total') > 0) {
262
-            return '<span class="txn-pad-rght">'
263
-                   . apply_filters(
264
-                       'FHEE__EE_Admin_Transactions_List_Table__column_TXN_total__TXN_total',
265
-                       $transaction->get_pretty('TXN_total'),
266
-                       $transaction
267
-                   )
268
-                   . '</span>';
269
-        } else {
270
-            return '<span class="txn-overview-free-event-spn">' . esc_html__('free', 'event_espresso') . '</span>';
271
-        }
272
-    }
273
-
274
-
275
-    /**
276
-     *    column_TXN_paid
277
-     *
278
-     * @param \EE_Transaction $transaction
279
-     * @return mixed|string
280
-     * @throws \EE_Error
281
-     */
282
-    public function column_TXN_paid(EE_Transaction $transaction)
283
-    {
284
-        $transaction_total = $transaction->get('TXN_total');
285
-        $transaction_paid  = $transaction->get('TXN_paid');
286
-
287
-        if (\EEH_Money::compare_floats($transaction_total, 0, '>')) {
288
-            // monies owing
289
-            $span_class = 'txn-overview-part-payment-spn';
290
-            if (\EEH_Money::compare_floats($transaction_paid, $transaction_total, '>=')) {
291
-                // paid in full
292
-                $span_class = 'txn-overview-full-payment-spn';
293
-            } elseif (\EEH_Money::compare_floats($transaction_paid, 0, '==')) {
294
-                // no payments made
295
-                $span_class = 'txn-overview-no-payment-spn';
296
-            }
297
-        } else {
298
-            $span_class       = 'txn-overview-free-event-spn';
299
-            $transaction_paid = 0;
300
-        }
301
-
302
-        $payment_method      = $transaction->payment_method();
303
-        $payment_method_name = $payment_method instanceof EE_Payment_Method
304
-            ? $payment_method->admin_name()
305
-            : esc_html__('Unknown', 'event_espresso');
306
-        $transaction_paid_content = $transaction_paid !== 0 ? $transaction->get_pretty('TXN_paid') : $transaction_paid;
307
-
308
-        $content = '<span class="' . $span_class . ' txn-pad-rght">'
309
-                   . $transaction_paid_content
310
-                   . '</span>';
311
-        if ($transaction_paid > 0) {
312
-            $content .= '<br><span class="ee-status-text-small">'
313
-                        . sprintf(
314
-                            esc_html__('...via %s', 'event_espresso'),
315
-                            $payment_method_name
316
-                        )
317
-                        . '</span>';
318
-        }
319
-        return $content;
320
-    }
321
-
322
-
323
-    /**
324
-     *    column_ATT_fname
325
-     *
326
-     * @param \EE_Transaction $transaction
327
-     * @return string
328
-     * @throws EE_Error
329
-     * @throws InvalidArgumentException
330
-     * @throws InvalidDataTypeException
331
-     * @throws InvalidInterfaceException
332
-     */
333
-    public function column_ATT_fname(EE_Transaction $transaction)
334
-    {
335
-        $primary_reg = $transaction->primary_registration();
336
-        $attendee    = $primary_reg->get_first_related('Attendee');
337
-        if ($attendee instanceof EE_Attendee) {
338
-            $edit_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
339
-                'action'  => 'view_registration',
340
-                '_REG_ID' => $primary_reg->ID(),
341
-            ), REG_ADMIN_URL);
342
-            $content      = EE_Registry::instance()->CAP->current_user_can(
343
-                'ee_read_registration',
344
-                'espresso_registrations_view_registration',
345
-                $primary_reg->ID()
346
-            )
347
-                ? '<a href="' . $edit_lnk_url . '"'
348
-                    . ' title="' . esc_attr__('View Registration Details', 'event_espresso') . '">'
349
-                    . $attendee->full_name()
350
-                    . '</a>'
351
-                : $attendee->full_name();
352
-            $content      .= '<br>' . $attendee->email();
353
-            return $content;
354
-        }
355
-        return $transaction->failed() || $transaction->is_abandoned()
356
-            ? esc_html__('no contact record.', 'event_espresso')
357
-            : esc_html__(
358
-                'No contact record, because the transaction was abandoned or the registration process failed.',
359
-                'event_espresso'
360
-            );
361
-    }
362
-
363
-
364
-    /**
365
-     *    column_ATT_email
366
-     *
367
-     * @param \EE_Transaction $transaction
368
-     * @return string
369
-     * @throws \EE_Error
370
-     */
371
-    public function column_ATT_email(EE_Transaction $transaction)
372
-    {
373
-        $attendee = $transaction->primary_registration()->get_first_related('Attendee');
374
-        if (! empty($attendee)) {
375
-            return '<a href="mailto:' . $attendee->get('ATT_email') . '">'
376
-                   . $attendee->get('ATT_email')
377
-                   . '</a>';
378
-        } else {
379
-            return $transaction->failed() || $transaction->is_abandoned()
380
-                ? esc_html__('no contact record.', 'event_espresso')
381
-                : esc_html__(
382
-                    'No contact record, because the transaction was abandoned or the registration process failed.',
383
-                    'event_espresso'
384
-                );
385
-        }
386
-    }
387
-
388
-
389
-    /**
390
-     *    column_event_name
391
-     *
392
-     * @param \EE_Transaction $transaction
393
-     * @return string
394
-     * @throws EE_Error
395
-     * @throws InvalidArgumentException
396
-     * @throws InvalidDataTypeException
397
-     * @throws InvalidInterfaceException
398
-     */
399
-    public function column_event_name(EE_Transaction $transaction)
400
-    {
401
-        $actions = array();
402
-        $event   = $transaction->primary_registration()->get_first_related('Event');
403
-        if (! empty($event)) {
404
-            $edit_event_url = EE_Admin_Page::add_query_args_and_nonce(
405
-                array('action' => 'edit', 'post' => $event->ID()),
406
-                EVENTS_ADMIN_URL
407
-            );
408
-            $event_name     = $event->get('EVT_name');
409
-
410
-            //filter this view by transactions for this event
411
-            $txn_by_event_lnk = EE_Admin_Page::add_query_args_and_nonce(array(
412
-                'action' => 'default',
413
-                'EVT_ID' => $event->ID(),
414
-            ));
415
-            if (empty($this->_req_data['EVT_ID'])
416
-                && EE_Registry::instance()->CAP->current_user_can(
417
-                    'ee_edit_event',
418
-                    'espresso_events_edit',
419
-                    $event->ID()
420
-                )
421
-            ) {
422
-                $actions['filter_by_event'] = '<a href="' . $txn_by_event_lnk . '"'
423
-                        . ' title="' . esc_attr__('Filter transactions by this event', 'event_espresso') . '">'
424
-                        . esc_html__('View Transactions for this event', 'event_espresso')
425
-                        . '</a>';
426
-            }
427
-
428
-            return sprintf(
429
-                '%1$s %2$s',
430
-                EE_Registry::instance()->CAP->current_user_can(
431
-                    'ee_edit_event',
432
-                    'espresso_events_edit',
433
-                    $event->ID()
434
-                )
435
-                    ? '<a href="' . $edit_event_url . '"'
436
-                        . ' title="'
437
-                        . sprintf(
438
-                            esc_attr__('Edit Event: %s', 'event_espresso'),
439
-                            $event->get('EVT_name')
440
-                        )
441
-                        . '">'
442
-                        . wp_trim_words(
443
-                            $event_name,
444
-                            30,
445
-                            '...'
446
-                        )
447
-                        . '</a>'
448
-                        : wp_trim_words($event_name, 30, '...'),
449
-                $this->row_actions($actions)
450
-            );
451
-        } else {
452
-            return esc_html__(
453
-                'The event associated with this transaction via the primary registration cannot be retrieved.',
454
-                'event_espresso'
455
-            );
456
-        }
457
-    }
458
-
459
-
460
-    /**
461
-     *    column_actions
462
-     *
463
-     * @param \EE_Transaction $transaction
464
-     * @return string
465
-     * @throws \EE_Error
466
-     */
467
-    public function column_actions(EE_Transaction $transaction)
468
-    {
469
-        return $this->_action_string(
470
-            $this->get_transaction_details_link($transaction)
471
-            . $this->get_invoice_link($transaction)
472
-            . $this->get_receipt_link($transaction)
473
-            . $this->get_primary_registration_details_link($transaction)
474
-            . $this->get_send_payment_reminder_trigger_link($transaction)
475
-            . $this->get_payment_overview_link($transaction)
476
-            . $this->get_related_messages_link($transaction),
477
-            $transaction,
478
-            'ul',
479
-            'txn-overview-actions-ul'
480
-        );
481
-    }
482
-
483
-
484
-    /**
485
-     * Get the transaction details link.
486
-     * @param EE_Transaction $transaction
487
-     * @return string
488
-     * @throws EE_Error
489
-     */
490
-    protected function get_transaction_details_link(EE_Transaction $transaction)
491
-    {
492
-        $url          = EE_Admin_Page::add_query_args_and_nonce(array(
493
-            'action' => 'view_transaction',
494
-            'TXN_ID' => $transaction->ID(),
495
-        ), TXN_ADMIN_URL);
496
-        return '
142
+		$filters[] = ob_get_contents();
143
+		ob_end_clean();
144
+		return $filters;
145
+	}
146
+
147
+
148
+	/**
149
+	 *_add_view_counts
150
+	 */
151
+	protected function _add_view_counts()
152
+	{
153
+		$this->_views['all']['count']       = $this->_admin_page->get_transactions($this->_per_page, true, 'all');
154
+		$this->_views['abandoned']['count'] = $this->_admin_page->get_transactions($this->_per_page, true, 'abandoned');
155
+		$this->_views['failed']['count']    = $this->_admin_page->get_transactions($this->_per_page, true, 'failed');
156
+	}
157
+
158
+
159
+	/**
160
+	 *    column TXN_ID
161
+	 *
162
+	 * @param \EE_Transaction $transaction
163
+	 * @return string
164
+	 * @throws \EE_Error
165
+	 */
166
+	public function column_TXN_ID(EE_Transaction $transaction)
167
+	{
168
+		$view_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
169
+			'action' => 'view_transaction',
170
+			'TXN_ID' => $transaction->ID(),
171
+		), TXN_ADMIN_URL);
172
+		$content      = '<a href="' . $view_lnk_url . '"'
173
+						. ' title="' . esc_attr__('Go to Transaction Details', 'event_espresso') . '">'
174
+						. $transaction->ID()
175
+						. '</a>';
176
+
177
+		//txn timestamp
178
+		$content .= '  <span class="show-on-mobile-view-only">' . $this->_get_txn_timestamp($transaction) . '</span>';
179
+		return $content;
180
+	}
181
+
182
+
183
+	/**
184
+	 * @param \EE_Transaction $transaction
185
+	 * @return string
186
+	 * @throws EE_Error
187
+	 * @throws InvalidArgumentException
188
+	 * @throws InvalidDataTypeException
189
+	 * @throws InvalidInterfaceException
190
+	 */
191
+	protected function _get_txn_timestamp(EE_Transaction $transaction)
192
+	{
193
+		// is TXN less than 2 hours old ?
194
+		if (($transaction->failed() || $transaction->is_abandoned())
195
+			&& $this->session_lifespan->expiration() < $transaction->datetime(false, true)
196
+		) {
197
+			$timestamp = esc_html__('TXN in progress...', 'event_espresso');
198
+		} else {
199
+			$timestamp = $transaction->get_i18n_datetime('TXN_timestamp');
200
+		}
201
+		return $timestamp;
202
+	}
203
+
204
+
205
+	/**
206
+	 *    column_cb
207
+	 *
208
+	 * @param \EE_Transaction $transaction
209
+	 * @return string
210
+	 * @throws \EE_Error
211
+	 */
212
+	public function column_cb($transaction)
213
+	{
214
+		return sprintf(
215
+			'<input type="checkbox" name="%1$s[]" value="%2$s" />',
216
+			$this->_wp_list_args['singular'],
217
+			$transaction->ID()
218
+		);
219
+	}
220
+
221
+
222
+	/**
223
+	 *    column_TXN_timestamp
224
+	 *
225
+	 * @param \EE_Transaction $transaction
226
+	 * @return string
227
+	 * @throws \EE_Error
228
+	 */
229
+	public function column_TXN_timestamp(EE_Transaction $transaction)
230
+	{
231
+		$view_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
232
+			'action' => 'view_transaction',
233
+			'TXN_ID' => $transaction->ID(),
234
+		), TXN_ADMIN_URL);
235
+		$txn_date     = '<a href="' . $view_lnk_url . '"'
236
+						. ' title="'
237
+						. esc_attr__('View Transaction Details for TXN #', 'event_espresso') . $transaction->ID() . '">'
238
+						. $this->_get_txn_timestamp($transaction)
239
+						. '</a>';
240
+		//status
241
+		$txn_date .= '<br><span class="ee-status-text-small">'
242
+					 . EEH_Template::pretty_status(
243
+						 $transaction->status_ID(),
244
+						 false,
245
+						 'sentence'
246
+					 )
247
+					 . '</span>';
248
+		return $txn_date;
249
+	}
250
+
251
+
252
+	/**
253
+	 *    column_TXN_total
254
+	 *
255
+	 * @param \EE_Transaction $transaction
256
+	 * @return string
257
+	 * @throws \EE_Error
258
+	 */
259
+	public function column_TXN_total(EE_Transaction $transaction)
260
+	{
261
+		if ($transaction->get('TXN_total') > 0) {
262
+			return '<span class="txn-pad-rght">'
263
+				   . apply_filters(
264
+					   'FHEE__EE_Admin_Transactions_List_Table__column_TXN_total__TXN_total',
265
+					   $transaction->get_pretty('TXN_total'),
266
+					   $transaction
267
+				   )
268
+				   . '</span>';
269
+		} else {
270
+			return '<span class="txn-overview-free-event-spn">' . esc_html__('free', 'event_espresso') . '</span>';
271
+		}
272
+	}
273
+
274
+
275
+	/**
276
+	 *    column_TXN_paid
277
+	 *
278
+	 * @param \EE_Transaction $transaction
279
+	 * @return mixed|string
280
+	 * @throws \EE_Error
281
+	 */
282
+	public function column_TXN_paid(EE_Transaction $transaction)
283
+	{
284
+		$transaction_total = $transaction->get('TXN_total');
285
+		$transaction_paid  = $transaction->get('TXN_paid');
286
+
287
+		if (\EEH_Money::compare_floats($transaction_total, 0, '>')) {
288
+			// monies owing
289
+			$span_class = 'txn-overview-part-payment-spn';
290
+			if (\EEH_Money::compare_floats($transaction_paid, $transaction_total, '>=')) {
291
+				// paid in full
292
+				$span_class = 'txn-overview-full-payment-spn';
293
+			} elseif (\EEH_Money::compare_floats($transaction_paid, 0, '==')) {
294
+				// no payments made
295
+				$span_class = 'txn-overview-no-payment-spn';
296
+			}
297
+		} else {
298
+			$span_class       = 'txn-overview-free-event-spn';
299
+			$transaction_paid = 0;
300
+		}
301
+
302
+		$payment_method      = $transaction->payment_method();
303
+		$payment_method_name = $payment_method instanceof EE_Payment_Method
304
+			? $payment_method->admin_name()
305
+			: esc_html__('Unknown', 'event_espresso');
306
+		$transaction_paid_content = $transaction_paid !== 0 ? $transaction->get_pretty('TXN_paid') : $transaction_paid;
307
+
308
+		$content = '<span class="' . $span_class . ' txn-pad-rght">'
309
+				   . $transaction_paid_content
310
+				   . '</span>';
311
+		if ($transaction_paid > 0) {
312
+			$content .= '<br><span class="ee-status-text-small">'
313
+						. sprintf(
314
+							esc_html__('...via %s', 'event_espresso'),
315
+							$payment_method_name
316
+						)
317
+						. '</span>';
318
+		}
319
+		return $content;
320
+	}
321
+
322
+
323
+	/**
324
+	 *    column_ATT_fname
325
+	 *
326
+	 * @param \EE_Transaction $transaction
327
+	 * @return string
328
+	 * @throws EE_Error
329
+	 * @throws InvalidArgumentException
330
+	 * @throws InvalidDataTypeException
331
+	 * @throws InvalidInterfaceException
332
+	 */
333
+	public function column_ATT_fname(EE_Transaction $transaction)
334
+	{
335
+		$primary_reg = $transaction->primary_registration();
336
+		$attendee    = $primary_reg->get_first_related('Attendee');
337
+		if ($attendee instanceof EE_Attendee) {
338
+			$edit_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
339
+				'action'  => 'view_registration',
340
+				'_REG_ID' => $primary_reg->ID(),
341
+			), REG_ADMIN_URL);
342
+			$content      = EE_Registry::instance()->CAP->current_user_can(
343
+				'ee_read_registration',
344
+				'espresso_registrations_view_registration',
345
+				$primary_reg->ID()
346
+			)
347
+				? '<a href="' . $edit_lnk_url . '"'
348
+					. ' title="' . esc_attr__('View Registration Details', 'event_espresso') . '">'
349
+					. $attendee->full_name()
350
+					. '</a>'
351
+				: $attendee->full_name();
352
+			$content      .= '<br>' . $attendee->email();
353
+			return $content;
354
+		}
355
+		return $transaction->failed() || $transaction->is_abandoned()
356
+			? esc_html__('no contact record.', 'event_espresso')
357
+			: esc_html__(
358
+				'No contact record, because the transaction was abandoned or the registration process failed.',
359
+				'event_espresso'
360
+			);
361
+	}
362
+
363
+
364
+	/**
365
+	 *    column_ATT_email
366
+	 *
367
+	 * @param \EE_Transaction $transaction
368
+	 * @return string
369
+	 * @throws \EE_Error
370
+	 */
371
+	public function column_ATT_email(EE_Transaction $transaction)
372
+	{
373
+		$attendee = $transaction->primary_registration()->get_first_related('Attendee');
374
+		if (! empty($attendee)) {
375
+			return '<a href="mailto:' . $attendee->get('ATT_email') . '">'
376
+				   . $attendee->get('ATT_email')
377
+				   . '</a>';
378
+		} else {
379
+			return $transaction->failed() || $transaction->is_abandoned()
380
+				? esc_html__('no contact record.', 'event_espresso')
381
+				: esc_html__(
382
+					'No contact record, because the transaction was abandoned or the registration process failed.',
383
+					'event_espresso'
384
+				);
385
+		}
386
+	}
387
+
388
+
389
+	/**
390
+	 *    column_event_name
391
+	 *
392
+	 * @param \EE_Transaction $transaction
393
+	 * @return string
394
+	 * @throws EE_Error
395
+	 * @throws InvalidArgumentException
396
+	 * @throws InvalidDataTypeException
397
+	 * @throws InvalidInterfaceException
398
+	 */
399
+	public function column_event_name(EE_Transaction $transaction)
400
+	{
401
+		$actions = array();
402
+		$event   = $transaction->primary_registration()->get_first_related('Event');
403
+		if (! empty($event)) {
404
+			$edit_event_url = EE_Admin_Page::add_query_args_and_nonce(
405
+				array('action' => 'edit', 'post' => $event->ID()),
406
+				EVENTS_ADMIN_URL
407
+			);
408
+			$event_name     = $event->get('EVT_name');
409
+
410
+			//filter this view by transactions for this event
411
+			$txn_by_event_lnk = EE_Admin_Page::add_query_args_and_nonce(array(
412
+				'action' => 'default',
413
+				'EVT_ID' => $event->ID(),
414
+			));
415
+			if (empty($this->_req_data['EVT_ID'])
416
+				&& EE_Registry::instance()->CAP->current_user_can(
417
+					'ee_edit_event',
418
+					'espresso_events_edit',
419
+					$event->ID()
420
+				)
421
+			) {
422
+				$actions['filter_by_event'] = '<a href="' . $txn_by_event_lnk . '"'
423
+						. ' title="' . esc_attr__('Filter transactions by this event', 'event_espresso') . '">'
424
+						. esc_html__('View Transactions for this event', 'event_espresso')
425
+						. '</a>';
426
+			}
427
+
428
+			return sprintf(
429
+				'%1$s %2$s',
430
+				EE_Registry::instance()->CAP->current_user_can(
431
+					'ee_edit_event',
432
+					'espresso_events_edit',
433
+					$event->ID()
434
+				)
435
+					? '<a href="' . $edit_event_url . '"'
436
+						. ' title="'
437
+						. sprintf(
438
+							esc_attr__('Edit Event: %s', 'event_espresso'),
439
+							$event->get('EVT_name')
440
+						)
441
+						. '">'
442
+						. wp_trim_words(
443
+							$event_name,
444
+							30,
445
+							'...'
446
+						)
447
+						. '</a>'
448
+						: wp_trim_words($event_name, 30, '...'),
449
+				$this->row_actions($actions)
450
+			);
451
+		} else {
452
+			return esc_html__(
453
+				'The event associated with this transaction via the primary registration cannot be retrieved.',
454
+				'event_espresso'
455
+			);
456
+		}
457
+	}
458
+
459
+
460
+	/**
461
+	 *    column_actions
462
+	 *
463
+	 * @param \EE_Transaction $transaction
464
+	 * @return string
465
+	 * @throws \EE_Error
466
+	 */
467
+	public function column_actions(EE_Transaction $transaction)
468
+	{
469
+		return $this->_action_string(
470
+			$this->get_transaction_details_link($transaction)
471
+			. $this->get_invoice_link($transaction)
472
+			. $this->get_receipt_link($transaction)
473
+			. $this->get_primary_registration_details_link($transaction)
474
+			. $this->get_send_payment_reminder_trigger_link($transaction)
475
+			. $this->get_payment_overview_link($transaction)
476
+			. $this->get_related_messages_link($transaction),
477
+			$transaction,
478
+			'ul',
479
+			'txn-overview-actions-ul'
480
+		);
481
+	}
482
+
483
+
484
+	/**
485
+	 * Get the transaction details link.
486
+	 * @param EE_Transaction $transaction
487
+	 * @return string
488
+	 * @throws EE_Error
489
+	 */
490
+	protected function get_transaction_details_link(EE_Transaction $transaction)
491
+	{
492
+		$url          = EE_Admin_Page::add_query_args_and_nonce(array(
493
+			'action' => 'view_transaction',
494
+			'TXN_ID' => $transaction->ID(),
495
+		), TXN_ADMIN_URL);
496
+		return '
497 497
 			<li>
498 498
 				<a href="' . $url . '"'
499
-                    . ' title="' . esc_attr__('View Transaction Details', 'event_espresso') . '" class="tiny-text">
499
+					. ' title="' . esc_attr__('View Transaction Details', 'event_espresso') . '" class="tiny-text">
500 500
 					<span class="dashicons dashicons-cart"></span>
501 501
 				</a>
502 502
 			</li>';
503
-    }
504
-
505
-
506
-    /**
507
-     * Get the invoice link for the given registration.
508
-     * @param EE_Transaction $transaction
509
-     * @return string
510
-     * @throws EE_Error
511
-     */
512
-    protected function get_invoice_link(EE_Transaction $transaction)
513
-    {
514
-        $registration = $transaction->primary_registration();
515
-        if ($registration instanceof EE_Registration) {
516
-            $url = $registration->invoice_url();
517
-            //only show invoice link if message type is active.
518
-            if ($registration->attendee() instanceof EE_Attendee
519
-                && EEH_MSG_Template::is_mt_active('invoice')
520
-            ) {
521
-                return '
503
+	}
504
+
505
+
506
+	/**
507
+	 * Get the invoice link for the given registration.
508
+	 * @param EE_Transaction $transaction
509
+	 * @return string
510
+	 * @throws EE_Error
511
+	 */
512
+	protected function get_invoice_link(EE_Transaction $transaction)
513
+	{
514
+		$registration = $transaction->primary_registration();
515
+		if ($registration instanceof EE_Registration) {
516
+			$url = $registration->invoice_url();
517
+			//only show invoice link if message type is active.
518
+			if ($registration->attendee() instanceof EE_Attendee
519
+				&& EEH_MSG_Template::is_mt_active('invoice')
520
+			) {
521
+				return '
522 522
                 <li>
523 523
                     <a title="' . esc_attr__('View Transaction Invoice', 'event_espresso') . '"'
524
-                       . ' target="_blank" href="' . $url . '" class="tiny-text">
524
+					   . ' target="_blank" href="' . $url . '" class="tiny-text">
525 525
                         <span class="dashicons dashicons-media-spreadsheet ee-icon-size-18"></span>
526 526
                     </a>
527 527
                 </li>';
528
-            }
529
-        }
530
-        return '';
531
-    }
532
-
533
-
534
-    /**
535
-     * Get the receipt link for the transaction.
536
-     * @param EE_Transaction $transaction
537
-     * @return string
538
-     * @throws EE_Error
539
-     */
540
-    protected function get_receipt_link(EE_Transaction $transaction)
541
-    {
542
-        $registration = $transaction->primary_registration();
543
-        if ($registration instanceof EE_Registration) {
544
-            $url = $registration->receipt_url();
545
-            //only show receipt link if message type is active.
546
-            if ($registration->attendee() instanceof EE_Attendee
547
-                && EEH_MSG_Template::is_mt_active('receipt')) {
548
-                return '
528
+			}
529
+		}
530
+		return '';
531
+	}
532
+
533
+
534
+	/**
535
+	 * Get the receipt link for the transaction.
536
+	 * @param EE_Transaction $transaction
537
+	 * @return string
538
+	 * @throws EE_Error
539
+	 */
540
+	protected function get_receipt_link(EE_Transaction $transaction)
541
+	{
542
+		$registration = $transaction->primary_registration();
543
+		if ($registration instanceof EE_Registration) {
544
+			$url = $registration->receipt_url();
545
+			//only show receipt link if message type is active.
546
+			if ($registration->attendee() instanceof EE_Attendee
547
+				&& EEH_MSG_Template::is_mt_active('receipt')) {
548
+				return '
549 549
 			<li>
550 550
 				<a title="' . esc_attr__('View Transaction Receipt', 'event_espresso') . '"'
551
-                                  . ' target="_blank" href="' . $url . '" class="tiny-text">
551
+								  . ' target="_blank" href="' . $url . '" class="tiny-text">
552 552
 					<span class="dashicons dashicons-media-default ee-icon-size-18"></span>
553 553
 				</a>
554 554
 			</li>';
555
-            }
556
-        }
557
-        return '';
558
-    }
559
-
560
-
561
-    /**
562
-     * Get the link to view the details for the primary registration.
563
-     *
564
-     * @param EE_Transaction $transaction
565
-     * @return string
566
-     * @throws EE_Error
567
-     * @throws InvalidArgumentException
568
-     * @throws InvalidDataTypeException
569
-     * @throws InvalidInterfaceException
570
-     */
571
-    protected function get_primary_registration_details_link(EE_Transaction $transaction)
572
-    {
573
-        $registration = $transaction->primary_registration();
574
-        if ($registration instanceof EE_Registration) {
575
-            $url      = EE_Admin_Page::add_query_args_and_nonce(array(
576
-                'action'  => 'view_registration',
577
-                '_REG_ID' => $registration->ID(),
578
-            ), REG_ADMIN_URL);
579
-            return EE_Registry::instance()->CAP->current_user_can(
580
-                'ee_read_registration',
581
-                'espresso_registrations_view_registration',
582
-                $registration->ID()
583
-            )
584
-                ? '
555
+			}
556
+		}
557
+		return '';
558
+	}
559
+
560
+
561
+	/**
562
+	 * Get the link to view the details for the primary registration.
563
+	 *
564
+	 * @param EE_Transaction $transaction
565
+	 * @return string
566
+	 * @throws EE_Error
567
+	 * @throws InvalidArgumentException
568
+	 * @throws InvalidDataTypeException
569
+	 * @throws InvalidInterfaceException
570
+	 */
571
+	protected function get_primary_registration_details_link(EE_Transaction $transaction)
572
+	{
573
+		$registration = $transaction->primary_registration();
574
+		if ($registration instanceof EE_Registration) {
575
+			$url      = EE_Admin_Page::add_query_args_and_nonce(array(
576
+				'action'  => 'view_registration',
577
+				'_REG_ID' => $registration->ID(),
578
+			), REG_ADMIN_URL);
579
+			return EE_Registry::instance()->CAP->current_user_can(
580
+				'ee_read_registration',
581
+				'espresso_registrations_view_registration',
582
+				$registration->ID()
583
+			)
584
+				? '
585 585
 				<li>
586 586
 					<a href="' . $url . '"'
587
-                  . ' title="' . esc_attr__('View Registration Details', 'event_espresso') . '" class="tiny-text">
587
+				  . ' title="' . esc_attr__('View Registration Details', 'event_espresso') . '" class="tiny-text">
588 588
 						<span class="dashicons dashicons-clipboard"></span>
589 589
 					</a>
590 590
 				</li>'
591
-                : '';
592
-        }
593
-        return '';
594
-    }
595
-
596
-
597
-    /**
598
-     * Get send payment reminder trigger link
599
-     * @param EE_Transaction $transaction
600
-     * @return string
601
-     * @throws EE_Error
602
-     * @throws InvalidArgumentException
603
-     * @throws InvalidDataTypeException
604
-     * @throws InvalidInterfaceException
605
-     */
606
-    protected function get_send_payment_reminder_trigger_link(EE_Transaction $transaction)
607
-    {
608
-        $registration = $transaction->primary_registration();
609
-        if ($registration instanceof EE_Registration
610
-            && $registration->attendee() instanceof EE_Attendee
611
-            && EEH_MSG_Template::is_mt_active('payment_reminder')
612
-            && ! in_array(
613
-                $transaction->status_ID(),
614
-                array(EEM_Transaction::complete_status_code, EEM_Transaction::overpaid_status_code),
615
-                true
616
-            )
617
-            && EE_Registry::instance()->CAP->current_user_can(
618
-                'ee_send_message',
619
-                'espresso_transactions_send_payment_reminder'
620
-            )
621
-        ) {
622
-            $url = EE_Admin_Page::add_query_args_and_nonce(array(
623
-                'action' => 'send_payment_reminder',
624
-                'TXN_ID' => $transaction->ID(),
625
-            ), TXN_ADMIN_URL);
626
-            return  '
591
+				: '';
592
+		}
593
+		return '';
594
+	}
595
+
596
+
597
+	/**
598
+	 * Get send payment reminder trigger link
599
+	 * @param EE_Transaction $transaction
600
+	 * @return string
601
+	 * @throws EE_Error
602
+	 * @throws InvalidArgumentException
603
+	 * @throws InvalidDataTypeException
604
+	 * @throws InvalidInterfaceException
605
+	 */
606
+	protected function get_send_payment_reminder_trigger_link(EE_Transaction $transaction)
607
+	{
608
+		$registration = $transaction->primary_registration();
609
+		if ($registration instanceof EE_Registration
610
+			&& $registration->attendee() instanceof EE_Attendee
611
+			&& EEH_MSG_Template::is_mt_active('payment_reminder')
612
+			&& ! in_array(
613
+				$transaction->status_ID(),
614
+				array(EEM_Transaction::complete_status_code, EEM_Transaction::overpaid_status_code),
615
+				true
616
+			)
617
+			&& EE_Registry::instance()->CAP->current_user_can(
618
+				'ee_send_message',
619
+				'espresso_transactions_send_payment_reminder'
620
+			)
621
+		) {
622
+			$url = EE_Admin_Page::add_query_args_and_nonce(array(
623
+				'action' => 'send_payment_reminder',
624
+				'TXN_ID' => $transaction->ID(),
625
+			), TXN_ADMIN_URL);
626
+			return  '
627 627
             <li>
628 628
                 <a href="' . $url . '"'
629
-                  . ' title="' . esc_attr__('Send Payment Reminder', 'event_espresso') . '" class="tiny-text">
629
+				  . ' title="' . esc_attr__('Send Payment Reminder', 'event_espresso') . '" class="tiny-text">
630 630
                     <span class="dashicons dashicons-email-alt"></span>
631 631
                 </a>
632 632
             </li>';
633
-        }
634
-        return '';
635
-    }
636
-
637
-
638
-    /**
639
-     * Get link to filtered view in the message activity list table of messages for this transaction.
640
-     * @param EE_Transaction $transaction
641
-     * @return string
642
-     * @throws EE_Error
643
-     * @throws InvalidArgumentException
644
-     * @throws InvalidDataTypeException
645
-     * @throws InvalidInterfaceException
646
-     */
647
-    protected function get_related_messages_link(EE_Transaction $transaction)
648
-    {
649
-        $url = EEH_MSG_Template::get_message_action_link(
650
-            'see_notifications_for',
651
-            null,
652
-            array('TXN_ID' => $transaction->ID())
653
-        );
654
-        return EE_Registry::instance()->CAP->current_user_can(
655
-            'ee_read_global_messages',
656
-            'view_filtered_messages'
657
-        )
658
-            ? '<li>' . $url . '</li>'
659
-            : '';
660
-    }
661
-
662
-
663
-    /**
664
-     * Return the link to make a payment on the frontend
665
-     * @param EE_Transaction $transaction
666
-     * @return string
667
-     * @throws EE_Error
668
-     */
669
-    protected function get_payment_overview_link(EE_Transaction $transaction)
670
-    {
671
-        $registration = $transaction->primary_registration();
672
-        if ($registration instanceof EE_Registration
673
-            && $transaction->status_ID() !== EEM_Transaction::complete_status_code
674
-            && $registration->owes_monies_and_can_pay()
675
-        ) {
676
-            return '
633
+		}
634
+		return '';
635
+	}
636
+
637
+
638
+	/**
639
+	 * Get link to filtered view in the message activity list table of messages for this transaction.
640
+	 * @param EE_Transaction $transaction
641
+	 * @return string
642
+	 * @throws EE_Error
643
+	 * @throws InvalidArgumentException
644
+	 * @throws InvalidDataTypeException
645
+	 * @throws InvalidInterfaceException
646
+	 */
647
+	protected function get_related_messages_link(EE_Transaction $transaction)
648
+	{
649
+		$url = EEH_MSG_Template::get_message_action_link(
650
+			'see_notifications_for',
651
+			null,
652
+			array('TXN_ID' => $transaction->ID())
653
+		);
654
+		return EE_Registry::instance()->CAP->current_user_can(
655
+			'ee_read_global_messages',
656
+			'view_filtered_messages'
657
+		)
658
+			? '<li>' . $url . '</li>'
659
+			: '';
660
+	}
661
+
662
+
663
+	/**
664
+	 * Return the link to make a payment on the frontend
665
+	 * @param EE_Transaction $transaction
666
+	 * @return string
667
+	 * @throws EE_Error
668
+	 */
669
+	protected function get_payment_overview_link(EE_Transaction $transaction)
670
+	{
671
+		$registration = $transaction->primary_registration();
672
+		if ($registration instanceof EE_Registration
673
+			&& $transaction->status_ID() !== EEM_Transaction::complete_status_code
674
+			&& $registration->owes_monies_and_can_pay()
675
+		) {
676
+			return '
677 677
             <li>
678 678
                 <a title="' . esc_attr__('Make Payment from the Frontend.', 'event_espresso') . '"'
679
-                    . ' target="_blank" href="' . $registration->payment_overview_url(true) . '"'
680
-                    . ' class="tiny-text">
679
+					. ' target="_blank" href="' . $registration->payment_overview_url(true) . '"'
680
+					. ' class="tiny-text">
681 681
                     <span class="dashicons dashicons-money ee-icon-size-18"></span>
682 682
                 </a>
683 683
             </li>
684 684
             ';
685 685
 
686
-        }
687
-        return '';
688
-    }
686
+		}
687
+		return '';
688
+	}
689 689
 }
Please login to merge, or discard this patch.
core/domain/values/session/SessionLifespan.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@
 block discarded – undo
53 53
      */
54 54
     protected function setLifespan($lifespan)
55 55
     {
56
-        if($lifespan < 60) {
56
+        if ($lifespan < 60) {
57 57
             throw new DomainException(
58 58
                 esc_html__(
59 59
                     'The session lifespan needs to be at least 60 seconds, and even that is extremely short',
Please login to merge, or discard this patch.
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -24,99 +24,99 @@
 block discarded – undo
24 24
 class SessionLifespan
25 25
 {
26 26
 
27
-    /**
28
-     * how long an EE session lasts in seconds
29
-     * default session lifespan of 1 hour (for not so instant IPNs)
30
-     *
31
-     * @var int $lifespan
32
-     */
33
-    private $lifespan;
34
-
35
-
36
-    /**
37
-     * SessionLifespan constructor.
38
-     *
39
-     * @param int $lifespan
40
-     * @throws DomainException
41
-     */
42
-    public function __construct($lifespan = 0)
43
-    {
44
-        $lifespan = absint($lifespan);
45
-        $lifespan = $lifespan > 0 ? $lifespan : (int) HOUR_IN_SECONDS;
46
-        $this->setLifespan($lifespan);
47
-    }
48
-
49
-
50
-    /**
51
-     * @param int $lifespan
52
-     * @throws DomainException
53
-     */
54
-    protected function setLifespan($lifespan)
55
-    {
56
-        if($lifespan < 60) {
57
-            throw new DomainException(
58
-                esc_html__(
59
-                    'The session lifespan needs to be at least 60 seconds, and even that is extremely short',
60
-                    'event_espresso'
61
-                )
62
-            );
63
-
64
-        }
65
-        $this->lifespan = apply_filters(
66
-            'FHEE__EventEspresso_core_domain_values_session_SessionLifespan__setLifespan___lifespan',
67
-            // apply legacy filter for now but add doing it wrong notice in future
68
-            apply_filters(
69
-                'FHEE__EE_Session__construct___lifespan',
70
-                $lifespan
71
-            )
72
-        ) + 1;
73
-    }
74
-
75
-
76
-    /**
77
-     * @return int
78
-     */
79
-    public function inSeconds()
80
-    {
81
-        return $this->lifespan;
82
-    }
83
-
84
-
85
-    /**
86
-     * @param string $separator
87
-     * @return string
88
-     */
89
-    public function inHoursMinutesSeconds($separator = ':')
90
-    {
91
-        return sprintf(
92
-            '%02d%s%02d%s%02d',
93
-            floor($this->lifespan / 3600),
94
-            $separator,
95
-            ($this->lifespan / 60) % 60,
96
-            $separator,
97
-            $this->lifespan % 60
98
-        );
99
-    }
100
-
101
-
102
-    /**
103
-     * Returns a timestamp for when the session would expire based on this lifespan
104
-     *
105
-     * @param bool $utc If true, displays expiration in UTC
106
-     *                  If false, displays expiration in local time
107
-     * @return int
108
-     */
109
-    public function expiration($utc = true)
110
-    {
111
-        return (int) current_time('timestamp', $utc) - $this->lifespan;
112
-    }
113
-
114
-
115
-    /**
116
-     * @return string
117
-     */
118
-    public function __toString()
119
-    {
120
-        return (string) $this->inSeconds();
121
-    }
27
+	/**
28
+	 * how long an EE session lasts in seconds
29
+	 * default session lifespan of 1 hour (for not so instant IPNs)
30
+	 *
31
+	 * @var int $lifespan
32
+	 */
33
+	private $lifespan;
34
+
35
+
36
+	/**
37
+	 * SessionLifespan constructor.
38
+	 *
39
+	 * @param int $lifespan
40
+	 * @throws DomainException
41
+	 */
42
+	public function __construct($lifespan = 0)
43
+	{
44
+		$lifespan = absint($lifespan);
45
+		$lifespan = $lifespan > 0 ? $lifespan : (int) HOUR_IN_SECONDS;
46
+		$this->setLifespan($lifespan);
47
+	}
48
+
49
+
50
+	/**
51
+	 * @param int $lifespan
52
+	 * @throws DomainException
53
+	 */
54
+	protected function setLifespan($lifespan)
55
+	{
56
+		if($lifespan < 60) {
57
+			throw new DomainException(
58
+				esc_html__(
59
+					'The session lifespan needs to be at least 60 seconds, and even that is extremely short',
60
+					'event_espresso'
61
+				)
62
+			);
63
+
64
+		}
65
+		$this->lifespan = apply_filters(
66
+			'FHEE__EventEspresso_core_domain_values_session_SessionLifespan__setLifespan___lifespan',
67
+			// apply legacy filter for now but add doing it wrong notice in future
68
+			apply_filters(
69
+				'FHEE__EE_Session__construct___lifespan',
70
+				$lifespan
71
+			)
72
+		) + 1;
73
+	}
74
+
75
+
76
+	/**
77
+	 * @return int
78
+	 */
79
+	public function inSeconds()
80
+	{
81
+		return $this->lifespan;
82
+	}
83
+
84
+
85
+	/**
86
+	 * @param string $separator
87
+	 * @return string
88
+	 */
89
+	public function inHoursMinutesSeconds($separator = ':')
90
+	{
91
+		return sprintf(
92
+			'%02d%s%02d%s%02d',
93
+			floor($this->lifespan / 3600),
94
+			$separator,
95
+			($this->lifespan / 60) % 60,
96
+			$separator,
97
+			$this->lifespan % 60
98
+		);
99
+	}
100
+
101
+
102
+	/**
103
+	 * Returns a timestamp for when the session would expire based on this lifespan
104
+	 *
105
+	 * @param bool $utc If true, displays expiration in UTC
106
+	 *                  If false, displays expiration in local time
107
+	 * @return int
108
+	 */
109
+	public function expiration($utc = true)
110
+	{
111
+		return (int) current_time('timestamp', $utc) - $this->lifespan;
112
+	}
113
+
114
+
115
+	/**
116
+	 * @return string
117
+	 */
118
+	public function __toString()
119
+	{
120
+		return (string) $this->inSeconds();
121
+	}
122 122
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Transaction.model.php 1 patch
Indentation   +405 added lines, -405 removed lines patch added patch discarded remove patch
@@ -5,7 +5,7 @@  discard block
 block discarded – undo
5 5
 use EventEspresso\core\services\loaders\LoaderFactory;
6 6
 
7 7
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
8
-    exit('No direct script access allowed');
8
+	exit('No direct script access allowed');
9 9
 }
10 10
 require_once(EE_MODELS . 'EEM_Base.model.php');
11 11
 
@@ -21,193 +21,193 @@  discard block
 block discarded – undo
21 21
 class EEM_Transaction extends EEM_Base
22 22
 {
23 23
 
24
-    // private instance of the Transaction object
25
-    protected static $_instance;
26
-
27
-    /**
28
-     * Status ID(STS_ID on esp_status table) to indicate the transaction is complete,
29
-     * but payment is pending. This is the state for transactions where payment is promised
30
-     * from an offline gateway.
31
-     */
32
-    //	const open_status_code = 'TPN';
33
-
34
-    /**
35
-     * Status ID(STS_ID on esp_status table) to indicate the transaction failed,
36
-     * either due to a technical reason (server or computer crash during registration),
37
-     *  or some other reason that prevent the collection of any useful contact information from any of the registrants
38
-     */
39
-    const failed_status_code = 'TFL';
40
-
41
-    /**
42
-     * Status ID(STS_ID on esp_status table) to indicate the transaction was abandoned,
43
-     * either due to a technical reason (server or computer crash during registration),
44
-     * or due to an abandoned cart after registrant chose not to complete the registration process
45
-     * HOWEVER...
46
-     * an abandoned TXN differs from a failed TXN in that it was able to capture contact information for at least one
47
-     * registrant
48
-     */
49
-    const abandoned_status_code = 'TAB';
50
-
51
-    /**
52
-     * Status ID(STS_ID on esp_status table) to indicate an incomplete transaction,
53
-     * meaning that monies are still owing: TXN_paid < TXN_total
54
-     */
55
-    const incomplete_status_code = 'TIN';
56
-
57
-    /**
58
-     * Status ID (STS_ID on esp_status table) to indicate a complete transaction.
59
-     * meaning that NO monies are owing: TXN_paid == TXN_total
60
-     */
61
-    const complete_status_code = 'TCM';
62
-
63
-    /**
64
-     *  Status ID(STS_ID on esp_status table) to indicate the transaction is overpaid.
65
-     *  This is the same as complete, but site admins actually owe clients the moneys!  TXN_paid > TXN_total
66
-     */
67
-    const overpaid_status_code = 'TOP';
68
-
69
-
70
-    /**
71
-     *    private constructor to prevent direct creation
72
-     *
73
-     * @Constructor
74
-     * @access protected
75
-     *
76
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
77
-     *                         incoming timezone data that gets saved). Note this just sends the timezone info to the
78
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
79
-     *                         timezone in the 'timezone_string' wp option)
80
-     *
81
-     * @return EEM_Transaction
82
-     * @throws \EE_Error
83
-     */
84
-    protected function __construct($timezone)
85
-    {
86
-        $this->singular_item = __('Transaction', 'event_espresso');
87
-        $this->plural_item   = __('Transactions', 'event_espresso');
88
-
89
-        $this->_tables                 = array(
90
-            'TransactionTable' => new EE_Primary_Table('esp_transaction', 'TXN_ID')
91
-        );
92
-        $this->_fields                 = array(
93
-            'TransactionTable' => array(
94
-                'TXN_ID'           => new EE_Primary_Key_Int_Field('TXN_ID', __('Transaction ID', 'event_espresso')),
95
-                'TXN_timestamp'    => new EE_Datetime_Field('TXN_timestamp',
96
-                    __('date when transaction was created', 'event_espresso'), false, EE_Datetime_Field::now,
97
-                    $timezone),
98
-                'TXN_total'        => new EE_Money_Field('TXN_total',
99
-                    __('Total value of Transaction', 'event_espresso'), false, 0),
100
-                'TXN_paid'         => new EE_Money_Field('TXN_paid',
101
-                    __('Amount paid towards transaction to date', 'event_espresso'), false, 0),
102
-                'STS_ID'           => new EE_Foreign_Key_String_Field('STS_ID', __('Status ID', 'event_espresso'),
103
-                    false, EEM_Transaction::failed_status_code, 'Status'),
104
-                'TXN_session_data' => new EE_Serialized_Text_Field('TXN_session_data',
105
-                    __('Serialized session data', 'event_espresso'), true, ''),
106
-                'TXN_hash_salt'    => new EE_Plain_Text_Field('TXN_hash_salt',
107
-                    __('Transaction Hash Salt', 'event_espresso'), true, ''),
108
-                'PMD_ID'           => new EE_Foreign_Key_Int_Field('PMD_ID',
109
-                    __("Last Used Payment Method", 'event_espresso'), true, null, 'Payment_Method'),
110
-                'TXN_reg_steps'    => new EE_Serialized_Text_Field('TXN_reg_steps',
111
-                    __('Registration Steps', 'event_espresso'), false, array()),
112
-            )
113
-        );
114
-        $this->_model_relations        = array(
115
-            'Registration'   => new EE_Has_Many_Relation(),
116
-            'Payment'        => new EE_Has_Many_Relation(),
117
-            'Status'         => new EE_Belongs_To_Relation(),
118
-            'Line_Item'      => new EE_Has_Many_Relation(false),
119
-            //you can delete a transaction without needing to delete its line items
120
-            'Payment_Method' => new EE_Belongs_To_Relation(),
121
-            'Message'        => new EE_Has_Many_Relation()
122
-        );
123
-        $this->_model_chain_to_wp_user = 'Registration.Event';
124
-        parent::__construct($timezone);
125
-
126
-    }
127
-
128
-
129
-    /**
130
-     *    txn_status_array
131
-     * get list of transaction statuses
132
-     *
133
-     * @access public
134
-     * @return array
135
-     */
136
-    public static function txn_status_array()
137
-    {
138
-        return apply_filters(
139
-            'FHEE__EEM_Transaction__txn_status_array',
140
-            array(
141
-                EEM_Transaction::overpaid_status_code,
142
-                EEM_Transaction::complete_status_code,
143
-                EEM_Transaction::incomplete_status_code,
144
-                EEM_Transaction::abandoned_status_code,
145
-                EEM_Transaction::failed_status_code,
146
-            )
147
-        );
148
-    }
149
-
150
-    /**
151
-     *        get the revenue per day  for the Transaction Admin page Reports Tab
152
-     *
153
-     * @access        public
154
-     *
155
-     * @param string $period
156
-     *
157
-     * @return \stdClass[]
158
-     */
159
-    public function get_revenue_per_day_report($period = '-1 month')
160
-    {
161
-        $sql_date = $this->convert_datetime_for_query('TXN_timestamp', date('Y-m-d H:i:s', strtotime($period)),
162
-            'Y-m-d H:i:s', 'UTC');
163
-
164
-        $query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'TXN_timestamp');
165
-
166
-        return $this->_get_all_wpdb_results(
167
-            array(
168
-                array(
169
-                    'TXN_timestamp' => array('>=', $sql_date)
170
-                ),
171
-                'group_by' => 'txnDate',
172
-                'order_by' => array('TXN_timestamp' => 'ASC')
173
-            ),
174
-            OBJECT,
175
-            array(
176
-                'txnDate' => array('DATE(' . $query_interval . ')', '%s'),
177
-                'revenue' => array('SUM(TransactionTable.TXN_paid)', '%d')
178
-            )
179
-        );
180
-    }
181
-
182
-
183
-    /**
184
-     *        get the revenue per event  for the Transaction Admin page Reports Tab
185
-     *
186
-     * @access        public
187
-     *
188
-     * @param string $period
189
-     *
190
-     * @throws \EE_Error
191
-     * @return mixed
192
-     */
193
-    public function get_revenue_per_event_report($period = '-1 month')
194
-    {
195
-        global $wpdb;
196
-        $transaction_table          = $wpdb->prefix . 'esp_transaction';
197
-        $registration_table         = $wpdb->prefix . 'esp_registration';
198
-        $registration_payment_table = $wpdb->prefix . 'esp_registration_payment';
199
-        $event_table                = $wpdb->posts;
200
-        $payment_table              = $wpdb->prefix . 'esp_payment';
201
-        $sql_date                   = date('Y-m-d H:i:s', strtotime($period));
202
-        $approved_payment_status    = EEM_Payment::status_id_approved;
203
-        $extra_event_on_join        = '';
204
-        //exclude events not authored by user if permissions in effect
205
-        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
206
-            $extra_event_on_join = ' AND Event.post_author = ' . get_current_user_id();
207
-        }
208
-
209
-        return $wpdb->get_results(
210
-            "SELECT
24
+	// private instance of the Transaction object
25
+	protected static $_instance;
26
+
27
+	/**
28
+	 * Status ID(STS_ID on esp_status table) to indicate the transaction is complete,
29
+	 * but payment is pending. This is the state for transactions where payment is promised
30
+	 * from an offline gateway.
31
+	 */
32
+	//	const open_status_code = 'TPN';
33
+
34
+	/**
35
+	 * Status ID(STS_ID on esp_status table) to indicate the transaction failed,
36
+	 * either due to a technical reason (server or computer crash during registration),
37
+	 *  or some other reason that prevent the collection of any useful contact information from any of the registrants
38
+	 */
39
+	const failed_status_code = 'TFL';
40
+
41
+	/**
42
+	 * Status ID(STS_ID on esp_status table) to indicate the transaction was abandoned,
43
+	 * either due to a technical reason (server or computer crash during registration),
44
+	 * or due to an abandoned cart after registrant chose not to complete the registration process
45
+	 * HOWEVER...
46
+	 * an abandoned TXN differs from a failed TXN in that it was able to capture contact information for at least one
47
+	 * registrant
48
+	 */
49
+	const abandoned_status_code = 'TAB';
50
+
51
+	/**
52
+	 * Status ID(STS_ID on esp_status table) to indicate an incomplete transaction,
53
+	 * meaning that monies are still owing: TXN_paid < TXN_total
54
+	 */
55
+	const incomplete_status_code = 'TIN';
56
+
57
+	/**
58
+	 * Status ID (STS_ID on esp_status table) to indicate a complete transaction.
59
+	 * meaning that NO monies are owing: TXN_paid == TXN_total
60
+	 */
61
+	const complete_status_code = 'TCM';
62
+
63
+	/**
64
+	 *  Status ID(STS_ID on esp_status table) to indicate the transaction is overpaid.
65
+	 *  This is the same as complete, but site admins actually owe clients the moneys!  TXN_paid > TXN_total
66
+	 */
67
+	const overpaid_status_code = 'TOP';
68
+
69
+
70
+	/**
71
+	 *    private constructor to prevent direct creation
72
+	 *
73
+	 * @Constructor
74
+	 * @access protected
75
+	 *
76
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
77
+	 *                         incoming timezone data that gets saved). Note this just sends the timezone info to the
78
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
79
+	 *                         timezone in the 'timezone_string' wp option)
80
+	 *
81
+	 * @return EEM_Transaction
82
+	 * @throws \EE_Error
83
+	 */
84
+	protected function __construct($timezone)
85
+	{
86
+		$this->singular_item = __('Transaction', 'event_espresso');
87
+		$this->plural_item   = __('Transactions', 'event_espresso');
88
+
89
+		$this->_tables                 = array(
90
+			'TransactionTable' => new EE_Primary_Table('esp_transaction', 'TXN_ID')
91
+		);
92
+		$this->_fields                 = array(
93
+			'TransactionTable' => array(
94
+				'TXN_ID'           => new EE_Primary_Key_Int_Field('TXN_ID', __('Transaction ID', 'event_espresso')),
95
+				'TXN_timestamp'    => new EE_Datetime_Field('TXN_timestamp',
96
+					__('date when transaction was created', 'event_espresso'), false, EE_Datetime_Field::now,
97
+					$timezone),
98
+				'TXN_total'        => new EE_Money_Field('TXN_total',
99
+					__('Total value of Transaction', 'event_espresso'), false, 0),
100
+				'TXN_paid'         => new EE_Money_Field('TXN_paid',
101
+					__('Amount paid towards transaction to date', 'event_espresso'), false, 0),
102
+				'STS_ID'           => new EE_Foreign_Key_String_Field('STS_ID', __('Status ID', 'event_espresso'),
103
+					false, EEM_Transaction::failed_status_code, 'Status'),
104
+				'TXN_session_data' => new EE_Serialized_Text_Field('TXN_session_data',
105
+					__('Serialized session data', 'event_espresso'), true, ''),
106
+				'TXN_hash_salt'    => new EE_Plain_Text_Field('TXN_hash_salt',
107
+					__('Transaction Hash Salt', 'event_espresso'), true, ''),
108
+				'PMD_ID'           => new EE_Foreign_Key_Int_Field('PMD_ID',
109
+					__("Last Used Payment Method", 'event_espresso'), true, null, 'Payment_Method'),
110
+				'TXN_reg_steps'    => new EE_Serialized_Text_Field('TXN_reg_steps',
111
+					__('Registration Steps', 'event_espresso'), false, array()),
112
+			)
113
+		);
114
+		$this->_model_relations        = array(
115
+			'Registration'   => new EE_Has_Many_Relation(),
116
+			'Payment'        => new EE_Has_Many_Relation(),
117
+			'Status'         => new EE_Belongs_To_Relation(),
118
+			'Line_Item'      => new EE_Has_Many_Relation(false),
119
+			//you can delete a transaction without needing to delete its line items
120
+			'Payment_Method' => new EE_Belongs_To_Relation(),
121
+			'Message'        => new EE_Has_Many_Relation()
122
+		);
123
+		$this->_model_chain_to_wp_user = 'Registration.Event';
124
+		parent::__construct($timezone);
125
+
126
+	}
127
+
128
+
129
+	/**
130
+	 *    txn_status_array
131
+	 * get list of transaction statuses
132
+	 *
133
+	 * @access public
134
+	 * @return array
135
+	 */
136
+	public static function txn_status_array()
137
+	{
138
+		return apply_filters(
139
+			'FHEE__EEM_Transaction__txn_status_array',
140
+			array(
141
+				EEM_Transaction::overpaid_status_code,
142
+				EEM_Transaction::complete_status_code,
143
+				EEM_Transaction::incomplete_status_code,
144
+				EEM_Transaction::abandoned_status_code,
145
+				EEM_Transaction::failed_status_code,
146
+			)
147
+		);
148
+	}
149
+
150
+	/**
151
+	 *        get the revenue per day  for the Transaction Admin page Reports Tab
152
+	 *
153
+	 * @access        public
154
+	 *
155
+	 * @param string $period
156
+	 *
157
+	 * @return \stdClass[]
158
+	 */
159
+	public function get_revenue_per_day_report($period = '-1 month')
160
+	{
161
+		$sql_date = $this->convert_datetime_for_query('TXN_timestamp', date('Y-m-d H:i:s', strtotime($period)),
162
+			'Y-m-d H:i:s', 'UTC');
163
+
164
+		$query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'TXN_timestamp');
165
+
166
+		return $this->_get_all_wpdb_results(
167
+			array(
168
+				array(
169
+					'TXN_timestamp' => array('>=', $sql_date)
170
+				),
171
+				'group_by' => 'txnDate',
172
+				'order_by' => array('TXN_timestamp' => 'ASC')
173
+			),
174
+			OBJECT,
175
+			array(
176
+				'txnDate' => array('DATE(' . $query_interval . ')', '%s'),
177
+				'revenue' => array('SUM(TransactionTable.TXN_paid)', '%d')
178
+			)
179
+		);
180
+	}
181
+
182
+
183
+	/**
184
+	 *        get the revenue per event  for the Transaction Admin page Reports Tab
185
+	 *
186
+	 * @access        public
187
+	 *
188
+	 * @param string $period
189
+	 *
190
+	 * @throws \EE_Error
191
+	 * @return mixed
192
+	 */
193
+	public function get_revenue_per_event_report($period = '-1 month')
194
+	{
195
+		global $wpdb;
196
+		$transaction_table          = $wpdb->prefix . 'esp_transaction';
197
+		$registration_table         = $wpdb->prefix . 'esp_registration';
198
+		$registration_payment_table = $wpdb->prefix . 'esp_registration_payment';
199
+		$event_table                = $wpdb->posts;
200
+		$payment_table              = $wpdb->prefix . 'esp_payment';
201
+		$sql_date                   = date('Y-m-d H:i:s', strtotime($period));
202
+		$approved_payment_status    = EEM_Payment::status_id_approved;
203
+		$extra_event_on_join        = '';
204
+		//exclude events not authored by user if permissions in effect
205
+		if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
206
+			$extra_event_on_join = ' AND Event.post_author = ' . get_current_user_id();
207
+		}
208
+
209
+		return $wpdb->get_results(
210
+			"SELECT
211 211
 			Transaction_Event.event_name AS event_name,
212 212
 			SUM(Transaction_Event.paid) AS revenue
213 213
 			FROM
@@ -235,227 +235,227 @@  discard block
 block discarded – undo
235 235
 					$extra_event_on_join
236 236
 				) AS Transaction_Event
237 237
 			GROUP BY event_name",
238
-            OBJECT
239
-        );
240
-    }
241
-
242
-
243
-    /**
244
-     * Gets the current transaction given the reg_url_link, or assumes the reg_url_link is in the
245
-     * $_REQUEST global variable. Either way, tries to find the current transaction (through
246
-     * the registration pointed to by reg_url_link), if not returns null
247
-     *
248
-     * @param string $reg_url_link
249
-     *
250
-     * @return EE_Transaction
251
-     */
252
-    public function get_transaction_from_reg_url_link($reg_url_link = '')
253
-    {
254
-        return $this->get_one(array(
255
-            array(
256
-                'Registration.REG_url_link' => ! empty($reg_url_link) ? $reg_url_link : EE_Registry::instance()->REQ->get('e_reg_url_link',
257
-                    '')
258
-            )
259
-        ));
260
-    }
261
-
262
-
263
-    /**
264
-     * Updates the provided EE_Transaction with all the applicable payments
265
-     * (or fetch the EE_Transaction from its ID)
266
-     *
267
-     * @deprecated
268
-     *
269
-     * @param EE_Transaction|int $transaction_obj_or_id
270
-     * @param boolean            $save_txn whether or not to save the transaction during this function call
271
-     *
272
-     * @return boolean
273
-     * @throws \EE_Error
274
-     */
275
-    public function update_based_on_payments($transaction_obj_or_id, $save_txn = true)
276
-    {
277
-        EE_Error::doing_it_wrong(
278
-            __CLASS__ . '::' . __FUNCTION__,
279
-            sprintf(__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
280
-                'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'),
281
-            '4.6.0'
282
-        );
283
-        /** @type EE_Transaction_Processor $transaction_processor */
284
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
285
-
286
-        return $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment(
287
-            $this->ensure_is_obj($transaction_obj_or_id)
288
-        );
289
-    }
290
-
291
-    /**
292
-     * Deletes "junk" transactions that were probably added by bots. There might be TONS
293
-     * of these, so we are very careful to NOT select (which the models do even when deleting),
294
-     * and so we only use wpdb directly and only do minimal joins.
295
-     * Transactions are considered "junk" if they're failed for longer than a week.
296
-     * Also, there is an extra check for payments related to the transaction, because if a transaction has a payment on
297
-     * it, it's probably not junk (regardless of what status it has).
298
-     * The downside to this approach is that is addons are listening for object deletions
299
-     * on EEM_Base::delete() they won't be notified of this.  However, there is an action that plugins can hook into
300
-     * to catch these types of deletions.
301
-     *
302
-     * @global WPDB $wpdb
303
-     * @return mixed
304
-     */
305
-    public function delete_junk_transactions()
306
-    {
307
-        /** @type WPDB $wpdb */
308
-        global $wpdb;
309
-        $deleted             = false;
310
-        $time_to_leave_alone = apply_filters(
311
-            'FHEE__EEM_Transaction__delete_junk_transactions__time_to_leave_alone'
312
-            , WEEK_IN_SECONDS
313
-        );
314
-
315
-
316
-        /**
317
-         * This allows code to filter the query arguments used for retrieving the transaction IDs to delete.
318
-         * Useful for plugins that want to exclude transactions matching certain query parameters.
319
-         * The query parameters should be in the format accepted by the EEM_Base model queries.
320
-         */
321
-        $ids_query = apply_filters(
322
-            'FHEE__EEM_Transaction__delete_junk_transactions__initial_query_args',
323
-            array(
324
-                0 => array(
325
-                    'STS_ID'        => EEM_Transaction::failed_status_code,
326
-                    'Payment.PAY_ID' => array( 'IS NULL' ),
327
-                    'TXN_timestamp' => array('<', time() - $time_to_leave_alone)
328
-                )
329
-            ),
330
-            $time_to_leave_alone
331
-        );
332
-
333
-
334
-        /**
335
-         * This filter is for when code needs to filter the list of transaction ids that represent transactions
336
-         * about to be deleted based on some other criteria that isn't easily done via the query args filter.
337
-         */
338
-        $txn_ids = apply_filters(
339
-            'FHEE__EEM_Transaction__delete_junk_transactions__transaction_ids_to_delete',
340
-            EEM_Transaction::instance()->get_col($ids_query, 'TXN_ID'),
341
-            $time_to_leave_alone
342
-        );
343
-        //now that we have the ids to delete
344
-        if (! empty($txn_ids) && is_array($txn_ids)) {
345
-            // first, make sure these TXN's are removed the "ee_locked_transactions" array
346
-            EEM_Transaction::unset_locked_transactions($txn_ids);
347
-            // let's get deletin'...
348
-            // Why no wpdb->prepare?  Because the data is trusted.
349
-            // We got the ids from the original query to get them FROM
350
-            // the db (which is sanitized) so no need to prepare them again.
351
-            $query   = '
238
+			OBJECT
239
+		);
240
+	}
241
+
242
+
243
+	/**
244
+	 * Gets the current transaction given the reg_url_link, or assumes the reg_url_link is in the
245
+	 * $_REQUEST global variable. Either way, tries to find the current transaction (through
246
+	 * the registration pointed to by reg_url_link), if not returns null
247
+	 *
248
+	 * @param string $reg_url_link
249
+	 *
250
+	 * @return EE_Transaction
251
+	 */
252
+	public function get_transaction_from_reg_url_link($reg_url_link = '')
253
+	{
254
+		return $this->get_one(array(
255
+			array(
256
+				'Registration.REG_url_link' => ! empty($reg_url_link) ? $reg_url_link : EE_Registry::instance()->REQ->get('e_reg_url_link',
257
+					'')
258
+			)
259
+		));
260
+	}
261
+
262
+
263
+	/**
264
+	 * Updates the provided EE_Transaction with all the applicable payments
265
+	 * (or fetch the EE_Transaction from its ID)
266
+	 *
267
+	 * @deprecated
268
+	 *
269
+	 * @param EE_Transaction|int $transaction_obj_or_id
270
+	 * @param boolean            $save_txn whether or not to save the transaction during this function call
271
+	 *
272
+	 * @return boolean
273
+	 * @throws \EE_Error
274
+	 */
275
+	public function update_based_on_payments($transaction_obj_or_id, $save_txn = true)
276
+	{
277
+		EE_Error::doing_it_wrong(
278
+			__CLASS__ . '::' . __FUNCTION__,
279
+			sprintf(__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
280
+				'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'),
281
+			'4.6.0'
282
+		);
283
+		/** @type EE_Transaction_Processor $transaction_processor */
284
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
285
+
286
+		return $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment(
287
+			$this->ensure_is_obj($transaction_obj_or_id)
288
+		);
289
+	}
290
+
291
+	/**
292
+	 * Deletes "junk" transactions that were probably added by bots. There might be TONS
293
+	 * of these, so we are very careful to NOT select (which the models do even when deleting),
294
+	 * and so we only use wpdb directly and only do minimal joins.
295
+	 * Transactions are considered "junk" if they're failed for longer than a week.
296
+	 * Also, there is an extra check for payments related to the transaction, because if a transaction has a payment on
297
+	 * it, it's probably not junk (regardless of what status it has).
298
+	 * The downside to this approach is that is addons are listening for object deletions
299
+	 * on EEM_Base::delete() they won't be notified of this.  However, there is an action that plugins can hook into
300
+	 * to catch these types of deletions.
301
+	 *
302
+	 * @global WPDB $wpdb
303
+	 * @return mixed
304
+	 */
305
+	public function delete_junk_transactions()
306
+	{
307
+		/** @type WPDB $wpdb */
308
+		global $wpdb;
309
+		$deleted             = false;
310
+		$time_to_leave_alone = apply_filters(
311
+			'FHEE__EEM_Transaction__delete_junk_transactions__time_to_leave_alone'
312
+			, WEEK_IN_SECONDS
313
+		);
314
+
315
+
316
+		/**
317
+		 * This allows code to filter the query arguments used for retrieving the transaction IDs to delete.
318
+		 * Useful for plugins that want to exclude transactions matching certain query parameters.
319
+		 * The query parameters should be in the format accepted by the EEM_Base model queries.
320
+		 */
321
+		$ids_query = apply_filters(
322
+			'FHEE__EEM_Transaction__delete_junk_transactions__initial_query_args',
323
+			array(
324
+				0 => array(
325
+					'STS_ID'        => EEM_Transaction::failed_status_code,
326
+					'Payment.PAY_ID' => array( 'IS NULL' ),
327
+					'TXN_timestamp' => array('<', time() - $time_to_leave_alone)
328
+				)
329
+			),
330
+			$time_to_leave_alone
331
+		);
332
+
333
+
334
+		/**
335
+		 * This filter is for when code needs to filter the list of transaction ids that represent transactions
336
+		 * about to be deleted based on some other criteria that isn't easily done via the query args filter.
337
+		 */
338
+		$txn_ids = apply_filters(
339
+			'FHEE__EEM_Transaction__delete_junk_transactions__transaction_ids_to_delete',
340
+			EEM_Transaction::instance()->get_col($ids_query, 'TXN_ID'),
341
+			$time_to_leave_alone
342
+		);
343
+		//now that we have the ids to delete
344
+		if (! empty($txn_ids) && is_array($txn_ids)) {
345
+			// first, make sure these TXN's are removed the "ee_locked_transactions" array
346
+			EEM_Transaction::unset_locked_transactions($txn_ids);
347
+			// let's get deletin'...
348
+			// Why no wpdb->prepare?  Because the data is trusted.
349
+			// We got the ids from the original query to get them FROM
350
+			// the db (which is sanitized) so no need to prepare them again.
351
+			$query   = '
352 352
 				DELETE
353 353
 				FROM ' . $this->table() . '
354 354
 				WHERE
355 355
 					TXN_ID IN ( ' . implode(",", $txn_ids) . ')';
356
-            $deleted = $wpdb->query($query);
357
-        }
358
-        if ($deleted) {
359
-            /**
360
-             * Allows code to do something after the transactions have been deleted.
361
-             */
362
-            do_action('AHEE__EEM_Transaction__delete_junk_transactions__successful_deletion', $txn_ids);
363
-        }
364
-
365
-        return $deleted;
366
-    }
367
-
368
-
369
-    /**
370
-     * @param array $transaction_IDs
371
-     *
372
-     * @return bool
373
-     */
374
-    public static function unset_locked_transactions(array $transaction_IDs)
375
-    {
376
-        $locked_transactions = get_option('ee_locked_transactions', array());
377
-        $update              = false;
378
-        foreach ($transaction_IDs as $TXN_ID) {
379
-            if (isset($locked_transactions[$TXN_ID])) {
380
-                unset($locked_transactions[$TXN_ID]);
381
-                $update = true;
382
-            }
383
-        }
384
-        if ($update) {
385
-            update_option('ee_locked_transactions', $locked_transactions);
386
-        }
387
-
388
-        return $update;
389
-    }
390
-
391
-
392
-
393
-    /**
394
-     * returns an array of EE_Transaction objects whose timestamp is greater than
395
-     * the current time minus the session lifespan, which defaults to 60 minutes
396
-     *
397
-     * @return EE_Base_Class[]|EE_Transaction[]
398
-     * @throws EE_Error
399
-     * @throws InvalidArgumentException
400
-     * @throws InvalidDataTypeException
401
-     * @throws InvalidInterfaceException
402
-     */
403
-    public function get_transactions_in_progress()
404
-    {
405
-        return $this->_get_transactions_in_progress();
406
-    }
407
-
408
-
409
-
410
-    /**
411
-     * returns an array of EE_Transaction objects whose timestamp is less than
412
-     * the current time minus the session lifespan, which defaults to 60 minutes
413
-     *
414
-     * @return EE_Base_Class[]|EE_Transaction[]
415
-     * @throws EE_Error
416
-     * @throws InvalidArgumentException
417
-     * @throws InvalidDataTypeException
418
-     * @throws InvalidInterfaceException
419
-     */
420
-    public function get_transactions_not_in_progress()
421
-    {
422
-        return $this->_get_transactions_in_progress('<=');
423
-    }
424
-
425
-
426
-
427
-    /**
428
-     * @param string $comparison
429
-     * @return EE_Base_Class[]|EE_Transaction[]
430
-     * @throws EE_Error
431
-     * @throws InvalidArgumentException
432
-     * @throws InvalidDataTypeException
433
-     * @throws InvalidInterfaceException
434
-     */
435
-    private function _get_transactions_in_progress($comparison = '>=')
436
-    {
437
-        $comparison = $comparison === '>=' || $comparison === '<='
438
-            ? $comparison
439
-            : '>=';
440
-        /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
441
-        $session_lifespan = LoaderFactory::getLoader()->getShared(
442
-            'EventEspresso\core\domain\values\session\SessionLifespan'
443
-        );
444
-        return $this->get_all(
445
-            array(
446
-                array(
447
-                    'TXN_timestamp' => array(
448
-                        $comparison,
449
-                        $session_lifespan->expiration()
450
-                    ),
451
-                    'STS_ID' => array(
452
-                        '!=',
453
-                        EEM_Transaction::complete_status_code
454
-                    ),
455
-                )
456
-            )
457
-        );
458
-    }
356
+			$deleted = $wpdb->query($query);
357
+		}
358
+		if ($deleted) {
359
+			/**
360
+			 * Allows code to do something after the transactions have been deleted.
361
+			 */
362
+			do_action('AHEE__EEM_Transaction__delete_junk_transactions__successful_deletion', $txn_ids);
363
+		}
364
+
365
+		return $deleted;
366
+	}
367
+
368
+
369
+	/**
370
+	 * @param array $transaction_IDs
371
+	 *
372
+	 * @return bool
373
+	 */
374
+	public static function unset_locked_transactions(array $transaction_IDs)
375
+	{
376
+		$locked_transactions = get_option('ee_locked_transactions', array());
377
+		$update              = false;
378
+		foreach ($transaction_IDs as $TXN_ID) {
379
+			if (isset($locked_transactions[$TXN_ID])) {
380
+				unset($locked_transactions[$TXN_ID]);
381
+				$update = true;
382
+			}
383
+		}
384
+		if ($update) {
385
+			update_option('ee_locked_transactions', $locked_transactions);
386
+		}
387
+
388
+		return $update;
389
+	}
390
+
391
+
392
+
393
+	/**
394
+	 * returns an array of EE_Transaction objects whose timestamp is greater than
395
+	 * the current time minus the session lifespan, which defaults to 60 minutes
396
+	 *
397
+	 * @return EE_Base_Class[]|EE_Transaction[]
398
+	 * @throws EE_Error
399
+	 * @throws InvalidArgumentException
400
+	 * @throws InvalidDataTypeException
401
+	 * @throws InvalidInterfaceException
402
+	 */
403
+	public function get_transactions_in_progress()
404
+	{
405
+		return $this->_get_transactions_in_progress();
406
+	}
407
+
408
+
409
+
410
+	/**
411
+	 * returns an array of EE_Transaction objects whose timestamp is less than
412
+	 * the current time minus the session lifespan, which defaults to 60 minutes
413
+	 *
414
+	 * @return EE_Base_Class[]|EE_Transaction[]
415
+	 * @throws EE_Error
416
+	 * @throws InvalidArgumentException
417
+	 * @throws InvalidDataTypeException
418
+	 * @throws InvalidInterfaceException
419
+	 */
420
+	public function get_transactions_not_in_progress()
421
+	{
422
+		return $this->_get_transactions_in_progress('<=');
423
+	}
424
+
425
+
426
+
427
+	/**
428
+	 * @param string $comparison
429
+	 * @return EE_Base_Class[]|EE_Transaction[]
430
+	 * @throws EE_Error
431
+	 * @throws InvalidArgumentException
432
+	 * @throws InvalidDataTypeException
433
+	 * @throws InvalidInterfaceException
434
+	 */
435
+	private function _get_transactions_in_progress($comparison = '>=')
436
+	{
437
+		$comparison = $comparison === '>=' || $comparison === '<='
438
+			? $comparison
439
+			: '>=';
440
+		/** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
441
+		$session_lifespan = LoaderFactory::getLoader()->getShared(
442
+			'EventEspresso\core\domain\values\session\SessionLifespan'
443
+		);
444
+		return $this->get_all(
445
+			array(
446
+				array(
447
+					'TXN_timestamp' => array(
448
+						$comparison,
449
+						$session_lifespan->expiration()
450
+					),
451
+					'STS_ID' => array(
452
+						'!=',
453
+						EEM_Transaction::complete_status_code
454
+					),
455
+				)
456
+			)
457
+		);
458
+	}
459 459
 
460 460
 
461 461
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Line_Item.model.php 4 patches
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -4,7 +4,9 @@
 block discarded – undo
4 4
 use EventEspresso\core\exceptions\InvalidInterfaceException;
5 5
 use EventEspresso\core\services\loaders\LoaderFactory;
6 6
 
7
-if (!defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');
7
+if (!defined('EVENT_ESPRESSO_VERSION')) {
8
+	exit('No direct script access allowed');
9
+}
8 10
 
9 11
 /**
10 12
  * Event Espresso
Please login to merge, or discard this patch.
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -416,7 +416,7 @@
 block discarded – undo
416 416
      * If $expired is set to true, then only line items for expired sessions will be returned.
417 417
      * If $expired is set to false, then only line items for active sessions will be returned.
418 418
      *
419
-     * @param null $expired
419
+     * @param boolean $expired
420 420
      * @return EE_Base_Class[]|EE_Line_Item[]
421 421
      * @throws EE_Error
422 422
      * @throws InvalidArgumentException
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 use EventEspresso\core\exceptions\InvalidInterfaceException;
5 5
 use EventEspresso\core\services\loaders\LoaderFactory;
6 6
 
7
-if (!defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');
7
+if ( ! defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');
8 8
 
9 9
 /**
10 10
  * Event Espresso
@@ -211,8 +211,8 @@  discard block
 block discarded – undo
211 211
         );
212 212
         $query = $wpdb->prepare(
213 213
             'DELETE li
214
-				FROM ' . $this->table() . ' li
215
-				LEFT JOIN ' . EEM_Transaction::instance()->table() . ' t ON li.TXN_ID = t.TXN_ID
214
+				FROM ' . $this->table().' li
215
+				LEFT JOIN ' . EEM_Transaction::instance()->table().' t ON li.TXN_ID = t.TXN_ID
216 216
 				WHERE t.TXN_ID IS NULL AND li.LIN_timestamp < %s',
217 217
             // use GMT time because that's what TXN_timestamps are in
218 218
             date('Y-m-d H:i:s', time() - $time_to_leave_alone)
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
         $query_params = array(
254 254
             'OBJ_type' => $OBJ_type,
255 255
             // if incoming $OBJ_IDs is an array, then make sure it is formatted correctly for the query
256
-            'OBJ_ID' => is_array($OBJ_IDs) && !isset($OBJ_IDs['IN']) ? array('IN', $OBJ_IDs) : $OBJ_IDs
256
+            'OBJ_ID' => is_array($OBJ_IDs) && ! isset($OBJ_IDs['IN']) ? array('IN', $OBJ_IDs) : $OBJ_IDs
257 257
         );
258 258
         if ($TXN_ID) {
259 259
             $query_params['TXN_ID'] = $TXN_ID;
@@ -456,7 +456,7 @@  discard block
 block discarded – undo
456 456
      */
457 457
     public function getTicketLineItemsForExpiredCarts($timestamp = 0)
458 458
     {
459
-        if(! absint($timestamp)) {
459
+        if ( ! absint($timestamp)) {
460 460
             /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
461 461
             $session_lifespan = LoaderFactory::getLoader()->getShared(
462 462
                 'EventEspresso\core\domain\values\session\SessionLifespan'
Please login to merge, or discard this patch.
Indentation   +436 added lines, -436 removed lines patch added patch discarded remove patch
@@ -47,444 +47,444 @@
 block discarded – undo
47 47
 class EEM_Line_Item extends EEM_Base
48 48
 {
49 49
 
50
-    /**
51
-     * Tax sub-total is just the total of all the taxes, which should be children
52
-     * of this line item. There should only ever be one tax sub-total, and it should
53
-     * be a direct child of. Its quantity and LIN_unit_price = 1.
54
-     */
55
-    const type_tax_sub_total = 'tax-sub-total';
56
-
57
-    /**
58
-     * Tax line items indicate a tax applied to all the taxable line items.
59
-     * Should not have any children line items. Its LIN_unit_price = 0. Its LIN_percent is a percent, not a decimal
60
-     * (eg 10% tax = 10, not 0.1). Its LIN_total = LIN_unit_price * pre-tax-total. Quantity = 1.
61
-     */
62
-    const type_tax = 'tax';
63
-
64
-    /**
65
-     * Indicating individual items purchased, or discounts or surcharges.
66
-     * The sum of all the regular line items  plus the tax items should equal
67
-     * the grand total.
68
-     * Possible children are sub-line-items and cancellations.
69
-     * For flat items, LIN_unit_price * LIN_quantity = LIN_total. Its LIN_total is the sum of all the children
70
-     * LIN_totals. Its LIN_percent = 0.
71
-     * For percent items, its LIN_unit_price = 0. Its LIN_percent is a percent, not a decimal (eg 10% = 10, not 0.1).
72
-     * Its LIN_total is LIN_percent / 100 * sum of lower-priority sibling line items. Quantity = 1.
73
-     */
74
-    const type_line_item = 'line-item';
75
-
76
-    /**
77
-     * Line item indicating all the factors that make a single line item.
78
-     * Sub-line items should have NO children line items.
79
-     * For flat sub-items, their quantity should match their parent item, their LIN_unit_price should be this sub-item's
80
-     * contribution towards the price of ONE of their parent items, and its LIN_total should be
81
-     *  = LIN_quantity * LIN_unit_price. Its LIN_percent = 0.
82
-     * For percent sub-items, the quantity should be 1, LIN_unit_price should be 0, and its LIN_total should
83
-     * = LIN_percent / 100 * sum of lower-priority sibling line items..
84
-     */
85
-    const type_sub_line_item = 'sub-item';
86
-
87
-    /**
88
-     * Line item indicating a sub-total (eg total for an event, or pre-tax subtotal).
89
-     * Direct children should be event subtotals.
90
-     * Should have quantity of 1, and a LIN_total and LIN_unit_price of the sum of all its sub-items' LIN_totals.
91
-     *
92
-     */
93
-    const type_sub_total = 'sub-total';
94
-
95
-    /**
96
-     * Line item for the grand total of an order. Its direct children
97
-     * should be tax subtotals and (pre-tax) subtotals, and possibly a regular line item
98
-     * indicating a transaction-wide discount/surcharge. Should have a quantity of 1, a LIN_total and LIN_unit_price of
99
-     * the entire order's mount.
100
-     */
101
-    const type_total = 'total';
102
-
103
-    /**
104
-     * When a line item is cancelled, a sub-line-item of type 'cancellation'
105
-     * should be created, indicating the quantity that were cancelled
106
-     * (because a line item could have a quantity of 1, and its cancellation item
107
-     * could be for 3, indicating that originally 4 were purchased, but 3 have been
108
-     * cancelled, and only one remains).
109
-     * When items are refunded, a cancellation line item should be made, which points
110
-     * to teh payment model object which actually refunded the payment.
111
-     * Cancellations should NOT have any children line items; the should NOT affect
112
-     * any calculations, and are only meant as a record that cancellations have occurred.
113
-     * Their LIN_percent should be 0.
114
-     */
115
-    const type_cancellation = 'cancellation';
116
-
117
-    // private instance of the EEM_Line_Item object
118
-    protected static $_instance = NULL;
119
-
120
-
121
-    /**
122
-     *        private constructor to prevent direct creation
123
-     * @Constructor
124
-     * @access protected
125
-     * @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)
126
-     * @return \EEM_Line_Item
127
-     */
128
-    protected function __construct($timezone)
129
-    {
130
-        $this->singular_item = __('Line Item', 'event_espresso');
131
-        $this->plural_item = __('Line Items', 'event_espresso');
132
-
133
-        $this->_tables = array(
134
-            'Line_Item' => new EE_Primary_Table('esp_line_item', 'LIN_ID')
135
-        );
136
-        $line_items_can_be_for = apply_filters('FHEE__EEM_Line_Item__line_items_can_be_for', array('Ticket', 'Price', 'Event'));
137
-        $this->_fields = array(
138
-            'Line_Item' => array(
139
-                'LIN_ID' => new EE_Primary_Key_Int_Field('LIN_ID', __("ID", "event_espresso")),
140
-                'LIN_code' => new EE_Slug_Field('LIN_code', __("Code for index into Cart", "event_espresso"), TRUE),
141
-                'TXN_ID' => new EE_Foreign_Key_Int_Field('TXN_ID', __("Transaction ID", "event_espresso"), TRUE, NULL, 'Transaction'),
142
-                'LIN_name' => new EE_Full_HTML_Field('LIN_name', __("Line Item Name", "event_espresso"), FALSE, ''),
143
-                'LIN_desc' => new EE_Full_HTML_Field('LIN_desc', __("Line Item Description", "event_espresso"), TRUE),
144
-                'LIN_unit_price' => new EE_Money_Field('LIN_unit_price', __("Unit Price", "event_espresso"), FALSE, 0),
145
-                'LIN_percent' => new EE_Float_Field('LIN_percent', __("Percent", "event_espresso"), FALSE, 0),
146
-                'LIN_is_taxable' => new EE_Boolean_Field('LIN_is_taxable', __("Taxable", "event_espresso"), FALSE, FALSE),
147
-                'LIN_order' => new EE_Integer_Field('LIN_order', __("Order of Application towards total of parent", "event_espresso"), FALSE, 1),
148
-                'LIN_total' => new EE_Money_Field('LIN_total', __("Total (unit price x quantity)", "event_espresso"), FALSE, 0),
149
-                'LIN_quantity' => new EE_Integer_Field('LIN_quantity', __("Quantity", "event_espresso"), TRUE, 1),
150
-                'LIN_parent' => new EE_Integer_Field('LIN_parent', __("Parent ID (this item goes towards that Line Item's total)", "event_espresso"), TRUE, NULL),
151
-                'LIN_type' => new EE_Enum_Text_Field('LIN_type', __("Type", "event_espresso"), FALSE, 'line-item', array(
152
-                        self::type_line_item => __("Line Item", "event_espresso"),
153
-                        self::type_sub_line_item => __("Sub-Item", "event_espresso"),
154
-                        self::type_sub_total => __("Subtotal", "event_espresso"),
155
-                        self::type_tax_sub_total => __("Tax Subtotal", "event_espresso"),
156
-                        self::type_tax => __("Tax", "event_espresso"),
157
-                        self::type_total => __("Total", "event_espresso"),
158
-                        self::type_cancellation => __('Cancellation', 'event_espresso')
159
-                    )
160
-                ),
161
-                'OBJ_ID' => new EE_Foreign_Key_Int_Field('OBJ_ID', __('ID of Item purchased.', 'event_espresso'), TRUE, NULL, $line_items_can_be_for),
162
-                'OBJ_type' => new EE_Any_Foreign_Model_Name_Field('OBJ_type', __("Model Name this Line Item is for", "event_espresso"), TRUE, NULL, $line_items_can_be_for),
163
-                'LIN_timestamp' => new EE_Datetime_Field('LIN_timestamp', __('When the line item was created', 'event_espresso'), false, EE_Datetime_Field::now, $timezone),
164
-            )
165
-        );
166
-        $this->_model_relations = array(
167
-            'Transaction' => new EE_Belongs_To_Relation(),
168
-            'Ticket' => new EE_Belongs_To_Any_Relation(),
169
-            'Price' => new EE_Belongs_To_Any_Relation(),
170
-            'Event' => new EE_Belongs_To_Any_Relation()
171
-        );
172
-        $this->_model_chain_to_wp_user = 'Transaction.Registration.Event';
173
-        $this->_caps_slug = 'transactions';
174
-        parent::__construct($timezone);
175
-    }
176
-
177
-
178
-    /**
179
-     * Gets all the line items for this transaction of the given type
180
-     * @param string $line_item_type like one of EEM_Line_Item::type_*
181
-     * @param EE_Transaction|int $transaction
182
-     * @return EE_Line_Item[]
183
-     */
184
-    public function get_all_of_type_for_transaction($line_item_type, $transaction)
185
-    {
186
-        $transaction = EEM_Transaction::instance()->ensure_is_ID($transaction);
187
-        return $this->get_all(array(array(
188
-            'LIN_type' => $line_item_type,
189
-            'TXN_ID' => $transaction
190
-        )));
191
-    }
192
-
193
-
194
-    /**
195
-     * Gets all line items unrelated to tickets that are normal line items
196
-     * (eg shipping, promotions, and miscellaneous other stuff should probably fit in this category)
197
-     * @param EE_Transaction|int $transaction
198
-     * @return EE_Line_Item[]
199
-     */
200
-    public function get_all_non_ticket_line_items_for_transaction($transaction)
201
-    {
202
-        $transaction = EEM_Transaction::instance()->ensure_is_ID($transaction);
203
-        return $this->get_all(array(array(
204
-            'LIN_type' => self::type_line_item,
205
-            'TXN_ID' => $transaction,
206
-            'OR' => array(
207
-                'OBJ_type*notticket' => array('!=', 'Ticket'),
208
-                'OBJ_type*null' => array('IS_NULL'))
209
-        )));
210
-    }
211
-
212
-    /**
213
-     * Deletes line items with no transaction who have passed the transaction cutoff time.
214
-     * This needs to be very efficient
215
-     * because if there are spam bots afoot there will be LOTS of line items
216
-     * @return int count of how many deleted
217
-     */
218
-    public function delete_line_items_with_no_transaction()
219
-    {
220
-        /** @type WPDB $wpdb */
221
-        global $wpdb;
222
-        $time_to_leave_alone = apply_filters(
223
-            'FHEE__EEM_Line_Item__delete_line_items_with_no_transaction__time_to_leave_alone', WEEK_IN_SECONDS
224
-        );
225
-        $query = $wpdb->prepare(
226
-            'DELETE li
50
+	/**
51
+	 * Tax sub-total is just the total of all the taxes, which should be children
52
+	 * of this line item. There should only ever be one tax sub-total, and it should
53
+	 * be a direct child of. Its quantity and LIN_unit_price = 1.
54
+	 */
55
+	const type_tax_sub_total = 'tax-sub-total';
56
+
57
+	/**
58
+	 * Tax line items indicate a tax applied to all the taxable line items.
59
+	 * Should not have any children line items. Its LIN_unit_price = 0. Its LIN_percent is a percent, not a decimal
60
+	 * (eg 10% tax = 10, not 0.1). Its LIN_total = LIN_unit_price * pre-tax-total. Quantity = 1.
61
+	 */
62
+	const type_tax = 'tax';
63
+
64
+	/**
65
+	 * Indicating individual items purchased, or discounts or surcharges.
66
+	 * The sum of all the regular line items  plus the tax items should equal
67
+	 * the grand total.
68
+	 * Possible children are sub-line-items and cancellations.
69
+	 * For flat items, LIN_unit_price * LIN_quantity = LIN_total. Its LIN_total is the sum of all the children
70
+	 * LIN_totals. Its LIN_percent = 0.
71
+	 * For percent items, its LIN_unit_price = 0. Its LIN_percent is a percent, not a decimal (eg 10% = 10, not 0.1).
72
+	 * Its LIN_total is LIN_percent / 100 * sum of lower-priority sibling line items. Quantity = 1.
73
+	 */
74
+	const type_line_item = 'line-item';
75
+
76
+	/**
77
+	 * Line item indicating all the factors that make a single line item.
78
+	 * Sub-line items should have NO children line items.
79
+	 * For flat sub-items, their quantity should match their parent item, their LIN_unit_price should be this sub-item's
80
+	 * contribution towards the price of ONE of their parent items, and its LIN_total should be
81
+	 *  = LIN_quantity * LIN_unit_price. Its LIN_percent = 0.
82
+	 * For percent sub-items, the quantity should be 1, LIN_unit_price should be 0, and its LIN_total should
83
+	 * = LIN_percent / 100 * sum of lower-priority sibling line items..
84
+	 */
85
+	const type_sub_line_item = 'sub-item';
86
+
87
+	/**
88
+	 * Line item indicating a sub-total (eg total for an event, or pre-tax subtotal).
89
+	 * Direct children should be event subtotals.
90
+	 * Should have quantity of 1, and a LIN_total and LIN_unit_price of the sum of all its sub-items' LIN_totals.
91
+	 *
92
+	 */
93
+	const type_sub_total = 'sub-total';
94
+
95
+	/**
96
+	 * Line item for the grand total of an order. Its direct children
97
+	 * should be tax subtotals and (pre-tax) subtotals, and possibly a regular line item
98
+	 * indicating a transaction-wide discount/surcharge. Should have a quantity of 1, a LIN_total and LIN_unit_price of
99
+	 * the entire order's mount.
100
+	 */
101
+	const type_total = 'total';
102
+
103
+	/**
104
+	 * When a line item is cancelled, a sub-line-item of type 'cancellation'
105
+	 * should be created, indicating the quantity that were cancelled
106
+	 * (because a line item could have a quantity of 1, and its cancellation item
107
+	 * could be for 3, indicating that originally 4 were purchased, but 3 have been
108
+	 * cancelled, and only one remains).
109
+	 * When items are refunded, a cancellation line item should be made, which points
110
+	 * to teh payment model object which actually refunded the payment.
111
+	 * Cancellations should NOT have any children line items; the should NOT affect
112
+	 * any calculations, and are only meant as a record that cancellations have occurred.
113
+	 * Their LIN_percent should be 0.
114
+	 */
115
+	const type_cancellation = 'cancellation';
116
+
117
+	// private instance of the EEM_Line_Item object
118
+	protected static $_instance = NULL;
119
+
120
+
121
+	/**
122
+	 *        private constructor to prevent direct creation
123
+	 * @Constructor
124
+	 * @access protected
125
+	 * @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)
126
+	 * @return \EEM_Line_Item
127
+	 */
128
+	protected function __construct($timezone)
129
+	{
130
+		$this->singular_item = __('Line Item', 'event_espresso');
131
+		$this->plural_item = __('Line Items', 'event_espresso');
132
+
133
+		$this->_tables = array(
134
+			'Line_Item' => new EE_Primary_Table('esp_line_item', 'LIN_ID')
135
+		);
136
+		$line_items_can_be_for = apply_filters('FHEE__EEM_Line_Item__line_items_can_be_for', array('Ticket', 'Price', 'Event'));
137
+		$this->_fields = array(
138
+			'Line_Item' => array(
139
+				'LIN_ID' => new EE_Primary_Key_Int_Field('LIN_ID', __("ID", "event_espresso")),
140
+				'LIN_code' => new EE_Slug_Field('LIN_code', __("Code for index into Cart", "event_espresso"), TRUE),
141
+				'TXN_ID' => new EE_Foreign_Key_Int_Field('TXN_ID', __("Transaction ID", "event_espresso"), TRUE, NULL, 'Transaction'),
142
+				'LIN_name' => new EE_Full_HTML_Field('LIN_name', __("Line Item Name", "event_espresso"), FALSE, ''),
143
+				'LIN_desc' => new EE_Full_HTML_Field('LIN_desc', __("Line Item Description", "event_espresso"), TRUE),
144
+				'LIN_unit_price' => new EE_Money_Field('LIN_unit_price', __("Unit Price", "event_espresso"), FALSE, 0),
145
+				'LIN_percent' => new EE_Float_Field('LIN_percent', __("Percent", "event_espresso"), FALSE, 0),
146
+				'LIN_is_taxable' => new EE_Boolean_Field('LIN_is_taxable', __("Taxable", "event_espresso"), FALSE, FALSE),
147
+				'LIN_order' => new EE_Integer_Field('LIN_order', __("Order of Application towards total of parent", "event_espresso"), FALSE, 1),
148
+				'LIN_total' => new EE_Money_Field('LIN_total', __("Total (unit price x quantity)", "event_espresso"), FALSE, 0),
149
+				'LIN_quantity' => new EE_Integer_Field('LIN_quantity', __("Quantity", "event_espresso"), TRUE, 1),
150
+				'LIN_parent' => new EE_Integer_Field('LIN_parent', __("Parent ID (this item goes towards that Line Item's total)", "event_espresso"), TRUE, NULL),
151
+				'LIN_type' => new EE_Enum_Text_Field('LIN_type', __("Type", "event_espresso"), FALSE, 'line-item', array(
152
+						self::type_line_item => __("Line Item", "event_espresso"),
153
+						self::type_sub_line_item => __("Sub-Item", "event_espresso"),
154
+						self::type_sub_total => __("Subtotal", "event_espresso"),
155
+						self::type_tax_sub_total => __("Tax Subtotal", "event_espresso"),
156
+						self::type_tax => __("Tax", "event_espresso"),
157
+						self::type_total => __("Total", "event_espresso"),
158
+						self::type_cancellation => __('Cancellation', 'event_espresso')
159
+					)
160
+				),
161
+				'OBJ_ID' => new EE_Foreign_Key_Int_Field('OBJ_ID', __('ID of Item purchased.', 'event_espresso'), TRUE, NULL, $line_items_can_be_for),
162
+				'OBJ_type' => new EE_Any_Foreign_Model_Name_Field('OBJ_type', __("Model Name this Line Item is for", "event_espresso"), TRUE, NULL, $line_items_can_be_for),
163
+				'LIN_timestamp' => new EE_Datetime_Field('LIN_timestamp', __('When the line item was created', 'event_espresso'), false, EE_Datetime_Field::now, $timezone),
164
+			)
165
+		);
166
+		$this->_model_relations = array(
167
+			'Transaction' => new EE_Belongs_To_Relation(),
168
+			'Ticket' => new EE_Belongs_To_Any_Relation(),
169
+			'Price' => new EE_Belongs_To_Any_Relation(),
170
+			'Event' => new EE_Belongs_To_Any_Relation()
171
+		);
172
+		$this->_model_chain_to_wp_user = 'Transaction.Registration.Event';
173
+		$this->_caps_slug = 'transactions';
174
+		parent::__construct($timezone);
175
+	}
176
+
177
+
178
+	/**
179
+	 * Gets all the line items for this transaction of the given type
180
+	 * @param string $line_item_type like one of EEM_Line_Item::type_*
181
+	 * @param EE_Transaction|int $transaction
182
+	 * @return EE_Line_Item[]
183
+	 */
184
+	public function get_all_of_type_for_transaction($line_item_type, $transaction)
185
+	{
186
+		$transaction = EEM_Transaction::instance()->ensure_is_ID($transaction);
187
+		return $this->get_all(array(array(
188
+			'LIN_type' => $line_item_type,
189
+			'TXN_ID' => $transaction
190
+		)));
191
+	}
192
+
193
+
194
+	/**
195
+	 * Gets all line items unrelated to tickets that are normal line items
196
+	 * (eg shipping, promotions, and miscellaneous other stuff should probably fit in this category)
197
+	 * @param EE_Transaction|int $transaction
198
+	 * @return EE_Line_Item[]
199
+	 */
200
+	public function get_all_non_ticket_line_items_for_transaction($transaction)
201
+	{
202
+		$transaction = EEM_Transaction::instance()->ensure_is_ID($transaction);
203
+		return $this->get_all(array(array(
204
+			'LIN_type' => self::type_line_item,
205
+			'TXN_ID' => $transaction,
206
+			'OR' => array(
207
+				'OBJ_type*notticket' => array('!=', 'Ticket'),
208
+				'OBJ_type*null' => array('IS_NULL'))
209
+		)));
210
+	}
211
+
212
+	/**
213
+	 * Deletes line items with no transaction who have passed the transaction cutoff time.
214
+	 * This needs to be very efficient
215
+	 * because if there are spam bots afoot there will be LOTS of line items
216
+	 * @return int count of how many deleted
217
+	 */
218
+	public function delete_line_items_with_no_transaction()
219
+	{
220
+		/** @type WPDB $wpdb */
221
+		global $wpdb;
222
+		$time_to_leave_alone = apply_filters(
223
+			'FHEE__EEM_Line_Item__delete_line_items_with_no_transaction__time_to_leave_alone', WEEK_IN_SECONDS
224
+		);
225
+		$query = $wpdb->prepare(
226
+			'DELETE li
227 227
 				FROM ' . $this->table() . ' li
228 228
 				LEFT JOIN ' . EEM_Transaction::instance()->table() . ' t ON li.TXN_ID = t.TXN_ID
229 229
 				WHERE t.TXN_ID IS NULL AND li.LIN_timestamp < %s',
230
-            // use GMT time because that's what TXN_timestamps are in
231
-            date('Y-m-d H:i:s', time() - $time_to_leave_alone)
232
-        );
233
-        return $wpdb->query($query);
234
-    }
235
-
236
-
237
-    /**
238
-     * get_line_item_for_transaction_object
239
-     * Gets a transaction's line item record for a specific object such as a EE_Event or EE_Ticket
240
-     *
241
-     * @param int $TXN_ID
242
-     * @param \EE_Base_Class $object
243
-     * @return EE_Line_Item[]
244
-     */
245
-    public function get_line_item_for_transaction_object($TXN_ID, EE_Base_Class $object)
246
-    {
247
-        return $this->get_all(array(array(
248
-            'TXN_ID' => $TXN_ID,
249
-            'OBJ_type' => str_replace('EE_', '', get_class($object)),
250
-            'OBJ_ID' => $object->ID()
251
-        )));
252
-    }
253
-
254
-
255
-    /**
256
-     * get_object_line_items_for_transaction
257
-     * Gets all of the the object line items for a transaction, based on an object type plus an array of object IDs
258
-     *
259
-     * @param int $TXN_ID
260
-     * @param string $OBJ_type
261
-     * @param array $OBJ_IDs
262
-     * @return EE_Line_Item[]
263
-     */
264
-    public function get_object_line_items_for_transaction($TXN_ID, $OBJ_type = 'Event', $OBJ_IDs = array())
265
-    {
266
-        $query_params = array(
267
-            'OBJ_type' => $OBJ_type,
268
-            // if incoming $OBJ_IDs is an array, then make sure it is formatted correctly for the query
269
-            'OBJ_ID' => is_array($OBJ_IDs) && !isset($OBJ_IDs['IN']) ? array('IN', $OBJ_IDs) : $OBJ_IDs
270
-        );
271
-        if ($TXN_ID) {
272
-            $query_params['TXN_ID'] = $TXN_ID;
273
-        }
274
-        return $this->get_all(array($query_params));
275
-    }
276
-
277
-
278
-    /**
279
-     * get_all_ticket_line_items_for_transaction
280
-     *
281
-     * @param EE_Transaction $transaction
282
-     * @return EE_Line_Item[]
283
-     */
284
-    public function get_all_ticket_line_items_for_transaction(EE_Transaction $transaction)
285
-    {
286
-        return $this->get_all(array(
287
-            array(
288
-                'TXN_ID' => $transaction->ID(),
289
-                'OBJ_type' => 'Ticket',
290
-            )
291
-        ));
292
-    }
293
-
294
-
295
-    /**
296
-     * get_ticket_line_item_for_transaction
297
-     *
298
-     * @param int $TXN_ID
299
-     * @param int $TKT_ID
300
-     * @return \EE_Line_Item
301
-     */
302
-    public function get_ticket_line_item_for_transaction($TXN_ID, $TKT_ID)
303
-    {
304
-        return $this->get_one(array(
305
-            array(
306
-                'TXN_ID' => EEM_Transaction::instance()->ensure_is_ID($TXN_ID),
307
-                'OBJ_ID' => $TKT_ID,
308
-                'OBJ_type' => 'Ticket',
309
-            )
310
-        ));
311
-    }
312
-
313
-
314
-    /**
315
-     * get_existing_promotion_line_item
316
-     * searches the cart for existing line items for the specified promotion
317
-     *
318
-     * @since   1.0.0
319
-     *
320
-     * @param EE_Line_Item $parent_line_item
321
-     * @param EE_Promotion $promotion
322
-     * @return EE_Line_Item
323
-     */
324
-    public function get_existing_promotion_line_item(EE_Line_Item $parent_line_item, EE_Promotion $promotion)
325
-    {
326
-        return $this->get_one(array(
327
-            array(
328
-                'TXN_ID' => $parent_line_item->TXN_ID(),
329
-                'LIN_parent' => $parent_line_item->ID(),
330
-                'OBJ_type' => 'Promotion',
331
-                'OBJ_ID' => $promotion->ID()
332
-            )
333
-        ));
334
-    }
335
-
336
-
337
-    /**
338
-     * get_all_promotion_line_items
339
-     * searches the cart for any and all existing promotion line items
340
-     *
341
-     * @since   1.0.0
342
-     *
343
-     * @param EE_Line_Item $parent_line_item
344
-     * @return EE_Line_Item[]
345
-     */
346
-    public function get_all_promotion_line_items(EE_Line_Item $parent_line_item)
347
-    {
348
-        return $this->get_all(array(
349
-            array(
350
-                'TXN_ID' => $parent_line_item->TXN_ID(),
351
-                'LIN_parent' => $parent_line_item->ID(),
352
-                'OBJ_type' => 'Promotion'
353
-            )
354
-        ));
355
-    }
356
-
357
-    /**
358
-     * Gets the registration's corresponding line item.
359
-     * Note: basically does NOT support having multiple line items for a single ticket,
360
-     * which would happen if some of the registrations had a price modifier while others didn't.
361
-     * In order to support that, we'd probably need a LIN_ID on registrations or something.
362
-     * @param EE_Registration $registration
363
-     * @return EE_Line_ITem
364
-     */
365
-    public function get_line_item_for_registration(EE_Registration $registration)
366
-    {
367
-        return $this->get_one($this->line_item_for_registration_query_params($registration));
368
-    }
369
-
370
-    /**
371
-     * Gets the query params used to retrieve a specific line item for the given registration
372
-     * @param EE_Registration $registration
373
-     * @param array $original_query_params any extra query params you'd like to be merged with
374
-     * @return array like EEM_Base::get_all()'s $query_params
375
-     */
376
-    public function line_item_for_registration_query_params(EE_Registration $registration, $original_query_params = array())
377
-    {
378
-        return array_replace_recursive($original_query_params, array(
379
-            array(
380
-                'OBJ_ID' => $registration->ticket_ID(),
381
-                'OBJ_type' => 'Ticket',
382
-                'TXN_ID' => $registration->transaction_ID()
383
-            )
384
-        ));
385
-    }
386
-
387
-
388
-    /**
389
-     * @return EE_Base_Class[]|EE_Line_Item[]
390
-     * @throws InvalidInterfaceException
391
-     * @throws InvalidDataTypeException
392
-     * @throws EE_Error
393
-     * @throws InvalidArgumentException
394
-     */
395
-    public function get_total_line_items_with_no_transaction()
396
-    {
397
-        return $this->get_total_line_items_for_carts();
398
-    }
399
-
400
-
401
-    /**
402
-     * @return EE_Base_Class[]|EE_Line_Item[]
403
-     * @throws InvalidInterfaceException
404
-     * @throws InvalidDataTypeException
405
-     * @throws EE_Error
406
-     * @throws InvalidArgumentException
407
-     */
408
-    public function get_total_line_items_for_active_carts()
409
-    {
410
-        return $this->get_total_line_items_for_carts(false);
411
-    }
412
-
413
-
414
-    /**
415
-     * @return EE_Base_Class[]|EE_Line_Item[]
416
-     * @throws InvalidInterfaceException
417
-     * @throws InvalidDataTypeException
418
-     * @throws EE_Error
419
-     * @throws InvalidArgumentException
420
-     */
421
-    public function get_total_line_items_for_expired_carts()
422
-    {
423
-        return $this->get_total_line_items_for_carts(true);
424
-    }
425
-
426
-
427
-    /**
428
-     * Returns an array of grand total line items where the TXN_ID is 0.
429
-     * If $expired is set to true, then only line items for expired sessions will be returned.
430
-     * If $expired is set to false, then only line items for active sessions will be returned.
431
-     *
432
-     * @param null $expired
433
-     * @return EE_Base_Class[]|EE_Line_Item[]
434
-     * @throws EE_Error
435
-     * @throws InvalidArgumentException
436
-     * @throws InvalidDataTypeException
437
-     * @throws InvalidInterfaceException
438
-     */
439
-    private function get_total_line_items_for_carts($expired = null)
440
-    {
441
-        $where_params = array(
442
-            'TXN_ID' => 0,
443
-            'LIN_type' => 'total',
444
-        );
445
-        if ($expired !== null) {
446
-            /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
447
-            $session_lifespan = LoaderFactory::getLoader()->getShared(
448
-                'EventEspresso\core\domain\values\session\SessionLifespan'
449
-            );
450
-            $where_params['LIN_timestamp'] = array(
451
-                $expired ? '<=' : '>',
452
-                $session_lifespan->expiration(),
453
-            );
454
-        }
455
-        return $this->get_all(array($where_params));
456
-    }
457
-
458
-
459
-    /**
460
-     * Returns an array of ticket total line items where the TXN_ID is 0
461
-     * AND the timestamp is older than the session lifespan.
462
-     *
463
-     * @param int $timestamp
464
-     * @return EE_Base_Class[]|EE_Line_Item[]
465
-     * @throws EE_Error
466
-     * @throws InvalidArgumentException
467
-     * @throws InvalidDataTypeException
468
-     * @throws InvalidInterfaceException
469
-     */
470
-    public function getTicketLineItemsForExpiredCarts($timestamp = 0)
471
-    {
472
-        if(! absint($timestamp)) {
473
-            /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
474
-            $session_lifespan = LoaderFactory::getLoader()->getShared(
475
-                'EventEspresso\core\domain\values\session\SessionLifespan'
476
-            );
477
-            $timestamp = $session_lifespan->expiration();
478
-        }
479
-        return $this->get_all(
480
-            array(
481
-                array(
482
-                    'TXN_ID'        => 0,
483
-                    'OBJ_type'      => 'Ticket',
484
-                    'LIN_timestamp' => array('<=', $timestamp),
485
-                )
486
-            )
487
-        );
488
-    }
230
+			// use GMT time because that's what TXN_timestamps are in
231
+			date('Y-m-d H:i:s', time() - $time_to_leave_alone)
232
+		);
233
+		return $wpdb->query($query);
234
+	}
235
+
236
+
237
+	/**
238
+	 * get_line_item_for_transaction_object
239
+	 * Gets a transaction's line item record for a specific object such as a EE_Event or EE_Ticket
240
+	 *
241
+	 * @param int $TXN_ID
242
+	 * @param \EE_Base_Class $object
243
+	 * @return EE_Line_Item[]
244
+	 */
245
+	public function get_line_item_for_transaction_object($TXN_ID, EE_Base_Class $object)
246
+	{
247
+		return $this->get_all(array(array(
248
+			'TXN_ID' => $TXN_ID,
249
+			'OBJ_type' => str_replace('EE_', '', get_class($object)),
250
+			'OBJ_ID' => $object->ID()
251
+		)));
252
+	}
253
+
254
+
255
+	/**
256
+	 * get_object_line_items_for_transaction
257
+	 * Gets all of the the object line items for a transaction, based on an object type plus an array of object IDs
258
+	 *
259
+	 * @param int $TXN_ID
260
+	 * @param string $OBJ_type
261
+	 * @param array $OBJ_IDs
262
+	 * @return EE_Line_Item[]
263
+	 */
264
+	public function get_object_line_items_for_transaction($TXN_ID, $OBJ_type = 'Event', $OBJ_IDs = array())
265
+	{
266
+		$query_params = array(
267
+			'OBJ_type' => $OBJ_type,
268
+			// if incoming $OBJ_IDs is an array, then make sure it is formatted correctly for the query
269
+			'OBJ_ID' => is_array($OBJ_IDs) && !isset($OBJ_IDs['IN']) ? array('IN', $OBJ_IDs) : $OBJ_IDs
270
+		);
271
+		if ($TXN_ID) {
272
+			$query_params['TXN_ID'] = $TXN_ID;
273
+		}
274
+		return $this->get_all(array($query_params));
275
+	}
276
+
277
+
278
+	/**
279
+	 * get_all_ticket_line_items_for_transaction
280
+	 *
281
+	 * @param EE_Transaction $transaction
282
+	 * @return EE_Line_Item[]
283
+	 */
284
+	public function get_all_ticket_line_items_for_transaction(EE_Transaction $transaction)
285
+	{
286
+		return $this->get_all(array(
287
+			array(
288
+				'TXN_ID' => $transaction->ID(),
289
+				'OBJ_type' => 'Ticket',
290
+			)
291
+		));
292
+	}
293
+
294
+
295
+	/**
296
+	 * get_ticket_line_item_for_transaction
297
+	 *
298
+	 * @param int $TXN_ID
299
+	 * @param int $TKT_ID
300
+	 * @return \EE_Line_Item
301
+	 */
302
+	public function get_ticket_line_item_for_transaction($TXN_ID, $TKT_ID)
303
+	{
304
+		return $this->get_one(array(
305
+			array(
306
+				'TXN_ID' => EEM_Transaction::instance()->ensure_is_ID($TXN_ID),
307
+				'OBJ_ID' => $TKT_ID,
308
+				'OBJ_type' => 'Ticket',
309
+			)
310
+		));
311
+	}
312
+
313
+
314
+	/**
315
+	 * get_existing_promotion_line_item
316
+	 * searches the cart for existing line items for the specified promotion
317
+	 *
318
+	 * @since   1.0.0
319
+	 *
320
+	 * @param EE_Line_Item $parent_line_item
321
+	 * @param EE_Promotion $promotion
322
+	 * @return EE_Line_Item
323
+	 */
324
+	public function get_existing_promotion_line_item(EE_Line_Item $parent_line_item, EE_Promotion $promotion)
325
+	{
326
+		return $this->get_one(array(
327
+			array(
328
+				'TXN_ID' => $parent_line_item->TXN_ID(),
329
+				'LIN_parent' => $parent_line_item->ID(),
330
+				'OBJ_type' => 'Promotion',
331
+				'OBJ_ID' => $promotion->ID()
332
+			)
333
+		));
334
+	}
335
+
336
+
337
+	/**
338
+	 * get_all_promotion_line_items
339
+	 * searches the cart for any and all existing promotion line items
340
+	 *
341
+	 * @since   1.0.0
342
+	 *
343
+	 * @param EE_Line_Item $parent_line_item
344
+	 * @return EE_Line_Item[]
345
+	 */
346
+	public function get_all_promotion_line_items(EE_Line_Item $parent_line_item)
347
+	{
348
+		return $this->get_all(array(
349
+			array(
350
+				'TXN_ID' => $parent_line_item->TXN_ID(),
351
+				'LIN_parent' => $parent_line_item->ID(),
352
+				'OBJ_type' => 'Promotion'
353
+			)
354
+		));
355
+	}
356
+
357
+	/**
358
+	 * Gets the registration's corresponding line item.
359
+	 * Note: basically does NOT support having multiple line items for a single ticket,
360
+	 * which would happen if some of the registrations had a price modifier while others didn't.
361
+	 * In order to support that, we'd probably need a LIN_ID on registrations or something.
362
+	 * @param EE_Registration $registration
363
+	 * @return EE_Line_ITem
364
+	 */
365
+	public function get_line_item_for_registration(EE_Registration $registration)
366
+	{
367
+		return $this->get_one($this->line_item_for_registration_query_params($registration));
368
+	}
369
+
370
+	/**
371
+	 * Gets the query params used to retrieve a specific line item for the given registration
372
+	 * @param EE_Registration $registration
373
+	 * @param array $original_query_params any extra query params you'd like to be merged with
374
+	 * @return array like EEM_Base::get_all()'s $query_params
375
+	 */
376
+	public function line_item_for_registration_query_params(EE_Registration $registration, $original_query_params = array())
377
+	{
378
+		return array_replace_recursive($original_query_params, array(
379
+			array(
380
+				'OBJ_ID' => $registration->ticket_ID(),
381
+				'OBJ_type' => 'Ticket',
382
+				'TXN_ID' => $registration->transaction_ID()
383
+			)
384
+		));
385
+	}
386
+
387
+
388
+	/**
389
+	 * @return EE_Base_Class[]|EE_Line_Item[]
390
+	 * @throws InvalidInterfaceException
391
+	 * @throws InvalidDataTypeException
392
+	 * @throws EE_Error
393
+	 * @throws InvalidArgumentException
394
+	 */
395
+	public function get_total_line_items_with_no_transaction()
396
+	{
397
+		return $this->get_total_line_items_for_carts();
398
+	}
399
+
400
+
401
+	/**
402
+	 * @return EE_Base_Class[]|EE_Line_Item[]
403
+	 * @throws InvalidInterfaceException
404
+	 * @throws InvalidDataTypeException
405
+	 * @throws EE_Error
406
+	 * @throws InvalidArgumentException
407
+	 */
408
+	public function get_total_line_items_for_active_carts()
409
+	{
410
+		return $this->get_total_line_items_for_carts(false);
411
+	}
412
+
413
+
414
+	/**
415
+	 * @return EE_Base_Class[]|EE_Line_Item[]
416
+	 * @throws InvalidInterfaceException
417
+	 * @throws InvalidDataTypeException
418
+	 * @throws EE_Error
419
+	 * @throws InvalidArgumentException
420
+	 */
421
+	public function get_total_line_items_for_expired_carts()
422
+	{
423
+		return $this->get_total_line_items_for_carts(true);
424
+	}
425
+
426
+
427
+	/**
428
+	 * Returns an array of grand total line items where the TXN_ID is 0.
429
+	 * If $expired is set to true, then only line items for expired sessions will be returned.
430
+	 * If $expired is set to false, then only line items for active sessions will be returned.
431
+	 *
432
+	 * @param null $expired
433
+	 * @return EE_Base_Class[]|EE_Line_Item[]
434
+	 * @throws EE_Error
435
+	 * @throws InvalidArgumentException
436
+	 * @throws InvalidDataTypeException
437
+	 * @throws InvalidInterfaceException
438
+	 */
439
+	private function get_total_line_items_for_carts($expired = null)
440
+	{
441
+		$where_params = array(
442
+			'TXN_ID' => 0,
443
+			'LIN_type' => 'total',
444
+		);
445
+		if ($expired !== null) {
446
+			/** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
447
+			$session_lifespan = LoaderFactory::getLoader()->getShared(
448
+				'EventEspresso\core\domain\values\session\SessionLifespan'
449
+			);
450
+			$where_params['LIN_timestamp'] = array(
451
+				$expired ? '<=' : '>',
452
+				$session_lifespan->expiration(),
453
+			);
454
+		}
455
+		return $this->get_all(array($where_params));
456
+	}
457
+
458
+
459
+	/**
460
+	 * Returns an array of ticket total line items where the TXN_ID is 0
461
+	 * AND the timestamp is older than the session lifespan.
462
+	 *
463
+	 * @param int $timestamp
464
+	 * @return EE_Base_Class[]|EE_Line_Item[]
465
+	 * @throws EE_Error
466
+	 * @throws InvalidArgumentException
467
+	 * @throws InvalidDataTypeException
468
+	 * @throws InvalidInterfaceException
469
+	 */
470
+	public function getTicketLineItemsForExpiredCarts($timestamp = 0)
471
+	{
472
+		if(! absint($timestamp)) {
473
+			/** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
474
+			$session_lifespan = LoaderFactory::getLoader()->getShared(
475
+				'EventEspresso\core\domain\values\session\SessionLifespan'
476
+			);
477
+			$timestamp = $session_lifespan->expiration();
478
+		}
479
+		return $this->get_all(
480
+			array(
481
+				array(
482
+					'TXN_ID'        => 0,
483
+					'OBJ_type'      => 'Ticket',
484
+					'LIN_timestamp' => array('<=', $timestamp),
485
+				)
486
+			)
487
+		);
488
+	}
489 489
 
490 490
 }
Please login to merge, or discard this patch.
core/domain/services/admin/PluginUpsells.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -83,12 +83,12 @@
 block discarded – undo
83 83
                     <div class="notice inline notice-alt">
84 84
                         <div class="ee-upsell-container">
85 85
                             <div class="ee-upsell-inner-container">
86
-                                <a href="' . $button_url . '">
87
-                                    ' . $button_text . '
86
+                                <a href="' . $button_url.'">
87
+                                    ' . $button_text.'
88 88
                                 </a>
89 89
                             </div>
90 90
                             <div class="ee-upsell-inner-container">
91
-                                <p>' . $upsell_text . '</p>
91
+                                <p>' . $upsell_text.'</p>
92 92
                             </div>
93 93
                             <div style="clear:both"></div>
94 94
                         </div>
Please login to merge, or discard this patch.
Indentation   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -16,46 +16,46 @@  discard block
 block discarded – undo
16 16
 class PluginUpsells
17 17
 {
18 18
 
19
-    /**
20
-     * @var DomainInterface
21
-     */
22
-    private $domain;
19
+	/**
20
+	 * @var DomainInterface
21
+	 */
22
+	private $domain;
23 23
 
24 24
 
25
-    /**
26
-     * PluginUpsells constructor.
27
-     *
28
-     * @param DomainInterface $domain
29
-     */
30
-    public function __construct(DomainInterface $domain)
31
-    {
32
-        $this->domain = $domain;
33
-    }
25
+	/**
26
+	 * PluginUpsells constructor.
27
+	 *
28
+	 * @param DomainInterface $domain
29
+	 */
30
+	public function __construct(DomainInterface $domain)
31
+	{
32
+		$this->domain = $domain;
33
+	}
34 34
 
35 35
 
36
-    /**
37
-     * Hook in various upsells for the decaf version of EE.
38
-     */
39
-    public function decafUpsells()
40
-    {
41
-        if ($this->domain instanceof CaffeinatedInterface && ! $this->domain->isCaffeinated()) {
42
-            add_action('after_plugin_row', array($this, 'doPremiumUpsell'), 10, 3);
43
-        }
44
-    }
36
+	/**
37
+	 * Hook in various upsells for the decaf version of EE.
38
+	 */
39
+	public function decafUpsells()
40
+	{
41
+		if ($this->domain instanceof CaffeinatedInterface && ! $this->domain->isCaffeinated()) {
42
+			add_action('after_plugin_row', array($this, 'doPremiumUpsell'), 10, 3);
43
+		}
44
+	}
45 45
 
46 46
 
47
-    /**
48
-     * Callback for `after_plugin_row` to add upsell info
49
-     * @param string $plugin_file
50
-     * @param array $plugin_data
51
-     * @param string $status
52
-     * @throws DomainException
53
-     */
54
-    public function doPremiumUpsell($plugin_file, $plugin_data, $status)
55
-    {
56
-        if ($plugin_file === $this->domain->pluginBasename()) {
57
-            list($button_text, $button_url, $upsell_text) = $this->getAfterPluginRowDetails();
58
-            echo '<tr class="plugin-update-tr ee-upsell-plugin-list-table active">
47
+	/**
48
+	 * Callback for `after_plugin_row` to add upsell info
49
+	 * @param string $plugin_file
50
+	 * @param array $plugin_data
51
+	 * @param string $status
52
+	 * @throws DomainException
53
+	 */
54
+	public function doPremiumUpsell($plugin_file, $plugin_data, $status)
55
+	{
56
+		if ($plugin_file === $this->domain->pluginBasename()) {
57
+			list($button_text, $button_url, $upsell_text) = $this->getAfterPluginRowDetails();
58
+			echo '<tr class="plugin-update-tr ee-upsell-plugin-list-table active">
59 59
                 <td colspan="3" class="plugin-update colspanchange">
60 60
                     <div class="notice inline notice-alt">
61 61
                         <div class="ee-upsell-container">
@@ -72,26 +72,26 @@  discard block
 block discarded – undo
72 72
                     </div>
73 73
                 </td>
74 74
               </tr>';
75
-        }
76
-    }
75
+		}
76
+	}
77 77
 
78
-    /**
79
-     * Provide the details used for the upsell container.
80
-     * @return array
81
-     */
82
-    protected function getAfterPluginRowDetails()
83
-    {
84
-        return array(
85
-            esc_html__('Upgrade for Support', 'event_espresso'),
86
-            'https://eventespresso.com/purchase/?slug=ee4-license-personal&utm_source=wp_admin_plugins_screen&utm_medium=link&utm_campaign=plugins_screen_upgrade_link" class="button button-primary',
87
-            sprintf(
88
-                esc_html__(
89
-                    'You\'re missing out on %1$sexpert support%2$s and %1$sone-click updates%2$s! Don\'t have an Event Espresso support license key? Support the project and buy one today!',
90
-                    'event_espresso'
91
-                ),
92
-                '<strong>',
93
-                '</strong>'
94
-            )
95
-        );
96
-    }
78
+	/**
79
+	 * Provide the details used for the upsell container.
80
+	 * @return array
81
+	 */
82
+	protected function getAfterPluginRowDetails()
83
+	{
84
+		return array(
85
+			esc_html__('Upgrade for Support', 'event_espresso'),
86
+			'https://eventespresso.com/purchase/?slug=ee4-license-personal&utm_source=wp_admin_plugins_screen&utm_medium=link&utm_campaign=plugins_screen_upgrade_link" class="button button-primary',
87
+			sprintf(
88
+				esc_html__(
89
+					'You\'re missing out on %1$sexpert support%2$s and %1$sone-click updates%2$s! Don\'t have an Event Espresso support license key? Support the project and buy one today!',
90
+					'event_espresso'
91
+				),
92
+				'<strong>',
93
+				'</strong>'
94
+			)
95
+		);
96
+	}
97 97
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Spacing   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -515,8 +515,8 @@  discard block
 block discarded – undo
515 515
     protected function __construct($timezone = null)
516 516
     {
517 517
         // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
518
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+            throw new EE_Error(
520 520
                 sprintf(
521 521
                     __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522 522
                         'event_espresso'),
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
          *
537 537
          * @var EE_Table_Base[] $_tables
538 538
          */
539
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
539
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
540 540
         foreach ($this->_tables as $table_alias => $table_obj) {
541 541
             /** @var $table_obj EE_Table_Base */
542 542
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -551,10 +551,10 @@  discard block
 block discarded – undo
551 551
          *
552 552
          * @param EE_Model_Field_Base[] $_fields
553 553
          */
554
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
554
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
555 555
         $this->_invalidate_field_caches();
556 556
         foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
557
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
558 558
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559 559
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
560 560
             }
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
          *
583 583
          * @param EE_Model_Relation_Base[] $_model_relations
584 584
          */
585
-        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
585
+        $this->_model_relations = (array) apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
586 586
             $this->_model_relations);
587 587
         foreach ($this->_model_relations as $model_name => $relation_obj) {
588 588
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -594,12 +594,12 @@  discard block
 block discarded – undo
594 594
         }
595 595
         $this->set_timezone($timezone);
596 596
         //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
597
+        if ( ! $this->_default_where_conditions_strategy) {
598 598
             //nothing was set during child constructor, so set default
599 599
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600 600
         }
601 601
         $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
602
+        if ( ! $this->_minimum_where_conditions_strategy) {
603 603
             //nothing was set during child constructor, so set default
604 604
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605 605
         }
@@ -612,7 +612,7 @@  discard block
 block discarded – undo
612 612
         //initialize the standard cap restriction generators if none were specified by the child constructor
613 613
         if ($this->_cap_restriction_generators !== false) {
614 614
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
615
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
616 616
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
617 617
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618 618
                         new EE_Restriction_Generator_Protected(),
@@ -625,10 +625,10 @@  discard block
 block discarded – undo
625 625
         //if there are cap restriction generators, use them to make the default cap restrictions
626 626
         if ($this->_cap_restriction_generators !== false) {
627 627
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
628
+                if ( ! $generator_object) {
629 629
                     continue;
630 630
                 }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
631
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
632 632
                     throw new EE_Error(
633 633
                         sprintf(
634 634
                             __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
@@ -639,12 +639,12 @@  discard block
 block discarded – undo
639 639
                     );
640 640
                 }
641 641
                 $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
642
+                if ( ! $generator_object->construction_finalized()) {
643 643
                     $generator_object->_construct_finalize($this, $action);
644 644
                 }
645 645
             }
646 646
         }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
647
+        do_action('AHEE__'.get_class($this).'__construct__end');
648 648
     }
649 649
 
650 650
 
@@ -657,7 +657,7 @@  discard block
 block discarded – undo
657 657
      */
658 658
     public static function set_model_query_blog_id($blog_id = 0)
659 659
     {
660
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
660
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
661 661
     }
662 662
 
663 663
 
@@ -691,7 +691,7 @@  discard block
 block discarded – undo
691 691
     public static function instance($timezone = null)
692 692
     {
693 693
         // check if instance of Espresso_model already exists
694
-        if (! static::$_instance instanceof static) {
694
+        if ( ! static::$_instance instanceof static) {
695 695
             // instantiate Espresso_model
696 696
             static::$_instance = new static(
697 697
                 $timezone,
@@ -730,7 +730,7 @@  discard block
 block discarded – undo
730 730
             foreach ($r->getDefaultProperties() as $property => $value) {
731 731
                 //don't set instance to null like it was originally,
732 732
                 //but it's static anyways, and we're ignoring static properties (for now at least)
733
-                if (! isset($static_properties[$property])) {
733
+                if ( ! isset($static_properties[$property])) {
734 734
                     static::$_instance->{$property} = $value;
735 735
                 }
736 736
             }
@@ -754,7 +754,7 @@  discard block
 block discarded – undo
754 754
      */
755 755
     private static function getLoader()
756 756
     {
757
-        if(! EEM_Base::$loader instanceof LoaderInterface) {
757
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
758 758
             EEM_Base::$loader = LoaderFactory::getLoader();
759 759
         }
760 760
         return EEM_Base::$loader;
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
      */
775 775
     public function status_array($translated = false)
776 776
     {
777
-        if (! array_key_exists('Status', $this->_model_relations)) {
777
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
778 778
             return array();
779 779
         }
780 780
         $model_name = $this->get_this_model_name();
@@ -977,17 +977,17 @@  discard block
 block discarded – undo
977 977
     public function wp_user_field_name()
978 978
     {
979 979
         try {
980
-            if (! empty($this->_model_chain_to_wp_user)) {
980
+            if ( ! empty($this->_model_chain_to_wp_user)) {
981 981
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
982 982
                 $last_model_name = end($models_to_follow_to_wp_users);
983 983
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
984
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
984
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
985 985
             } else {
986 986
                 $model_with_fk_to_wp_users = $this;
987 987
                 $model_chain_to_wp_user = '';
988 988
             }
989 989
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
990
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
990
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
991 991
         } catch (EE_Error $e) {
992 992
             return false;
993 993
         }
@@ -1055,7 +1055,7 @@  discard block
 block discarded – undo
1055 1055
      */
1056 1056
     protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1057 1057
     {
1058
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);;
1058
+        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select); ;
1059 1059
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1060 1060
         $select_expressions = $columns_to_select === null
1061 1061
             ? $this->_construct_default_select_sql($model_query_info)
@@ -1063,11 +1063,11 @@  discard block
 block discarded – undo
1063 1063
         if ($this->_custom_selections instanceof CustomSelects) {
1064 1064
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1065 1065
             $select_expressions .= $select_expressions
1066
-                ? ', ' . $custom_expressions
1066
+                ? ', '.$custom_expressions
1067 1067
                 : $custom_expressions;
1068 1068
         }
1069 1069
 
1070
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1070
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1071 1071
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1072 1072
     }
1073 1073
 
@@ -1084,7 +1084,7 @@  discard block
 block discarded – undo
1084 1084
      */
1085 1085
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1086 1086
     {
1087
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1087
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1088 1088
             return null;
1089 1089
         }
1090 1090
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1133,7 +1133,7 @@  discard block
 block discarded – undo
1133 1133
         if (is_array($columns_to_select)) {
1134 1134
             $select_sql_array = array();
1135 1135
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1136
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1136
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1137 1137
                     throw new EE_Error(
1138 1138
                         sprintf(
1139 1139
                             __(
@@ -1145,7 +1145,7 @@  discard block
 block discarded – undo
1145 1145
                         )
1146 1146
                     );
1147 1147
                 }
1148
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1148
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1149 1149
                     throw new EE_Error(
1150 1150
                         sprintf(
1151 1151
                             esc_html__(
@@ -1217,7 +1217,7 @@  discard block
 block discarded – undo
1217 1217
      */
1218 1218
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1219 1219
     {
1220
-        if (! isset($query_params[0])) {
1220
+        if ( ! isset($query_params[0])) {
1221 1221
             $query_params[0] = array();
1222 1222
         }
1223 1223
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1242,7 +1242,7 @@  discard block
 block discarded – undo
1242 1242
      */
1243 1243
     public function get_one($query_params = array())
1244 1244
     {
1245
-        if (! is_array($query_params)) {
1245
+        if ( ! is_array($query_params)) {
1246 1246
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1247 1247
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1248 1248
                     gettype($query_params)), '4.6.0');
@@ -1433,7 +1433,7 @@  discard block
 block discarded – undo
1433 1433
                 return array();
1434 1434
             }
1435 1435
         }
1436
-        if (! is_array($query_params)) {
1436
+        if ( ! is_array($query_params)) {
1437 1437
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1438 1438
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1439 1439
                     gettype($query_params)), '4.6.0');
@@ -1443,7 +1443,7 @@  discard block
 block discarded – undo
1443 1443
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1444 1444
         $query_params['limit'] = $limit;
1445 1445
         //set direction
1446
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1446
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1447 1447
         $query_params['order_by'] = $operand === '>'
1448 1448
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1449 1449
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1521,7 +1521,7 @@  discard block
 block discarded – undo
1521 1521
     {
1522 1522
         $field_settings = $this->field_settings_for($field_name);
1523 1523
         //if not a valid EE_Datetime_Field then throw error
1524
-        if (! $field_settings instanceof EE_Datetime_Field) {
1524
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1525 1525
             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.',
1526 1526
                 'event_espresso'), $field_name));
1527 1527
         }
@@ -1672,7 +1672,7 @@  discard block
 block discarded – undo
1672 1672
      */
1673 1673
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1674 1674
     {
1675
-        if (! is_array($query_params)) {
1675
+        if ( ! is_array($query_params)) {
1676 1676
             EE_Error::doing_it_wrong('EEM_Base::update',
1677 1677
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1678 1678
                     gettype($query_params)), '4.6.0');
@@ -1694,7 +1694,7 @@  discard block
 block discarded – undo
1694 1694
          * @param EEM_Base $model           the model being queried
1695 1695
          * @param array    $query_params    see EEM_Base::get_all()
1696 1696
          */
1697
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1697
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1698 1698
             $query_params);
1699 1699
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1700 1700
         //to do that, for each table, verify that it's PK isn't null.
@@ -1708,7 +1708,7 @@  discard block
 block discarded – undo
1708 1708
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1709 1709
         foreach ($wpdb_select_results as $wpdb_result) {
1710 1710
             // type cast stdClass as array
1711
-            $wpdb_result = (array)$wpdb_result;
1711
+            $wpdb_result = (array) $wpdb_result;
1712 1712
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1713 1713
             if ($this->has_primary_key_field()) {
1714 1714
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1725,13 +1725,13 @@  discard block
 block discarded – undo
1725 1725
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1726 1726
                     //if there is no private key for this table on the results, it means there's no entry
1727 1727
                     //in this table, right? so insert a row in the current table, using any fields available
1728
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1728
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1729 1729
                            && $wpdb_result[$this_table_pk_column])
1730 1730
                     ) {
1731 1731
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1732 1732
                             $main_table_pk_value);
1733 1733
                         //if we died here, report the error
1734
-                        if (! $success) {
1734
+                        if ( ! $success) {
1735 1735
                             return false;
1736 1736
                         }
1737 1737
                     }
@@ -1762,7 +1762,7 @@  discard block
 block discarded – undo
1762 1762
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1763 1763
                 }
1764 1764
             }
1765
-            if (! $model_objs_affected_ids) {
1765
+            if ( ! $model_objs_affected_ids) {
1766 1766
                 //wait wait wait- if nothing was affected let's stop here
1767 1767
                 return 0;
1768 1768
             }
@@ -1789,7 +1789,7 @@  discard block
 block discarded – undo
1789 1789
                . $model_query_info->get_full_join_sql()
1790 1790
                . " SET "
1791 1791
                . $this->_construct_update_sql($fields_n_values)
1792
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1792
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1793 1793
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1794 1794
         /**
1795 1795
          * Action called after a model update call has been made.
@@ -1800,7 +1800,7 @@  discard block
 block discarded – undo
1800 1800
          * @param int      $rows_affected
1801 1801
          */
1802 1802
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1803
-        return $rows_affected;//how many supposedly got updated
1803
+        return $rows_affected; //how many supposedly got updated
1804 1804
     }
1805 1805
 
1806 1806
 
@@ -1828,7 +1828,7 @@  discard block
 block discarded – undo
1828 1828
         }
1829 1829
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1830 1830
         $select_expressions = $field->get_qualified_column();
1831
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1831
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1832 1832
         return $this->_do_wpdb_query('get_col', array($SQL));
1833 1833
     }
1834 1834
 
@@ -1846,7 +1846,7 @@  discard block
 block discarded – undo
1846 1846
     {
1847 1847
         $query_params['limit'] = 1;
1848 1848
         $col = $this->get_col($query_params, $field_to_select);
1849
-        if (! empty($col)) {
1849
+        if ( ! empty($col)) {
1850 1850
             return reset($col);
1851 1851
         }
1852 1852
         return null;
@@ -1877,7 +1877,7 @@  discard block
 block discarded – undo
1877 1877
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1878 1878
             $value_sql = $prepared_value === null ? 'NULL'
1879 1879
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1880
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1880
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1881 1881
         }
1882 1882
         return implode(",", $cols_n_values);
1883 1883
     }
@@ -2059,7 +2059,7 @@  discard block
 block discarded – undo
2059 2059
          * @param int      $rows_deleted
2060 2060
          */
2061 2061
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2062
-        return $rows_deleted;//how many supposedly got deleted
2062
+        return $rows_deleted; //how many supposedly got deleted
2063 2063
     }
2064 2064
 
2065 2065
 
@@ -2209,7 +2209,7 @@  discard block
 block discarded – undo
2209 2209
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2210 2210
                 //make sure we have unique $ids
2211 2211
                 $ids = array_unique($ids);
2212
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2212
+                $query[] = $column.' IN('.implode(',', $ids).')';
2213 2213
             }
2214 2214
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2215 2215
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2217,7 +2217,7 @@  discard block
 block discarded – undo
2217 2217
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2218 2218
                 $values_for_each_combined_primary_key_for_a_row = array();
2219 2219
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2220
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2220
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2221 2221
                 }
2222 2222
                 $ways_to_identify_a_row[] = '('
2223 2223
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2237,8 +2237,8 @@  discard block
 block discarded – undo
2237 2237
      */
2238 2238
     public function get_field_by_column($qualified_column_name)
2239 2239
     {
2240
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2241
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2240
+       foreach ($this->field_settings(true) as $field_name => $field_obj) {
2241
+           if ($field_obj->get_qualified_column() === $qualified_column_name) {
2242 2242
                return $field_obj;
2243 2243
            }
2244 2244
        }
@@ -2289,9 +2289,9 @@  discard block
 block discarded – undo
2289 2289
                 $column_to_count = '*';
2290 2290
             }
2291 2291
         }
2292
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2293
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2294
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2292
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2293
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2294
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2295 2295
     }
2296 2296
 
2297 2297
 
@@ -2313,14 +2313,14 @@  discard block
 block discarded – undo
2313 2313
             $field_obj = $this->get_primary_key_field();
2314 2314
         }
2315 2315
         $column_to_count = $field_obj->get_qualified_column();
2316
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2316
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2317 2317
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2318 2318
         $data_type = $field_obj->get_wpdb_data_type();
2319 2319
         if ($data_type === '%d' || $data_type === '%s') {
2320
-            return (float)$return_value;
2320
+            return (float) $return_value;
2321 2321
         }
2322 2322
         //must be %f
2323
-        return (float)$return_value;
2323
+        return (float) $return_value;
2324 2324
     }
2325 2325
 
2326 2326
 
@@ -2340,13 +2340,13 @@  discard block
 block discarded – undo
2340 2340
         //if we're in maintenance mode level 2, DON'T run any queries
2341 2341
         //because level 2 indicates the database needs updating and
2342 2342
         //is probably out of sync with the code
2343
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2343
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2344 2344
             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.",
2345 2345
                 "event_espresso")));
2346 2346
         }
2347 2347
         /** @type WPDB $wpdb */
2348 2348
         global $wpdb;
2349
-        if (! method_exists($wpdb, $wpdb_method)) {
2349
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2350 2350
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2351 2351
                 'event_espresso'), $wpdb_method));
2352 2352
         }
@@ -2358,7 +2358,7 @@  discard block
 block discarded – undo
2358 2358
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2359 2359
         if (WP_DEBUG) {
2360 2360
             $wpdb->show_errors($old_show_errors_value);
2361
-            if (! empty($wpdb->last_error)) {
2361
+            if ( ! empty($wpdb->last_error)) {
2362 2362
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2363 2363
             }
2364 2364
             if ($result === false) {
@@ -2419,7 +2419,7 @@  discard block
 block discarded – undo
2419 2419
                     return $result;
2420 2420
                     break;
2421 2421
             }
2422
-            if (! empty($error_message)) {
2422
+            if ( ! empty($error_message)) {
2423 2423
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2424 2424
                 trigger_error($error_message);
2425 2425
             }
@@ -2495,11 +2495,11 @@  discard block
 block discarded – undo
2495 2495
      */
2496 2496
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2497 2497
     {
2498
-        return " FROM " . $model_query_info->get_full_join_sql() .
2499
-               $model_query_info->get_where_sql() .
2500
-               $model_query_info->get_group_by_sql() .
2501
-               $model_query_info->get_having_sql() .
2502
-               $model_query_info->get_order_by_sql() .
2498
+        return " FROM ".$model_query_info->get_full_join_sql().
2499
+               $model_query_info->get_where_sql().
2500
+               $model_query_info->get_group_by_sql().
2501
+               $model_query_info->get_having_sql().
2502
+               $model_query_info->get_order_by_sql().
2503 2503
                $model_query_info->get_limit_sql();
2504 2504
     }
2505 2505
 
@@ -2695,12 +2695,12 @@  discard block
 block discarded – undo
2695 2695
         $related_model = $this->get_related_model_obj($model_name);
2696 2696
         //we're just going to use the query params on the related model's normal get_all query,
2697 2697
         //except add a condition to say to match the current mod
2698
-        if (! isset($query_params['default_where_conditions'])) {
2698
+        if ( ! isset($query_params['default_where_conditions'])) {
2699 2699
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2700 2700
         }
2701 2701
         $this_model_name = $this->get_this_model_name();
2702 2702
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2703
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2703
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2704 2704
         return $related_model->count($query_params, $field_to_count, $distinct);
2705 2705
     }
2706 2706
 
@@ -2720,7 +2720,7 @@  discard block
 block discarded – undo
2720 2720
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2721 2721
     {
2722 2722
         $related_model = $this->get_related_model_obj($model_name);
2723
-        if (! is_array($query_params)) {
2723
+        if ( ! is_array($query_params)) {
2724 2724
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2725 2725
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2726 2726
                     gettype($query_params)), '4.6.0');
@@ -2728,12 +2728,12 @@  discard block
 block discarded – undo
2728 2728
         }
2729 2729
         //we're just going to use the query params on the related model's normal get_all query,
2730 2730
         //except add a condition to say to match the current mod
2731
-        if (! isset($query_params['default_where_conditions'])) {
2731
+        if ( ! isset($query_params['default_where_conditions'])) {
2732 2732
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2733 2733
         }
2734 2734
         $this_model_name = $this->get_this_model_name();
2735 2735
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2736
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2736
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2737 2737
         return $related_model->sum($query_params, $field_to_sum);
2738 2738
     }
2739 2739
 
@@ -2786,7 +2786,7 @@  discard block
 block discarded – undo
2786 2786
                 $field_with_model_name = $field;
2787 2787
             }
2788 2788
         }
2789
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2789
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2790 2790
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2791 2791
                 $this->get_this_model_name()));
2792 2792
         }
@@ -2819,7 +2819,7 @@  discard block
 block discarded – undo
2819 2819
          * @param array    $fields_n_values keys are the fields and values are their new values
2820 2820
          * @param EEM_Base $model           the model used
2821 2821
          */
2822
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2822
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2823 2823
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2824 2824
             $main_table = $this->_get_main_table();
2825 2825
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2926,7 +2926,7 @@  discard block
 block discarded – undo
2926 2926
         }
2927 2927
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2928 2928
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2929
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2929
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2930 2930
         }
2931 2931
         //if there is nothing to base this search on, then we shouldn't find anything
2932 2932
         if (empty($query_params)) {
@@ -3012,7 +3012,7 @@  discard block
 block discarded – undo
3012 3012
             //its not the main table, so we should have already saved the main table's PK which we just inserted
3013 3013
             //so add the fk to the main table as a column
3014 3014
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3015
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
3015
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
3016 3016
         }
3017 3017
         //insert the new entry
3018 3018
         $result = $this->_do_wpdb_query('insert',
@@ -3216,7 +3216,7 @@  discard block
 block discarded – undo
3216 3216
                     $query_info_carrier,
3217 3217
                     'group_by'
3218 3218
                 );
3219
-            } elseif (! empty ($query_params['group_by'])) {
3219
+            } elseif ( ! empty ($query_params['group_by'])) {
3220 3220
                 $this->_extract_related_model_info_from_query_param(
3221 3221
                     $query_params['group_by'],
3222 3222
                     $query_info_carrier,
@@ -3238,7 +3238,7 @@  discard block
 block discarded – undo
3238 3238
                     $query_info_carrier,
3239 3239
                     'order_by'
3240 3240
                 );
3241
-            } elseif (! empty($query_params['order_by'])) {
3241
+            } elseif ( ! empty($query_params['order_by'])) {
3242 3242
                 $this->_extract_related_model_info_from_query_param(
3243 3243
                     $query_params['order_by'],
3244 3244
                     $query_info_carrier,
@@ -3274,8 +3274,8 @@  discard block
 block discarded – undo
3274 3274
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3275 3275
         $query_param_type
3276 3276
     ) {
3277
-        if (! empty($sub_query_params)) {
3278
-            $sub_query_params = (array)$sub_query_params;
3277
+        if ( ! empty($sub_query_params)) {
3278
+            $sub_query_params = (array) $sub_query_params;
3279 3279
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3280 3280
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3281 3281
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3286,7 +3286,7 @@  discard block
 block discarded – undo
3286 3286
                 //of array('Registration.TXN_ID'=>23)
3287 3287
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3288 3288
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3289
-                    if (! is_array($possibly_array_of_params)) {
3289
+                    if ( ! is_array($possibly_array_of_params)) {
3290 3290
                         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'))",
3291 3291
                             "event_espresso"),
3292 3292
                             $param, $possibly_array_of_params));
@@ -3303,7 +3303,7 @@  discard block
 block discarded – undo
3303 3303
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3304 3304
                     //indicating that $possible_array_of_params[1] is actually a field name,
3305 3305
                     //from which we should extract query parameters!
3306
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3306
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3307 3307
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3308 3308
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3309 3309
                     }
@@ -3333,8 +3333,8 @@  discard block
 block discarded – undo
3333 3333
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3334 3334
         $query_param_type
3335 3335
     ) {
3336
-        if (! empty($sub_query_params)) {
3337
-            if (! is_array($sub_query_params)) {
3336
+        if ( ! empty($sub_query_params)) {
3337
+            if ( ! is_array($sub_query_params)) {
3338 3338
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3339 3339
                     $sub_query_params));
3340 3340
             }
@@ -3363,7 +3363,7 @@  discard block
 block discarded – undo
3363 3363
      */
3364 3364
     public function _create_model_query_info_carrier($query_params)
3365 3365
     {
3366
-        if (! is_array($query_params)) {
3366
+        if ( ! is_array($query_params)) {
3367 3367
             EE_Error::doing_it_wrong(
3368 3368
                 'EEM_Base::_create_model_query_info_carrier',
3369 3369
                 sprintf(
@@ -3439,7 +3439,7 @@  discard block
 block discarded – undo
3439 3439
         //set limit
3440 3440
         if (array_key_exists('limit', $query_params)) {
3441 3441
             if (is_array($query_params['limit'])) {
3442
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3442
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3443 3443
                     $e = sprintf(
3444 3444
                         __(
3445 3445
                             "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)",
@@ -3447,12 +3447,12 @@  discard block
 block discarded – undo
3447 3447
                         ),
3448 3448
                         http_build_query($query_params['limit'])
3449 3449
                     );
3450
-                    throw new EE_Error($e . "|" . $e);
3450
+                    throw new EE_Error($e."|".$e);
3451 3451
                 }
3452 3452
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3453
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3454
-            } elseif (! empty ($query_params['limit'])) {
3455
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3453
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3454
+            } elseif ( ! empty ($query_params['limit'])) {
3455
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3456 3456
             }
3457 3457
         }
3458 3458
         //set order by
@@ -3484,10 +3484,10 @@  discard block
 block discarded – undo
3484 3484
                 $order_array = array();
3485 3485
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3486 3486
                     $order = $this->_extract_order($order);
3487
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3487
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3488 3488
                 }
3489
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3490
-            } elseif (! empty ($query_params['order_by'])) {
3489
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3490
+            } elseif ( ! empty ($query_params['order_by'])) {
3491 3491
                 $this->_extract_related_model_info_from_query_param(
3492 3492
                     $query_params['order_by'],
3493 3493
                     $query_object,
@@ -3498,18 +3498,18 @@  discard block
 block discarded – undo
3498 3498
                     ? $this->_extract_order($query_params['order'])
3499 3499
                     : 'DESC';
3500 3500
                 $query_object->set_order_by_sql(
3501
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3501
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3502 3502
                 );
3503 3503
             }
3504 3504
         }
3505 3505
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3506
-        if (! array_key_exists('order_by', $query_params)
3506
+        if ( ! array_key_exists('order_by', $query_params)
3507 3507
             && array_key_exists('order', $query_params)
3508 3508
             && ! empty($query_params['order'])
3509 3509
         ) {
3510 3510
             $pk_field = $this->get_primary_key_field();
3511 3511
             $order = $this->_extract_order($query_params['order']);
3512
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3512
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3513 3513
         }
3514 3514
         //set group by
3515 3515
         if (array_key_exists('group_by', $query_params)) {
@@ -3519,10 +3519,10 @@  discard block
 block discarded – undo
3519 3519
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3520 3520
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3521 3521
                 }
3522
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3523
-            } elseif (! empty ($query_params['group_by'])) {
3522
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3523
+            } elseif ( ! empty ($query_params['group_by'])) {
3524 3524
                 $query_object->set_group_by_sql(
3525
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3525
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3526 3526
                 );
3527 3527
             }
3528 3528
         }
@@ -3532,7 +3532,7 @@  discard block
 block discarded – undo
3532 3532
         }
3533 3533
         //now, just verify they didn't pass anything wack
3534 3534
         foreach ($query_params as $query_key => $query_value) {
3535
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3535
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3536 3536
                 throw new EE_Error(
3537 3537
                     sprintf(
3538 3538
                         __(
@@ -3631,22 +3631,22 @@  discard block
 block discarded – undo
3631 3631
         $where_query_params = array()
3632 3632
     ) {
3633 3633
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3634
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3634
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3635 3635
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3636 3636
                 "event_espresso"), $use_default_where_conditions,
3637 3637
                 implode(", ", $allowed_used_default_where_conditions_values)));
3638 3638
         }
3639 3639
         $universal_query_params = array();
3640
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3640
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3641 3641
             $universal_query_params = $this->_get_default_where_conditions();
3642
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3642
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3643 3643
             $universal_query_params = $this->_get_minimum_where_conditions();
3644 3644
         }
3645 3645
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3646 3646
             $related_model = $this->get_related_model_obj($model_name);
3647
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3647
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3648 3648
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3649
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3649
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3650 3650
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3651 3651
             } else {
3652 3652
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3679,7 +3679,7 @@  discard block
 block discarded – undo
3679 3679
      * @param bool $for_this_model false means this is for OTHER related models
3680 3680
      * @return bool
3681 3681
      */
3682
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3682
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3683 3683
     {
3684 3684
         return (
3685 3685
                    $for_this_model
@@ -3758,7 +3758,7 @@  discard block
 block discarded – undo
3758 3758
     ) {
3759 3759
         $null_friendly_where_conditions = array();
3760 3760
         $none_overridden = true;
3761
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3761
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3762 3762
         foreach ($default_where_conditions as $key => $val) {
3763 3763
             if (isset($provided_where_conditions[$key])) {
3764 3764
                 $none_overridden = false;
@@ -3876,7 +3876,7 @@  discard block
 block discarded – undo
3876 3876
             foreach ($tables as $table_obj) {
3877 3877
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3878 3878
                                        . $table_obj->get_fully_qualified_pk_column();
3879
-                if (! in_array($qualified_pk_column, $selects)) {
3879
+                if ( ! in_array($qualified_pk_column, $selects)) {
3880 3880
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3881 3881
                 }
3882 3882
             }
@@ -4022,9 +4022,9 @@  discard block
 block discarded – undo
4022 4022
         $query_parameter_type
4023 4023
     ) {
4024 4024
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4025
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4025
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4026 4026
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4027
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4027
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4028 4028
                 if ($possible_join_string === '') {
4029 4029
                     //nothing left to $query_param
4030 4030
                     //we should actually end in a field name, not a model like this!
@@ -4151,7 +4151,7 @@  discard block
 block discarded – undo
4151 4151
     {
4152 4152
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4153 4153
         if ($SQL) {
4154
-            return " WHERE " . $SQL;
4154
+            return " WHERE ".$SQL;
4155 4155
         }
4156 4156
         return '';
4157 4157
     }
@@ -4170,7 +4170,7 @@  discard block
 block discarded – undo
4170 4170
     {
4171 4171
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4172 4172
         if ($SQL) {
4173
-            return " HAVING " . $SQL;
4173
+            return " HAVING ".$SQL;
4174 4174
         }
4175 4175
         return '';
4176 4176
     }
@@ -4189,7 +4189,7 @@  discard block
 block discarded – undo
4189 4189
     {
4190 4190
         $where_clauses = array();
4191 4191
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4192
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4192
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
4193 4193
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4194 4194
                 switch ($query_param) {
4195 4195
                     case 'not':
@@ -4217,7 +4217,7 @@  discard block
 block discarded – undo
4217 4217
             } else {
4218 4218
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4219 4219
                 //if it's not a normal field, maybe it's a custom selection?
4220
-                if (! $field_obj) {
4220
+                if ( ! $field_obj) {
4221 4221
                     if ($this->_custom_selections instanceof CustomSelects) {
4222 4222
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4223 4223
                     } else {
@@ -4226,7 +4226,7 @@  discard block
 block discarded – undo
4226 4226
                     }
4227 4227
                 }
4228 4228
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4229
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4229
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4230 4230
             }
4231 4231
         }
4232 4232
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4247,7 +4247,7 @@  discard block
 block discarded – undo
4247 4247
         if ($field) {
4248 4248
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4249 4249
                 $query_param);
4250
-            return $table_alias_prefix . $field->get_qualified_column();
4250
+            return $table_alias_prefix.$field->get_qualified_column();
4251 4251
         }
4252 4252
         if ($this->_custom_selections instanceof CustomSelects
4253 4253
             && in_array($query_param, $this->_custom_selections->columnAliases(), true)
@@ -4304,7 +4304,7 @@  discard block
 block discarded – undo
4304 4304
     {
4305 4305
         if (is_array($op_and_value)) {
4306 4306
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4307
-            if (! $operator) {
4307
+            if ( ! $operator) {
4308 4308
                 $php_array_like_string = array();
4309 4309
                 foreach ($op_and_value as $key => $value) {
4310 4310
                     $php_array_like_string[] = "$key=>$value";
@@ -4326,14 +4326,14 @@  discard block
 block discarded – undo
4326 4326
         }
4327 4327
         //check to see if the value is actually another field
4328 4328
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4329
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4329
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4330 4330
         }
4331 4331
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4332 4332
             //in this case, the value should be an array, or at least a comma-separated list
4333 4333
             //it will need to handle a little differently
4334 4334
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4335 4335
             //note: $cleaned_value has already been run through $wpdb->prepare()
4336
-            return $operator . SP . $cleaned_value;
4336
+            return $operator.SP.$cleaned_value;
4337 4337
         }
4338 4338
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4339 4339
             //the value should be an array with count of two.
@@ -4349,7 +4349,7 @@  discard block
 block discarded – undo
4349 4349
                 );
4350 4350
             }
4351 4351
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4352
-            return $operator . SP . $cleaned_value;
4352
+            return $operator.SP.$cleaned_value;
4353 4353
         }
4354 4354
         if (in_array($operator, $this->valid_null_style_operators())) {
4355 4355
             if ($value !== null) {
@@ -4369,10 +4369,10 @@  discard block
 block discarded – undo
4369 4369
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4370 4370
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4371 4371
             //remove other junk. So just treat it as a string.
4372
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4372
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4373 4373
         }
4374
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4375
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4374
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4375
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4376 4376
         }
4377 4377
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4378 4378
             throw new EE_Error(
@@ -4386,7 +4386,7 @@  discard block
 block discarded – undo
4386 4386
                 )
4387 4387
             );
4388 4388
         }
4389
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4389
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4390 4390
             throw new EE_Error(
4391 4391
                 sprintf(
4392 4392
                     __(
@@ -4426,7 +4426,7 @@  discard block
 block discarded – undo
4426 4426
         foreach ($values as $value) {
4427 4427
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4428 4428
         }
4429
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4429
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4430 4430
     }
4431 4431
 
4432 4432
 
@@ -4467,7 +4467,7 @@  discard block
 block discarded – undo
4467 4467
                                 . $main_table->get_table_name()
4468 4468
                                 . " WHERE FALSE";
4469 4469
         }
4470
-        return "(" . implode(",", $cleaned_values) . ")";
4470
+        return "(".implode(",", $cleaned_values).")";
4471 4471
     }
4472 4472
 
4473 4473
 
@@ -4486,7 +4486,7 @@  discard block
 block discarded – undo
4486 4486
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4487 4487
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4488 4488
         } //$field_obj should really just be a data type
4489
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4489
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4490 4490
             throw new EE_Error(
4491 4491
                 sprintf(
4492 4492
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4614,10 +4614,10 @@  discard block
 block discarded – undo
4614 4614
      */
4615 4615
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4616 4616
     {
4617
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4617
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4618 4618
         $qualified_columns = array();
4619 4619
         foreach ($this->field_settings() as $field_name => $field) {
4620
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4620
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4621 4621
         }
4622 4622
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4623 4623
     }
@@ -4641,11 +4641,11 @@  discard block
 block discarded – undo
4641 4641
             if ($table_obj instanceof EE_Primary_Table) {
4642 4642
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4643 4643
                     ? $table_obj->get_select_join_limit($limit)
4644
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4644
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4645 4645
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4646 4646
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4647 4647
                     ? $table_obj->get_select_join_limit_join($limit)
4648
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4648
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4649 4649
             }
4650 4650
         }
4651 4651
         return $SQL;
@@ -4733,12 +4733,12 @@  discard block
 block discarded – undo
4733 4733
      */
4734 4734
     public function get_related_model_obj($model_name)
4735 4735
     {
4736
-        $model_classname = "EEM_" . $model_name;
4737
-        if (! class_exists($model_classname)) {
4736
+        $model_classname = "EEM_".$model_name;
4737
+        if ( ! class_exists($model_classname)) {
4738 4738
             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",
4739 4739
                 'event_espresso'), $model_name, $model_classname));
4740 4740
         }
4741
-        return call_user_func($model_classname . "::instance");
4741
+        return call_user_func($model_classname."::instance");
4742 4742
     }
4743 4743
 
4744 4744
 
@@ -4785,7 +4785,7 @@  discard block
 block discarded – undo
4785 4785
     public function related_settings_for($relation_name)
4786 4786
     {
4787 4787
         $relatedModels = $this->relation_settings();
4788
-        if (! array_key_exists($relation_name, $relatedModels)) {
4788
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4789 4789
             throw new EE_Error(
4790 4790
                 sprintf(
4791 4791
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4813,7 +4813,7 @@  discard block
 block discarded – undo
4813 4813
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4814 4814
     {
4815 4815
         $fieldSettings = $this->field_settings($include_db_only_fields);
4816
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4816
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4817 4817
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4818 4818
                 get_class($this)));
4819 4819
         }
@@ -4886,7 +4886,7 @@  discard block
 block discarded – undo
4886 4886
                     break;
4887 4887
                 }
4888 4888
             }
4889
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4889
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4890 4890
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4891 4891
                     get_class($this)));
4892 4892
             }
@@ -4945,7 +4945,7 @@  discard block
 block discarded – undo
4945 4945
      */
4946 4946
     public function get_foreign_key_to($model_name)
4947 4947
     {
4948
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4948
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4949 4949
             foreach ($this->field_settings() as $field) {
4950 4950
                 if (
4951 4951
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4955,7 +4955,7 @@  discard block
 block discarded – undo
4955 4955
                     break;
4956 4956
                 }
4957 4957
             }
4958
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4958
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4959 4959
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4960 4960
                     'event_espresso'), $model_name, get_class($this)));
4961 4961
             }
@@ -5006,7 +5006,7 @@  discard block
 block discarded – undo
5006 5006
             foreach ($this->_fields as $fields_corresponding_to_table) {
5007 5007
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5008 5008
                     /** @var $field_obj EE_Model_Field_Base */
5009
-                    if (! $field_obj->is_db_only_field()) {
5009
+                    if ( ! $field_obj->is_db_only_field()) {
5010 5010
                         $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5011 5011
                     }
5012 5012
                 }
@@ -5035,7 +5035,7 @@  discard block
 block discarded – undo
5035 5035
         $count_if_model_has_no_primary_key = 0;
5036 5036
         $has_primary_key = $this->has_primary_key_field();
5037 5037
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5038
-        foreach ((array)$rows as $row) {
5038
+        foreach ((array) $rows as $row) {
5039 5039
             if (empty($row)) {
5040 5040
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5041 5041
                 return array();
@@ -5053,7 +5053,7 @@  discard block
 block discarded – undo
5053 5053
                 }
5054 5054
             }
5055 5055
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5056
-            if (! $classInstance) {
5056
+            if ( ! $classInstance) {
5057 5057
                 throw new EE_Error(
5058 5058
                     sprintf(
5059 5059
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5172,7 +5172,7 @@  discard block
 block discarded – undo
5172 5172
      */
5173 5173
     public function instantiate_class_from_array_or_object($cols_n_values)
5174 5174
     {
5175
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5175
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5176 5176
             $cols_n_values = get_object_vars($cols_n_values);
5177 5177
         }
5178 5178
         $primary_key = null;
@@ -5197,7 +5197,7 @@  discard block
 block discarded – undo
5197 5197
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5198 5198
         if ($primary_key) {
5199 5199
             $classInstance = $this->get_from_entity_map($primary_key);
5200
-            if (! $classInstance) {
5200
+            if ( ! $classInstance) {
5201 5201
                 $classInstance = EE_Registry::instance()
5202 5202
                                             ->load_class($className,
5203 5203
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -5246,12 +5246,12 @@  discard block
 block discarded – undo
5246 5246
     public function add_to_entity_map(EE_Base_Class $object)
5247 5247
     {
5248 5248
         $className = $this->_get_class_name();
5249
-        if (! $object instanceof $className) {
5249
+        if ( ! $object instanceof $className) {
5250 5250
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5251 5251
                 is_object($object) ? get_class($object) : $object, $className));
5252 5252
         }
5253 5253
         /** @var $object EE_Base_Class */
5254
-        if (! $object->ID()) {
5254
+        if ( ! $object->ID()) {
5255 5255
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5256 5256
                 "event_espresso"), get_class($this)));
5257 5257
         }
@@ -5320,7 +5320,7 @@  discard block
 block discarded – undo
5320 5320
             //there is a primary key on this table and its not set. Use defaults for all its columns
5321 5321
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5322 5322
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5323
-                    if (! $field_obj->is_db_only_field()) {
5323
+                    if ( ! $field_obj->is_db_only_field()) {
5324 5324
                         //prepare field as if its coming from db
5325 5325
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5326 5326
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5329,7 +5329,7 @@  discard block
 block discarded – undo
5329 5329
             } else {
5330 5330
                 //the table's rows existed. Use their values
5331 5331
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5332
-                    if (! $field_obj->is_db_only_field()) {
5332
+                    if ( ! $field_obj->is_db_only_field()) {
5333 5333
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5334 5334
                             $cols_n_values, $field_obj->get_qualified_column(),
5335 5335
                             $field_obj->get_table_column()
@@ -5444,7 +5444,7 @@  discard block
 block discarded – undo
5444 5444
      */
5445 5445
     private function _get_class_name()
5446 5446
     {
5447
-        return "EE_" . $this->get_this_model_name();
5447
+        return "EE_".$this->get_this_model_name();
5448 5448
     }
5449 5449
 
5450 5450
 
@@ -5459,7 +5459,7 @@  discard block
 block discarded – undo
5459 5459
      */
5460 5460
     public function item_name($quantity = 1)
5461 5461
     {
5462
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5462
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5463 5463
     }
5464 5464
 
5465 5465
 
@@ -5492,7 +5492,7 @@  discard block
 block discarded – undo
5492 5492
     {
5493 5493
         $className = get_class($this);
5494 5494
         $tagName = "FHEE__{$className}__{$methodName}";
5495
-        if (! has_filter($tagName)) {
5495
+        if ( ! has_filter($tagName)) {
5496 5496
             throw new EE_Error(
5497 5497
                 sprintf(
5498 5498
                     __('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 );',
@@ -5718,7 +5718,7 @@  discard block
 block discarded – undo
5718 5718
         $key_vals_in_combined_pk = array();
5719 5719
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5720 5720
         foreach ($key_fields as $key_field_name => $field_obj) {
5721
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5721
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5722 5722
                 return null;
5723 5723
             }
5724 5724
         }
@@ -5739,7 +5739,7 @@  discard block
 block discarded – undo
5739 5739
     {
5740 5740
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5741 5741
         foreach ($keys_it_should_have as $key) {
5742
-            if (! isset($key_vals[$key])) {
5742
+            if ( ! isset($key_vals[$key])) {
5743 5743
                 return false;
5744 5744
             }
5745 5745
         }
@@ -5793,7 +5793,7 @@  discard block
 block discarded – undo
5793 5793
      */
5794 5794
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5795 5795
     {
5796
-        if (! is_array($query_params)) {
5796
+        if ( ! is_array($query_params)) {
5797 5797
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5798 5798
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5799 5799
                     gettype($query_params)), '4.6.0');
@@ -5859,7 +5859,7 @@  discard block
 block discarded – undo
5859 5859
      * Gets the valid operators
5860 5860
      * @return array keys are accepted strings, values are the SQL they are converted to
5861 5861
      */
5862
-    public function valid_operators(){
5862
+    public function valid_operators() {
5863 5863
         return $this->_valid_operators;
5864 5864
     }
5865 5865
 
@@ -5947,7 +5947,7 @@  discard block
 block discarded – undo
5947 5947
      */
5948 5948
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5949 5949
     {
5950
-        if (! $this->has_primary_key_field()) {
5950
+        if ( ! $this->has_primary_key_field()) {
5951 5951
             if (WP_DEBUG) {
5952 5952
                 EE_Error::add_error(
5953 5953
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5960,7 +5960,7 @@  discard block
 block discarded – undo
5960 5960
         $IDs = array();
5961 5961
         foreach ($model_objects as $model_object) {
5962 5962
             $id = $model_object->ID();
5963
-            if (! $id) {
5963
+            if ( ! $id) {
5964 5964
                 if ($filter_out_empty_ids) {
5965 5965
                     continue;
5966 5966
                 }
@@ -6056,8 +6056,8 @@  discard block
 block discarded – undo
6056 6056
         $missing_caps = array();
6057 6057
         $cap_restrictions = $this->cap_restrictions($context);
6058 6058
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6059
-            if (! EE_Capabilities::instance()
6060
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6059
+            if ( ! EE_Capabilities::instance()
6060
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6061 6061
             ) {
6062 6062
                 $missing_caps[$cap] = $restriction_if_no_cap;
6063 6063
             }
@@ -6209,7 +6209,7 @@  discard block
 block discarded – undo
6209 6209
     {
6210 6210
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6211 6211
             if ($query_param_key === $logic_query_param_key
6212
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6212
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6213 6213
             ) {
6214 6214
                 return true;
6215 6215
             }
Please login to merge, or discard this patch.
Indentation   +6177 added lines, -6177 removed lines patch added patch discarded remove patch
@@ -34,6185 +34,6185 @@
 block discarded – undo
34 34
 abstract class EEM_Base extends EE_Base implements ResettableInterface
35 35
 {
36 36
 
37
-    /**
38
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
-     * They almost always WILL NOT, but it's not necessarily a requirement.
41
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
-     *
43
-     * @var boolean
44
-     */
45
-    private $_values_already_prepared_by_model_object = 0;
46
-
47
-    /**
48
-     * when $_values_already_prepared_by_model_object equals this, we assume
49
-     * the data is just like form input that needs to have the model fields'
50
-     * prepare_for_set and prepare_for_use_in_db called on it
51
-     */
52
-    const not_prepared_by_model_object = 0;
53
-
54
-    /**
55
-     * when $_values_already_prepared_by_model_object equals this, we
56
-     * assume this value is coming from a model object and doesn't need to have
57
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
58
-     */
59
-    const prepared_by_model_object = 1;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the values are already to be used in the database (ie no processing is done
64
-     * on them by the model's fields)
65
-     */
66
-    const prepared_for_use_in_db = 2;
67
-
68
-
69
-    protected $singular_item = 'Item';
70
-
71
-    protected $plural_item   = 'Items';
72
-
73
-    /**
74
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
-     */
76
-    protected $_tables;
77
-
78
-    /**
79
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
-     *
83
-     * @var \EE_Model_Field_Base[][] $_fields
84
-     */
85
-    protected $_fields;
86
-
87
-    /**
88
-     * array of different kinds of relations
89
-     *
90
-     * @var \EE_Model_Relation_Base[] $_model_relations
91
-     */
92
-    protected $_model_relations;
93
-
94
-    /**
95
-     * @var \EE_Index[] $_indexes
96
-     */
97
-    protected $_indexes = array();
98
-
99
-    /**
100
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
101
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
-     * by setting the same columns as used in these queries in the query yourself.
103
-     *
104
-     * @var EE_Default_Where_Conditions
105
-     */
106
-    protected $_default_where_conditions_strategy;
107
-
108
-    /**
109
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
-     * This is particularly useful when you want something between 'none' and 'default'
111
-     *
112
-     * @var EE_Default_Where_Conditions
113
-     */
114
-    protected $_minimum_where_conditions_strategy;
115
-
116
-    /**
117
-     * String describing how to find the "owner" of this model's objects.
118
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
-     * But when there isn't, this indicates which related model, or transiently-related model,
120
-     * has the foreign key to the wp_users table.
121
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
-     * related to events, and events have a foreign key to wp_users.
123
-     * On EEM_Transaction, this would be 'Transaction.Event'
124
-     *
125
-     * @var string
126
-     */
127
-    protected $_model_chain_to_wp_user = '';
128
-
129
-    /**
130
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
-     * don't need it (particularly CPT models)
132
-     *
133
-     * @var bool
134
-     */
135
-    protected $_ignore_where_strategy = false;
136
-
137
-    /**
138
-     * String used in caps relating to this model. Eg, if the caps relating to this
139
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
-     *
141
-     * @var string. If null it hasn't been initialized yet. If false then we
142
-     * have indicated capabilities don't apply to this
143
-     */
144
-    protected $_caps_slug = null;
145
-
146
-    /**
147
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
-     * and next-level keys are capability names, and each's value is a
149
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
-     * they specify which context to use (ie, frontend, backend, edit or delete)
151
-     * and then each capability in the corresponding sub-array that they're missing
152
-     * adds the where conditions onto the query.
153
-     *
154
-     * @var array
155
-     */
156
-    protected $_cap_restrictions = array(
157
-        self::caps_read       => array(),
158
-        self::caps_read_admin => array(),
159
-        self::caps_edit       => array(),
160
-        self::caps_delete     => array(),
161
-    );
162
-
163
-    /**
164
-     * Array defining which cap restriction generators to use to create default
165
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
166
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
-     * automatically set this to false (not just null).
169
-     *
170
-     * @var EE_Restriction_Generator_Base[]
171
-     */
172
-    protected $_cap_restriction_generators = array();
173
-
174
-    /**
175
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
-     */
177
-    const caps_read       = 'read';
178
-
179
-    const caps_read_admin = 'read_admin';
180
-
181
-    const caps_edit       = 'edit';
182
-
183
-    const caps_delete     = 'delete';
184
-
185
-    /**
186
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
-     * maps to 'read' because when looking for relevant permissions we're going to use
189
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
190
-     *
191
-     * @var array
192
-     */
193
-    protected $_cap_contexts_to_cap_action_map = array(
194
-        self::caps_read       => 'read',
195
-        self::caps_read_admin => 'read',
196
-        self::caps_edit       => 'edit',
197
-        self::caps_delete     => 'delete',
198
-    );
199
-
200
-    /**
201
-     * Timezone
202
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
-     * EE_Datetime_Field data type will have access to it.
206
-     *
207
-     * @var string
208
-     */
209
-    protected $_timezone;
210
-
211
-
212
-    /**
213
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
-     * multisite.
215
-     *
216
-     * @var int
217
-     */
218
-    protected static $_model_query_blog_id;
219
-
220
-    /**
221
-     * A copy of _fields, except the array keys are the model names pointed to by
222
-     * the field
223
-     *
224
-     * @var EE_Model_Field_Base[]
225
-     */
226
-    private $_cache_foreign_key_to_fields = array();
227
-
228
-    /**
229
-     * Cached list of all the fields on the model, indexed by their name
230
-     *
231
-     * @var EE_Model_Field_Base[]
232
-     */
233
-    private $_cached_fields = null;
234
-
235
-    /**
236
-     * Cached list of all the fields on the model, except those that are
237
-     * marked as only pertinent to the database
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cached_fields_non_db_only = null;
242
-
243
-    /**
244
-     * A cached reference to the primary key for quick lookup
245
-     *
246
-     * @var EE_Model_Field_Base
247
-     */
248
-    private $_primary_key_field = null;
249
-
250
-    /**
251
-     * Flag indicating whether this model has a primary key or not
252
-     *
253
-     * @var boolean
254
-     */
255
-    protected $_has_primary_key_field = null;
256
-
257
-    /**
258
-     * Whether or not this model is based off a table in WP core only (CPTs should set
259
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
-     * This should be true for models that deal with data that should exist independent of EE.
261
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
263
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
265
-     * @var boolean
266
-     */
267
-    protected $_wp_core_model = false;
268
-
269
-    /**
270
-     *    List of valid operators that can be used for querying.
271
-     * The keys are all operators we'll accept, the values are the real SQL
272
-     * operators used
273
-     *
274
-     * @var array
275
-     */
276
-    protected $_valid_operators = array(
277
-        '='           => '=',
278
-        '<='          => '<=',
279
-        '<'           => '<',
280
-        '>='          => '>=',
281
-        '>'           => '>',
282
-        '!='          => '!=',
283
-        'LIKE'        => 'LIKE',
284
-        'like'        => 'LIKE',
285
-        'NOT_LIKE'    => 'NOT LIKE',
286
-        'not_like'    => 'NOT LIKE',
287
-        'NOT LIKE'    => 'NOT LIKE',
288
-        'not like'    => 'NOT LIKE',
289
-        'IN'          => 'IN',
290
-        'in'          => 'IN',
291
-        'NOT_IN'      => 'NOT IN',
292
-        'not_in'      => 'NOT IN',
293
-        'NOT IN'      => 'NOT IN',
294
-        'not in'      => 'NOT IN',
295
-        'between'     => 'BETWEEN',
296
-        'BETWEEN'     => 'BETWEEN',
297
-        'IS_NOT_NULL' => 'IS NOT NULL',
298
-        'is_not_null' => 'IS NOT NULL',
299
-        'IS NOT NULL' => 'IS NOT NULL',
300
-        'is not null' => 'IS NOT NULL',
301
-        'IS_NULL'     => 'IS NULL',
302
-        'is_null'     => 'IS NULL',
303
-        'IS NULL'     => 'IS NULL',
304
-        'is null'     => 'IS NULL',
305
-        'REGEXP'      => 'REGEXP',
306
-        'regexp'      => 'REGEXP',
307
-        'NOT_REGEXP'  => 'NOT REGEXP',
308
-        'not_regexp'  => 'NOT REGEXP',
309
-        'NOT REGEXP'  => 'NOT REGEXP',
310
-        'not regexp'  => 'NOT REGEXP',
311
-    );
312
-
313
-    /**
314
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
-     *
316
-     * @var array
317
-     */
318
-    protected $_in_style_operators = array('IN', 'NOT IN');
319
-
320
-    /**
321
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
-     * '12-31-2012'"
323
-     *
324
-     * @var array
325
-     */
326
-    protected $_between_style_operators = array('BETWEEN');
327
-
328
-    /**
329
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
-     * @var array
331
-     */
332
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
-    /**
334
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
-     * on a join table.
336
-     *
337
-     * @var array
338
-     */
339
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
-
341
-    /**
342
-     * Allowed values for $query_params['order'] for ordering in queries
343
-     *
344
-     * @var array
345
-     */
346
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
-
348
-    /**
349
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
351
-     *
352
-     * @var array
353
-     */
354
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
-
356
-    /**
357
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
359
-     *
360
-     * @var array
361
-     */
362
-    private $_allowed_query_params = array(
363
-        0,
364
-        'limit',
365
-        'order_by',
366
-        'group_by',
367
-        'having',
368
-        'force_join',
369
-        'order',
370
-        'on_join_limit',
371
-        'default_where_conditions',
372
-        'caps',
373
-        'extra_selects'
374
-    );
375
-
376
-    /**
377
-     * All the data types that can be used in $wpdb->prepare statements.
378
-     *
379
-     * @var array
380
-     */
381
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
-
383
-    /**
384
-     * @var EE_Registry $EE
385
-     */
386
-    protected $EE = null;
387
-
388
-
389
-    /**
390
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
-     *
392
-     * @var int
393
-     */
394
-    protected $_show_next_x_db_queries = 0;
395
-
396
-    /**
397
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
-     * WHERE, GROUP_BY, etc.
400
-     *
401
-     * @var CustomSelects
402
-     */
403
-    protected $_custom_selections = array();
404
-
405
-    /**
406
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
-     * caches every model object we've fetched from the DB on this request
408
-     *
409
-     * @var array
410
-     */
411
-    protected $_entity_map;
412
-
413
-    /**
414
-     * @var LoaderInterface $loader
415
-     */
416
-    private static $loader;
417
-
418
-
419
-    /**
420
-     * constant used to show EEM_Base has not yet verified the db on this http request
421
-     */
422
-    const db_verified_none = 0;
423
-
424
-    /**
425
-     * constant used to show EEM_Base has verified the EE core db on this http request,
426
-     * but not the addons' dbs
427
-     */
428
-    const db_verified_core = 1;
429
-
430
-    /**
431
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
-     * the EE core db too)
433
-     */
434
-    const db_verified_addons = 2;
435
-
436
-    /**
437
-     * indicates whether an EEM_Base child has already re-verified the DB
438
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
-     * looking like EEM_Base::db_verified_*
440
-     *
441
-     * @var int - 0 = none, 1 = core, 2 = addons
442
-     */
443
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
-
445
-    /**
446
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
-     *        registrations for non-trashed tickets for non-trashed datetimes)
449
-     */
450
-    const default_where_conditions_all = 'all';
451
-
452
-    /**
453
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
-     *        models which share tables with other models, this can return data for the wrong model.
458
-     */
459
-    const default_where_conditions_this_only = 'this_model_only';
460
-
461
-    /**
462
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
-     */
466
-    const default_where_conditions_others_only = 'other_models_only';
467
-
468
-    /**
469
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
-     *        (regardless of whether those events and venues are trashed)
474
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
-     *        events.
476
-     */
477
-    const default_where_conditions_minimum_all = 'minimum';
478
-
479
-    /**
480
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
-     *        not)
484
-     */
485
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
-
487
-    /**
488
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
-     *        it's possible it will return table entries for other models. You should use
491
-     *        EEM_Base::default_where_conditions_minimum_all instead.
492
-     */
493
-    const default_where_conditions_none = 'none';
494
-
495
-
496
-
497
-    /**
498
-     * About all child constructors:
499
-     * they should define the _tables, _fields and _model_relations arrays.
500
-     * Should ALWAYS be called after child constructor.
501
-     * In order to make the child constructors to be as simple as possible, this parent constructor
502
-     * finalizes constructing all the object's attributes.
503
-     * Generally, rather than requiring a child to code
504
-     * $this->_tables = array(
505
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
-     *        ...);
507
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
-     * each EE_Table has a function to set the table's alias after the constructor, using
509
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
-     * do something similar.
511
-     *
512
-     * @param null $timezone
513
-     * @throws EE_Error
514
-     */
515
-    protected function __construct($timezone = null)
516
-    {
517
-        // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
520
-                sprintf(
521
-                    __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
-                        'event_espresso'),
523
-                    get_class($this)
524
-                )
525
-            );
526
-        }
527
-        /**
528
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
-         */
530
-        if (empty(EEM_Base::$_model_query_blog_id)) {
531
-            EEM_Base::set_model_query_blog_id();
532
-        }
533
-        /**
534
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
-         * just use EE_Register_Model_Extension
536
-         *
537
-         * @var EE_Table_Base[] $_tables
538
-         */
539
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
-        foreach ($this->_tables as $table_alias => $table_obj) {
541
-            /** @var $table_obj EE_Table_Base */
542
-            $table_obj->_construct_finalize_with_alias($table_alias);
543
-            if ($table_obj instanceof EE_Secondary_Table) {
544
-                /** @var $table_obj EE_Secondary_Table */
545
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
-            }
547
-        }
548
-        /**
549
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
-         * EE_Register_Model_Extension
551
-         *
552
-         * @param EE_Model_Field_Base[] $_fields
553
-         */
554
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
-        $this->_invalidate_field_caches();
556
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
558
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
-            }
561
-            foreach ($fields_for_table as $field_name => $field_obj) {
562
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
-                //primary key field base has a slightly different _construct_finalize
564
-                /** @var $field_obj EE_Model_Field_Base */
565
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
-            }
567
-        }
568
-        // everything is related to Extra_Meta
569
-        if (get_class($this) !== 'EEM_Extra_Meta') {
570
-            //make extra meta related to everything, but don't block deleting things just
571
-            //because they have related extra meta info. For now just orphan those extra meta
572
-            //in the future we should automatically delete them
573
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
-        }
575
-        //and change logs
576
-        if (get_class($this) !== 'EEM_Change_Log') {
577
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        /**
580
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
-         * EE_Register_Model_Extension
582
-         *
583
-         * @param EE_Model_Relation_Base[] $_model_relations
584
-         */
585
-        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
-            $this->_model_relations);
587
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
588
-            /** @var $relation_obj EE_Model_Relation_Base */
589
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
-        }
591
-        foreach ($this->_indexes as $index_name => $index_obj) {
592
-            /** @var $index_obj EE_Index */
593
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
-        }
595
-        $this->set_timezone($timezone);
596
-        //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
598
-            //nothing was set during child constructor, so set default
599
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
-        }
601
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
603
-            //nothing was set during child constructor, so set default
604
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
-        }
606
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
608
-        //to indicate to NOT set it, set it to the logical default
609
-        if ($this->_caps_slug === null) {
610
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
-        }
612
-        //initialize the standard cap restriction generators if none were specified by the child constructor
613
-        if ($this->_cap_restriction_generators !== false) {
614
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
617
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
-                        new EE_Restriction_Generator_Protected(),
619
-                        $cap_context,
620
-                        $this
621
-                    );
622
-                }
623
-            }
624
-        }
625
-        //if there are cap restriction generators, use them to make the default cap restrictions
626
-        if ($this->_cap_restriction_generators !== false) {
627
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
629
-                    continue;
630
-                }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
-                    throw new EE_Error(
633
-                        sprintf(
634
-                            __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
-                                'event_espresso'),
636
-                            $context,
637
-                            $this->get_this_model_name()
638
-                        )
639
-                    );
640
-                }
641
-                $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
643
-                    $generator_object->_construct_finalize($this, $action);
644
-                }
645
-            }
646
-        }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
648
-    }
649
-
650
-
651
-
652
-    /**
653
-     * Used to set the $_model_query_blog_id static property.
654
-     *
655
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
656
-     *                      value for get_current_blog_id() will be used.
657
-     */
658
-    public static function set_model_query_blog_id($blog_id = 0)
659
-    {
660
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
661
-    }
662
-
663
-
664
-
665
-    /**
666
-     * Returns whatever is set as the internal $model_query_blog_id.
667
-     *
668
-     * @return int
669
-     */
670
-    public static function get_model_query_blog_id()
671
-    {
672
-        return EEM_Base::$_model_query_blog_id;
673
-    }
674
-
675
-
676
-
677
-    /**
678
-     * This function is a singleton method used to instantiate the Espresso_model object
679
-     *
680
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
681
-     *                                (and any incoming timezone data that gets saved).
682
-     *                                Note this just sends the timezone info to the date time model field objects.
683
-     *                                Default is NULL
684
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
685
-     * @return static (as in the concrete child class)
686
-     * @throws EE_Error
687
-     * @throws InvalidArgumentException
688
-     * @throws InvalidDataTypeException
689
-     * @throws InvalidInterfaceException
690
-     */
691
-    public static function instance($timezone = null)
692
-    {
693
-        // check if instance of Espresso_model already exists
694
-        if (! static::$_instance instanceof static) {
695
-            // instantiate Espresso_model
696
-            static::$_instance = new static(
697
-                $timezone,
698
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
699
-            );
700
-        }
701
-        //we might have a timezone set, let set_timezone decide what to do with it
702
-        static::$_instance->set_timezone($timezone);
703
-        // Espresso_model object
704
-        return static::$_instance;
705
-    }
706
-
707
-
708
-
709
-    /**
710
-     * resets the model and returns it
711
-     *
712
-     * @param null | string $timezone
713
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
714
-     * all its properties reset; if it wasn't instantiated, returns null)
715
-     * @throws EE_Error
716
-     * @throws ReflectionException
717
-     * @throws InvalidArgumentException
718
-     * @throws InvalidDataTypeException
719
-     * @throws InvalidInterfaceException
720
-     */
721
-    public static function reset($timezone = null)
722
-    {
723
-        if (static::$_instance instanceof EEM_Base) {
724
-            //let's try to NOT swap out the current instance for a new one
725
-            //because if someone has a reference to it, we can't remove their reference
726
-            //so it's best to keep using the same reference, but change the original object
727
-            //reset all its properties to their original values as defined in the class
728
-            $r = new ReflectionClass(get_class(static::$_instance));
729
-            $static_properties = $r->getStaticProperties();
730
-            foreach ($r->getDefaultProperties() as $property => $value) {
731
-                //don't set instance to null like it was originally,
732
-                //but it's static anyways, and we're ignoring static properties (for now at least)
733
-                if (! isset($static_properties[$property])) {
734
-                    static::$_instance->{$property} = $value;
735
-                }
736
-            }
737
-            //and then directly call its constructor again, like we would if we were creating a new one
738
-            static::$_instance->__construct(
739
-                $timezone,
740
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
741
-            );
742
-            return self::instance();
743
-        }
744
-        return null;
745
-    }
746
-
747
-
748
-
749
-    /**
750
-     * @return LoaderInterface
751
-     * @throws InvalidArgumentException
752
-     * @throws InvalidDataTypeException
753
-     * @throws InvalidInterfaceException
754
-     */
755
-    private static function getLoader()
756
-    {
757
-        if(! EEM_Base::$loader instanceof LoaderInterface) {
758
-            EEM_Base::$loader = LoaderFactory::getLoader();
759
-        }
760
-        return EEM_Base::$loader;
761
-    }
762
-
763
-
764
-
765
-    /**
766
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
767
-     *
768
-     * @param  boolean $translated return localized strings or JUST the array.
769
-     * @return array
770
-     * @throws EE_Error
771
-     * @throws InvalidArgumentException
772
-     * @throws InvalidDataTypeException
773
-     * @throws InvalidInterfaceException
774
-     */
775
-    public function status_array($translated = false)
776
-    {
777
-        if (! array_key_exists('Status', $this->_model_relations)) {
778
-            return array();
779
-        }
780
-        $model_name = $this->get_this_model_name();
781
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
782
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
783
-        $status_array = array();
784
-        foreach ($stati as $status) {
785
-            $status_array[$status->ID()] = $status->get('STS_code');
786
-        }
787
-        return $translated
788
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
789
-            : $status_array;
790
-    }
791
-
792
-
793
-
794
-    /**
795
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
796
-     *
797
-     * @param array $query_params             {
798
-     * @var array $0 (where) array {
799
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
800
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
801
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
802
-     *                                        conditions based on related models (and even
803
-     *                                        models-related-to-related-models) prepend the model's name onto the field
804
-     *                                        name. Eg,
805
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
806
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
807
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
808
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
809
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
810
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
811
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
812
-     *                                        to Venues (even when each of those models actually consisted of two
813
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
814
-     *                                        just having
815
-     *                                        "Venue.VNU_ID", you could have
816
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
817
-     *                                        events are related to Registrations, which are related to Attendees). You
818
-     *                                        can take it even further with
819
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
820
-     *                                        (from the default of '='), change the value to an numerically-indexed
821
-     *                                        array, where the first item in the list is the operator. eg: array(
822
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
823
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
824
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
825
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
826
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
827
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
828
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
829
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
830
-     *                                        the value is a field, simply provide a third array item (true) to the
831
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
832
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
833
-     *                                        Note: you can also use related model field names like you would any other
834
-     *                                        field name. eg:
835
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
836
-     *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
837
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
838
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
839
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
840
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
841
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
842
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
843
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
844
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
845
-     *                                        "stick" until you specify an AND. eg
846
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
847
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
848
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
849
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
850
-     *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
851
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
852
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
853
-     *                                        too, eg:
854
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
855
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
856
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
857
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
858
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
859
-     *                                        the OFFSET, the 2nd is the LIMIT
860
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
861
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
862
-     *                                        following format array('on_join_limit'
863
-     *                                        => array( 'table_alias', array(1,2) ) ).
864
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
865
-     *                                        values are either 'ASC' or 'DESC'.
866
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
867
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
868
-     *                                        DESC..." respectively. Like the
869
-     *                                        'where' conditions, these fields can be on related models. Eg
870
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
871
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
872
-     *                                        Attendee, Price, Datetime, etc.)
873
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
874
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
875
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
876
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
877
-     *                                        order by the primary key. Eg,
878
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
879
-     *                                        //(will join with the Datetime model's table(s) and order by its field
880
-     *                                        DTT_EVT_start) or
881
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
882
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
883
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
884
-     *                                        'group_by'=>'VNU_ID', or
885
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
886
-     *                                        if no
887
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
888
-     *                                        model's primary key (or combined primary keys). This avoids some
889
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
890
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
891
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
892
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
893
-     *                                        results)
894
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
895
-     *                                        array where values are models to be joined in the query.Eg
896
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
897
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
898
-     *                                        probably only want to do this in hopes of increasing efficiency, as
899
-     *                                        related models which belongs to the current model
900
-     *                                        (ie, the current model has a foreign key to them, like how Registration
901
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
902
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
903
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
904
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
905
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
906
-     *                                        default where conditions set it to 'other_models_only'. If you only want
907
-     *                                        this model's default where conditions added to the query, use
908
-     *                                        'this_model_only'. If you want to use all default where conditions
909
-     *                                        (default), set to 'all'.
910
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
911
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
912
-     *                                        everything? Or should we only show the current user items they should be
913
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
914
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
915
-     *                                        }
916
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
917
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
918
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
919
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
920
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
921
-     *                                        array( array(
922
-     *                                        'OR'=>array(
923
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
924
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
925
-     *                                        )
926
-     *                                        ),
927
-     *                                        'limit'=>10,
928
-     *                                        'group_by'=>'TXN_ID'
929
-     *                                        ));
930
-     *                                        get all the answers to the question titled "shirt size" for event with id
931
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
932
-     *                                        'Question.QST_display_text'=>'shirt size',
933
-     *                                        'Registration.Event.EVT_ID'=>12
934
-     *                                        ),
935
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
936
-     *                                        ));
937
-     * @throws EE_Error
938
-     */
939
-    public function get_all($query_params = array())
940
-    {
941
-        if (isset($query_params['limit'])
942
-            && ! isset($query_params['group_by'])
943
-        ) {
944
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
945
-        }
946
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
947
-    }
948
-
949
-
950
-
951
-    /**
952
-     * Modifies the query parameters so we only get back model objects
953
-     * that "belong" to the current user
954
-     *
955
-     * @param array $query_params @see EEM_Base::get_all()
956
-     * @return array like EEM_Base::get_all
957
-     */
958
-    public function alter_query_params_to_only_include_mine($query_params = array())
959
-    {
960
-        $wp_user_field_name = $this->wp_user_field_name();
961
-        if ($wp_user_field_name) {
962
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
963
-        }
964
-        return $query_params;
965
-    }
966
-
967
-
968
-
969
-    /**
970
-     * Returns the name of the field's name that points to the WP_User table
971
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
972
-     * foreign key to the WP_User table)
973
-     *
974
-     * @return string|boolean string on success, boolean false when there is no
975
-     * foreign key to the WP_User table
976
-     */
977
-    public function wp_user_field_name()
978
-    {
979
-        try {
980
-            if (! empty($this->_model_chain_to_wp_user)) {
981
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
982
-                $last_model_name = end($models_to_follow_to_wp_users);
983
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
984
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
985
-            } else {
986
-                $model_with_fk_to_wp_users = $this;
987
-                $model_chain_to_wp_user = '';
988
-            }
989
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
990
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
991
-        } catch (EE_Error $e) {
992
-            return false;
993
-        }
994
-    }
995
-
996
-
997
-
998
-    /**
999
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
1000
-     * (or transiently-related model) has a foreign key to the wp_users table;
1001
-     * useful for finding if model objects of this type are 'owned' by the current user.
1002
-     * This is an empty string when the foreign key is on this model and when it isn't,
1003
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
1004
-     * (or transiently-related model)
1005
-     *
1006
-     * @return string
1007
-     */
1008
-    public function model_chain_to_wp_user()
1009
-    {
1010
-        return $this->_model_chain_to_wp_user;
1011
-    }
1012
-
1013
-
1014
-
1015
-    /**
1016
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1017
-     * like how registrations don't have a foreign key to wp_users, but the
1018
-     * events they are for are), or is unrelated to wp users.
1019
-     * generally available
1020
-     *
1021
-     * @return boolean
1022
-     */
1023
-    public function is_owned()
1024
-    {
1025
-        if ($this->model_chain_to_wp_user()) {
1026
-            return true;
1027
-        }
1028
-        try {
1029
-            $this->get_foreign_key_to('WP_User');
1030
-            return true;
1031
-        } catch (EE_Error $e) {
1032
-            return false;
1033
-        }
1034
-    }
1035
-
1036
-
1037
-    /**
1038
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1039
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1040
-     * the model)
1041
-     *
1042
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1043
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1044
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1045
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1046
-     *                                  override this and set the select to "*", or a specific column name, like
1047
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1048
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1049
-     *                                  the aliases used to refer to this selection, and values are to be
1050
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1051
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1052
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1053
-     * @throws EE_Error
1054
-     * @throws InvalidArgumentException
1055
-     */
1056
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1057
-    {
1058
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);;
1059
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1060
-        $select_expressions = $columns_to_select === null
1061
-            ? $this->_construct_default_select_sql($model_query_info)
1062
-            : '';
1063
-        if ($this->_custom_selections instanceof CustomSelects) {
1064
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1065
-            $select_expressions .= $select_expressions
1066
-                ? ', ' . $custom_expressions
1067
-                : $custom_expressions;
1068
-        }
1069
-
1070
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1071
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1072
-    }
1073
-
1074
-
1075
-    /**
1076
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1077
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1078
-     * method of including extra select information.
1079
-     *
1080
-     * @param array             $query_params
1081
-     * @param null|array|string $columns_to_select
1082
-     * @return null|CustomSelects
1083
-     * @throws InvalidArgumentException
1084
-     */
1085
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1086
-    {
1087
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1088
-            return null;
1089
-        }
1090
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1091
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1092
-        return new CustomSelects($selects);
1093
-    }
1094
-
1095
-
1096
-
1097
-    /**
1098
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1099
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1100
-     * take care of joins, field preparation etc.
1101
-     *
1102
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1103
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1104
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1105
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1106
-     *                                  override this and set the select to "*", or a specific column name, like
1107
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1108
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1109
-     *                                  the aliases used to refer to this selection, and values are to be
1110
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1111
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1112
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1113
-     * @throws EE_Error
1114
-     */
1115
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1116
-    {
1117
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1118
-    }
1119
-
1120
-
1121
-
1122
-    /**
1123
-     * For creating a custom select statement
1124
-     *
1125
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1126
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1127
-     *                                 SQL, and 1=>is the datatype
1128
-     * @throws EE_Error
1129
-     * @return string
1130
-     */
1131
-    private function _construct_select_from_input($columns_to_select)
1132
-    {
1133
-        if (is_array($columns_to_select)) {
1134
-            $select_sql_array = array();
1135
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1136
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1137
-                    throw new EE_Error(
1138
-                        sprintf(
1139
-                            __(
1140
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1141
-                                'event_espresso'
1142
-                            ),
1143
-                            $selection_and_datatype,
1144
-                            $alias
1145
-                        )
1146
-                    );
1147
-                }
1148
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1149
-                    throw new EE_Error(
1150
-                        sprintf(
1151
-                            esc_html__(
1152
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1153
-                                'event_espresso'
1154
-                            ),
1155
-                            $selection_and_datatype[1],
1156
-                            $selection_and_datatype[0],
1157
-                            $alias,
1158
-                            implode(', ', $this->_valid_wpdb_data_types)
1159
-                        )
1160
-                    );
1161
-                }
1162
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1163
-            }
1164
-            $columns_to_select_string = implode(', ', $select_sql_array);
1165
-        } else {
1166
-            $columns_to_select_string = $columns_to_select;
1167
-        }
1168
-        return $columns_to_select_string;
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1175
-     *
1176
-     * @return string
1177
-     * @throws EE_Error
1178
-     */
1179
-    public function primary_key_name()
1180
-    {
1181
-        return $this->get_primary_key_field()->get_name();
1182
-    }
1183
-
1184
-
1185
-
1186
-    /**
1187
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1188
-     * If there is no primary key on this model, $id is treated as primary key string
1189
-     *
1190
-     * @param mixed $id int or string, depending on the type of the model's primary key
1191
-     * @return EE_Base_Class
1192
-     */
1193
-    public function get_one_by_ID($id)
1194
-    {
1195
-        if ($this->get_from_entity_map($id)) {
1196
-            return $this->get_from_entity_map($id);
1197
-        }
1198
-        return $this->get_one(
1199
-            $this->alter_query_params_to_restrict_by_ID(
1200
-                $id,
1201
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1202
-            )
1203
-        );
1204
-    }
1205
-
1206
-
1207
-
1208
-    /**
1209
-     * Alters query parameters to only get items with this ID are returned.
1210
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1211
-     * or could just be a simple primary key ID
1212
-     *
1213
-     * @param int   $id
1214
-     * @param array $query_params
1215
-     * @return array of normal query params, @see EEM_Base::get_all
1216
-     * @throws EE_Error
1217
-     */
1218
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1219
-    {
1220
-        if (! isset($query_params[0])) {
1221
-            $query_params[0] = array();
1222
-        }
1223
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1224
-        if ($conditions_from_id === null) {
1225
-            $query_params[0][$this->primary_key_name()] = $id;
1226
-        } else {
1227
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1228
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1229
-        }
1230
-        return $query_params;
1231
-    }
1232
-
1233
-
1234
-
1235
-    /**
1236
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1237
-     * array. If no item is found, null is returned.
1238
-     *
1239
-     * @param array $query_params like EEM_Base's $query_params variable.
1240
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1241
-     * @throws EE_Error
1242
-     */
1243
-    public function get_one($query_params = array())
1244
-    {
1245
-        if (! is_array($query_params)) {
1246
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1247
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1248
-                    gettype($query_params)), '4.6.0');
1249
-            $query_params = array();
1250
-        }
1251
-        $query_params['limit'] = 1;
1252
-        $items = $this->get_all($query_params);
1253
-        if (empty($items)) {
1254
-            return null;
1255
-        }
1256
-        return array_shift($items);
1257
-    }
1258
-
1259
-
1260
-
1261
-    /**
1262
-     * Returns the next x number of items in sequence from the given value as
1263
-     * found in the database matching the given query conditions.
1264
-     *
1265
-     * @param mixed $current_field_value    Value used for the reference point.
1266
-     * @param null  $field_to_order_by      What field is used for the
1267
-     *                                      reference point.
1268
-     * @param int   $limit                  How many to return.
1269
-     * @param array $query_params           Extra conditions on the query.
1270
-     * @param null  $columns_to_select      If left null, then an array of
1271
-     *                                      EE_Base_Class objects is returned,
1272
-     *                                      otherwise you can indicate just the
1273
-     *                                      columns you want returned.
1274
-     * @return EE_Base_Class[]|array
1275
-     * @throws EE_Error
1276
-     */
1277
-    public function next_x(
1278
-        $current_field_value,
1279
-        $field_to_order_by = null,
1280
-        $limit = 1,
1281
-        $query_params = array(),
1282
-        $columns_to_select = null
1283
-    ) {
1284
-        return $this->_get_consecutive(
1285
-            $current_field_value,
1286
-            '>',
1287
-            $field_to_order_by,
1288
-            $limit,
1289
-            $query_params,
1290
-            $columns_to_select
1291
-        );
1292
-    }
1293
-
1294
-
1295
-
1296
-    /**
1297
-     * Returns the previous x number of items in sequence from the given value
1298
-     * as found in the database matching the given query conditions.
1299
-     *
1300
-     * @param mixed $current_field_value    Value used for the reference point.
1301
-     * @param null  $field_to_order_by      What field is used for the
1302
-     *                                      reference point.
1303
-     * @param int   $limit                  How many to return.
1304
-     * @param array $query_params           Extra conditions on the query.
1305
-     * @param null  $columns_to_select      If left null, then an array of
1306
-     *                                      EE_Base_Class objects is returned,
1307
-     *                                      otherwise you can indicate just the
1308
-     *                                      columns you want returned.
1309
-     * @return EE_Base_Class[]|array
1310
-     * @throws EE_Error
1311
-     */
1312
-    public function previous_x(
1313
-        $current_field_value,
1314
-        $field_to_order_by = null,
1315
-        $limit = 1,
1316
-        $query_params = array(),
1317
-        $columns_to_select = null
1318
-    ) {
1319
-        return $this->_get_consecutive(
1320
-            $current_field_value,
1321
-            '<',
1322
-            $field_to_order_by,
1323
-            $limit,
1324
-            $query_params,
1325
-            $columns_to_select
1326
-        );
1327
-    }
1328
-
1329
-
1330
-
1331
-    /**
1332
-     * Returns the next item in sequence from the given value as found in the
1333
-     * database matching the given query conditions.
1334
-     *
1335
-     * @param mixed $current_field_value    Value used for the reference point.
1336
-     * @param null  $field_to_order_by      What field is used for the
1337
-     *                                      reference point.
1338
-     * @param array $query_params           Extra conditions on the query.
1339
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1340
-     *                                      object is returned, otherwise you
1341
-     *                                      can indicate just the columns you
1342
-     *                                      want and a single array indexed by
1343
-     *                                      the columns will be returned.
1344
-     * @return EE_Base_Class|null|array()
1345
-     * @throws EE_Error
1346
-     */
1347
-    public function next(
1348
-        $current_field_value,
1349
-        $field_to_order_by = null,
1350
-        $query_params = array(),
1351
-        $columns_to_select = null
1352
-    ) {
1353
-        $results = $this->_get_consecutive(
1354
-            $current_field_value,
1355
-            '>',
1356
-            $field_to_order_by,
1357
-            1,
1358
-            $query_params,
1359
-            $columns_to_select
1360
-        );
1361
-        return empty($results) ? null : reset($results);
1362
-    }
1363
-
1364
-
1365
-
1366
-    /**
1367
-     * Returns the previous item in sequence from the given value as found in
1368
-     * the database matching the given query conditions.
1369
-     *
1370
-     * @param mixed $current_field_value    Value used for the reference point.
1371
-     * @param null  $field_to_order_by      What field is used for the
1372
-     *                                      reference point.
1373
-     * @param array $query_params           Extra conditions on the query.
1374
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1375
-     *                                      object is returned, otherwise you
1376
-     *                                      can indicate just the columns you
1377
-     *                                      want and a single array indexed by
1378
-     *                                      the columns will be returned.
1379
-     * @return EE_Base_Class|null|array()
1380
-     * @throws EE_Error
1381
-     */
1382
-    public function previous(
1383
-        $current_field_value,
1384
-        $field_to_order_by = null,
1385
-        $query_params = array(),
1386
-        $columns_to_select = null
1387
-    ) {
1388
-        $results = $this->_get_consecutive(
1389
-            $current_field_value,
1390
-            '<',
1391
-            $field_to_order_by,
1392
-            1,
1393
-            $query_params,
1394
-            $columns_to_select
1395
-        );
1396
-        return empty($results) ? null : reset($results);
1397
-    }
1398
-
1399
-
1400
-
1401
-    /**
1402
-     * Returns the a consecutive number of items in sequence from the given
1403
-     * value as found in the database matching the given query conditions.
1404
-     *
1405
-     * @param mixed  $current_field_value   Value used for the reference point.
1406
-     * @param string $operand               What operand is used for the sequence.
1407
-     * @param string $field_to_order_by     What field is used for the reference point.
1408
-     * @param int    $limit                 How many to return.
1409
-     * @param array  $query_params          Extra conditions on the query.
1410
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1411
-     *                                      otherwise you can indicate just the columns you want returned.
1412
-     * @return EE_Base_Class[]|array
1413
-     * @throws EE_Error
1414
-     */
1415
-    protected function _get_consecutive(
1416
-        $current_field_value,
1417
-        $operand = '>',
1418
-        $field_to_order_by = null,
1419
-        $limit = 1,
1420
-        $query_params = array(),
1421
-        $columns_to_select = null
1422
-    ) {
1423
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1424
-        if (empty($field_to_order_by)) {
1425
-            if ($this->has_primary_key_field()) {
1426
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1427
-            } else {
1428
-                if (WP_DEBUG) {
1429
-                    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).',
1430
-                        'event_espresso'));
1431
-                }
1432
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1433
-                return array();
1434
-            }
1435
-        }
1436
-        if (! is_array($query_params)) {
1437
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1438
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1439
-                    gettype($query_params)), '4.6.0');
1440
-            $query_params = array();
1441
-        }
1442
-        //let's add the where query param for consecutive look up.
1443
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1444
-        $query_params['limit'] = $limit;
1445
-        //set direction
1446
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1447
-        $query_params['order_by'] = $operand === '>'
1448
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1449
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1450
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1451
-        if (empty($columns_to_select)) {
1452
-            return $this->get_all($query_params);
1453
-        }
1454
-        //getting just the fields
1455
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1456
-    }
1457
-
1458
-
1459
-
1460
-    /**
1461
-     * This sets the _timezone property after model object has been instantiated.
1462
-     *
1463
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1464
-     */
1465
-    public function set_timezone($timezone)
1466
-    {
1467
-        if ($timezone !== null) {
1468
-            $this->_timezone = $timezone;
1469
-        }
1470
-        //note we need to loop through relations and set the timezone on those objects as well.
1471
-        foreach ($this->_model_relations as $relation) {
1472
-            $relation->set_timezone($timezone);
1473
-        }
1474
-        //and finally we do the same for any datetime fields
1475
-        foreach ($this->_fields as $field) {
1476
-            if ($field instanceof EE_Datetime_Field) {
1477
-                $field->set_timezone($timezone);
1478
-            }
1479
-        }
1480
-    }
1481
-
1482
-
1483
-
1484
-    /**
1485
-     * This just returns whatever is set for the current timezone.
1486
-     *
1487
-     * @access public
1488
-     * @return string
1489
-     */
1490
-    public function get_timezone()
1491
-    {
1492
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1493
-        if (empty($this->_timezone)) {
1494
-            foreach ($this->_fields as $field) {
1495
-                if ($field instanceof EE_Datetime_Field) {
1496
-                    $this->set_timezone($field->get_timezone());
1497
-                    break;
1498
-                }
1499
-            }
1500
-        }
1501
-        //if timezone STILL empty then return the default timezone for the site.
1502
-        if (empty($this->_timezone)) {
1503
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1504
-        }
1505
-        return $this->_timezone;
1506
-    }
1507
-
1508
-
1509
-
1510
-    /**
1511
-     * This returns the date formats set for the given field name and also ensures that
1512
-     * $this->_timezone property is set correctly.
1513
-     *
1514
-     * @since 4.6.x
1515
-     * @param string $field_name The name of the field the formats are being retrieved for.
1516
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1517
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1518
-     * @return array formats in an array with the date format first, and the time format last.
1519
-     */
1520
-    public function get_formats_for($field_name, $pretty = false)
1521
-    {
1522
-        $field_settings = $this->field_settings_for($field_name);
1523
-        //if not a valid EE_Datetime_Field then throw error
1524
-        if (! $field_settings instanceof EE_Datetime_Field) {
1525
-            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.',
1526
-                'event_espresso'), $field_name));
1527
-        }
1528
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1529
-        //the field.
1530
-        $this->_timezone = $field_settings->get_timezone();
1531
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1532
-    }
1533
-
1534
-
1535
-
1536
-    /**
1537
-     * This returns the current time in a format setup for a query on this model.
1538
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1539
-     * it will return:
1540
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1541
-     *  NOW
1542
-     *  - or a unix timestamp (equivalent to time())
1543
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1544
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1545
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1546
-     * @since 4.6.x
1547
-     * @param string $field_name       The field the current time is needed for.
1548
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1549
-     *                                 formatted string matching the set format for the field in the set timezone will
1550
-     *                                 be returned.
1551
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1552
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1553
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1554
-     *                                 exception is triggered.
1555
-     */
1556
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1557
-    {
1558
-        $formats = $this->get_formats_for($field_name);
1559
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1560
-        if ($timestamp) {
1561
-            return $DateTime->format('U');
1562
-        }
1563
-        //not returning timestamp, so return formatted string in timezone.
1564
-        switch ($what) {
1565
-            case 'time' :
1566
-                return $DateTime->format($formats[1]);
1567
-                break;
1568
-            case 'date' :
1569
-                return $DateTime->format($formats[0]);
1570
-                break;
1571
-            default :
1572
-                return $DateTime->format(implode(' ', $formats));
1573
-                break;
1574
-        }
1575
-    }
1576
-
1577
-
1578
-
1579
-    /**
1580
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1581
-     * for the model are.  Returns a DateTime object.
1582
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1583
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1584
-     * ignored.
1585
-     *
1586
-     * @param string $field_name      The field being setup.
1587
-     * @param string $timestring      The date time string being used.
1588
-     * @param string $incoming_format The format for the time string.
1589
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1590
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1591
-     *                                format is
1592
-     *                                'U', this is ignored.
1593
-     * @return DateTime
1594
-     * @throws EE_Error
1595
-     */
1596
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1597
-    {
1598
-        //just using this to ensure the timezone is set correctly internally
1599
-        $this->get_formats_for($field_name);
1600
-        //load EEH_DTT_Helper
1601
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1602
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1603
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1604
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1605
-    }
1606
-
1607
-
1608
-
1609
-    /**
1610
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1611
-     *
1612
-     * @return EE_Table_Base[]
1613
-     */
1614
-    public function get_tables()
1615
-    {
1616
-        return $this->_tables;
1617
-    }
1618
-
1619
-
1620
-
1621
-    /**
1622
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1623
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1624
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1625
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1626
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1627
-     * model object with EVT_ID = 1
1628
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1629
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1630
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1631
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1632
-     * are not specified)
1633
-     *
1634
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1635
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1636
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1637
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1638
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1639
-     *                                         ID=34, we'd use this method as follows:
1640
-     *                                         EEM_Transaction::instance()->update(
1641
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1642
-     *                                         array(array('TXN_ID'=>34)));
1643
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1644
-     *                                         in client code into what's expected to be stored on each field. Eg,
1645
-     *                                         consider updating Question's QST_admin_label field is of type
1646
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1647
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1648
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1649
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1650
-     *                                         TRUE, it is assumed that you've already called
1651
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1652
-     *                                         malicious javascript. However, if
1653
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1654
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1655
-     *                                         and every other field, before insertion. We provide this parameter
1656
-     *                                         because model objects perform their prepare_for_set function on all
1657
-     *                                         their values, and so don't need to be called again (and in many cases,
1658
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1659
-     *                                         prepare_for_set method...)
1660
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1661
-     *                                         in this model's entity map according to $fields_n_values that match
1662
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1663
-     *                                         by setting this to FALSE, but be aware that model objects being used
1664
-     *                                         could get out-of-sync with the database
1665
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1666
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1667
-     *                                         bad)
1668
-     * @throws EE_Error
1669
-     */
1670
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1671
-    {
1672
-        if (! is_array($query_params)) {
1673
-            EE_Error::doing_it_wrong('EEM_Base::update',
1674
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1675
-                    gettype($query_params)), '4.6.0');
1676
-            $query_params = array();
1677
-        }
1678
-        /**
1679
-         * Action called before a model update call has been made.
1680
-         *
1681
-         * @param EEM_Base $model
1682
-         * @param array    $fields_n_values the updated fields and their new values
1683
-         * @param array    $query_params    @see EEM_Base::get_all()
1684
-         */
1685
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1686
-        /**
1687
-         * Filters the fields about to be updated given the query parameters. You can provide the
1688
-         * $query_params to $this->get_all() to find exactly which records will be updated
1689
-         *
1690
-         * @param array    $fields_n_values fields and their new values
1691
-         * @param EEM_Base $model           the model being queried
1692
-         * @param array    $query_params    see EEM_Base::get_all()
1693
-         */
1694
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1695
-            $query_params);
1696
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1697
-        //to do that, for each table, verify that it's PK isn't null.
1698
-        $tables = $this->get_tables();
1699
-        //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
1700
-        //NOTE: we should make this code more efficient by NOT querying twice
1701
-        //before the real update, but that needs to first go through ALPHA testing
1702
-        //as it's dangerous. says Mike August 8 2014
1703
-        //we want to make sure the default_where strategy is ignored
1704
-        $this->_ignore_where_strategy = true;
1705
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1706
-        foreach ($wpdb_select_results as $wpdb_result) {
1707
-            // type cast stdClass as array
1708
-            $wpdb_result = (array)$wpdb_result;
1709
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1710
-            if ($this->has_primary_key_field()) {
1711
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1712
-            } else {
1713
-                //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)
1714
-                $main_table_pk_value = null;
1715
-            }
1716
-            //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
1717
-            //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
1718
-            if (count($tables) > 1) {
1719
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1720
-                //in that table, and so we'll want to insert one
1721
-                foreach ($tables as $table_obj) {
1722
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1723
-                    //if there is no private key for this table on the results, it means there's no entry
1724
-                    //in this table, right? so insert a row in the current table, using any fields available
1725
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1726
-                           && $wpdb_result[$this_table_pk_column])
1727
-                    ) {
1728
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1729
-                            $main_table_pk_value);
1730
-                        //if we died here, report the error
1731
-                        if (! $success) {
1732
-                            return false;
1733
-                        }
1734
-                    }
1735
-                }
1736
-            }
1737
-            //				//and now check that if we have cached any models by that ID on the model, that
1738
-            //				//they also get updated properly
1739
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1740
-            //				if( $model_object ){
1741
-            //					foreach( $fields_n_values as $field => $value ){
1742
-            //						$model_object->set($field, $value);
1743
-            //let's make sure default_where strategy is followed now
1744
-            $this->_ignore_where_strategy = false;
1745
-        }
1746
-        //if we want to keep model objects in sync, AND
1747
-        //if this wasn't called from a model object (to update itself)
1748
-        //then we want to make sure we keep all the existing
1749
-        //model objects in sync with the db
1750
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1751
-            if ($this->has_primary_key_field()) {
1752
-                $model_objs_affected_ids = $this->get_col($query_params);
1753
-            } else {
1754
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1755
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1756
-                $model_objs_affected_ids = array();
1757
-                foreach ($models_affected_key_columns as $row) {
1758
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1759
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1760
-                }
1761
-            }
1762
-            if (! $model_objs_affected_ids) {
1763
-                //wait wait wait- if nothing was affected let's stop here
1764
-                return 0;
1765
-            }
1766
-            foreach ($model_objs_affected_ids as $id) {
1767
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1768
-                if ($model_obj_in_entity_map) {
1769
-                    foreach ($fields_n_values as $field => $new_value) {
1770
-                        $model_obj_in_entity_map->set($field, $new_value);
1771
-                    }
1772
-                }
1773
-            }
1774
-            //if there is a primary key on this model, we can now do a slight optimization
1775
-            if ($this->has_primary_key_field()) {
1776
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1777
-                $query_params = array(
1778
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1779
-                    'limit'                    => count($model_objs_affected_ids),
1780
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1781
-                );
1782
-            }
1783
-        }
1784
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1785
-        $SQL = "UPDATE "
1786
-               . $model_query_info->get_full_join_sql()
1787
-               . " SET "
1788
-               . $this->_construct_update_sql($fields_n_values)
1789
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1790
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1791
-        /**
1792
-         * Action called after a model update call has been made.
1793
-         *
1794
-         * @param EEM_Base $model
1795
-         * @param array    $fields_n_values the updated fields and their new values
1796
-         * @param array    $query_params    @see EEM_Base::get_all()
1797
-         * @param int      $rows_affected
1798
-         */
1799
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1800
-        return $rows_affected;//how many supposedly got updated
1801
-    }
1802
-
1803
-
1804
-
1805
-    /**
1806
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1807
-     * are teh values of the field specified (or by default the primary key field)
1808
-     * that matched the query params. Note that you should pass the name of the
1809
-     * model FIELD, not the database table's column name.
1810
-     *
1811
-     * @param array  $query_params @see EEM_Base::get_all()
1812
-     * @param string $field_to_select
1813
-     * @return array just like $wpdb->get_col()
1814
-     * @throws EE_Error
1815
-     */
1816
-    public function get_col($query_params = array(), $field_to_select = null)
1817
-    {
1818
-        if ($field_to_select) {
1819
-            $field = $this->field_settings_for($field_to_select);
1820
-        } elseif ($this->has_primary_key_field()) {
1821
-            $field = $this->get_primary_key_field();
1822
-        } else {
1823
-            //no primary key, just grab the first column
1824
-            $field = reset($this->field_settings());
1825
-        }
1826
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1827
-        $select_expressions = $field->get_qualified_column();
1828
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1829
-        return $this->_do_wpdb_query('get_col', array($SQL));
1830
-    }
1831
-
1832
-
1833
-
1834
-    /**
1835
-     * Returns a single column value for a single row from the database
1836
-     *
1837
-     * @param array  $query_params    @see EEM_Base::get_all()
1838
-     * @param string $field_to_select @see EEM_Base::get_col()
1839
-     * @return string
1840
-     * @throws EE_Error
1841
-     */
1842
-    public function get_var($query_params = array(), $field_to_select = null)
1843
-    {
1844
-        $query_params['limit'] = 1;
1845
-        $col = $this->get_col($query_params, $field_to_select);
1846
-        if (! empty($col)) {
1847
-            return reset($col);
1848
-        }
1849
-        return null;
1850
-    }
1851
-
1852
-
1853
-
1854
-    /**
1855
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1856
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1857
-     * injection, but currently no further filtering is done
1858
-     *
1859
-     * @global      $wpdb
1860
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1861
-     *                               be updated to in the DB
1862
-     * @return string of SQL
1863
-     * @throws EE_Error
1864
-     */
1865
-    public function _construct_update_sql($fields_n_values)
1866
-    {
1867
-        /** @type WPDB $wpdb */
1868
-        global $wpdb;
1869
-        $cols_n_values = array();
1870
-        foreach ($fields_n_values as $field_name => $value) {
1871
-            $field_obj = $this->field_settings_for($field_name);
1872
-            //if the value is NULL, we want to assign the value to that.
1873
-            //wpdb->prepare doesn't really handle that properly
1874
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1875
-            $value_sql = $prepared_value === null ? 'NULL'
1876
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1877
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1878
-        }
1879
-        return implode(",", $cols_n_values);
1880
-    }
1881
-
1882
-
1883
-
1884
-    /**
1885
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1886
-     * Performs a HARD delete, meaning the database row should always be removed,
1887
-     * not just have a flag field on it switched
1888
-     * Wrapper for EEM_Base::delete_permanently()
1889
-     *
1890
-     * @param mixed $id
1891
-     * @param boolean $allow_blocking
1892
-     * @return int the number of rows deleted
1893
-     * @throws EE_Error
1894
-     */
1895
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1896
-    {
1897
-        return $this->delete_permanently(
1898
-            array(
1899
-                array($this->get_primary_key_field()->get_name() => $id),
1900
-                'limit' => 1,
1901
-            ),
1902
-            $allow_blocking
1903
-        );
1904
-    }
1905
-
1906
-
1907
-
1908
-    /**
1909
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1910
-     * Wrapper for EEM_Base::delete()
1911
-     *
1912
-     * @param mixed $id
1913
-     * @param boolean $allow_blocking
1914
-     * @return int the number of rows deleted
1915
-     * @throws EE_Error
1916
-     */
1917
-    public function delete_by_ID($id, $allow_blocking = true)
1918
-    {
1919
-        return $this->delete(
1920
-            array(
1921
-                array($this->get_primary_key_field()->get_name() => $id),
1922
-                'limit' => 1,
1923
-            ),
1924
-            $allow_blocking
1925
-        );
1926
-    }
1927
-
1928
-
1929
-
1930
-    /**
1931
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1932
-     * meaning if the model has a field that indicates its been "trashed" or
1933
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1934
-     *
1935
-     * @see EEM_Base::delete_permanently
1936
-     * @param array   $query_params
1937
-     * @param boolean $allow_blocking
1938
-     * @return int how many rows got deleted
1939
-     * @throws EE_Error
1940
-     */
1941
-    public function delete($query_params, $allow_blocking = true)
1942
-    {
1943
-        return $this->delete_permanently($query_params, $allow_blocking);
1944
-    }
1945
-
1946
-
1947
-
1948
-    /**
1949
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1950
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1951
-     * as archived, not actually deleted
1952
-     *
1953
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1954
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1955
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1956
-     *                                deletes regardless of other objects which may depend on it. Its generally
1957
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1958
-     *                                DB
1959
-     * @return int how many rows got deleted
1960
-     * @throws EE_Error
1961
-     */
1962
-    public function delete_permanently($query_params, $allow_blocking = true)
1963
-    {
1964
-        /**
1965
-         * Action called just before performing a real deletion query. You can use the
1966
-         * model and its $query_params to find exactly which items will be deleted
1967
-         *
1968
-         * @param EEM_Base $model
1969
-         * @param array    $query_params   @see EEM_Base::get_all()
1970
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1971
-         *                                 to block (prevent) this deletion
1972
-         */
1973
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1974
-        //some MySQL databases may be running safe mode, which may restrict
1975
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1976
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1977
-        //to delete them
1978
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1979
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1980
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1981
-            $columns_and_ids_for_deleting
1982
-        );
1983
-        /**
1984
-         * Allows client code to act on the items being deleted before the query is actually executed.
1985
-         *
1986
-         * @param EEM_Base $this  The model instance being acted on.
1987
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1988
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1989
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1990
-         *                                                  derived from the incoming query parameters.
1991
-         *                                                  @see details on the structure of this array in the phpdocs
1992
-         *                                                  for the `_get_ids_for_delete_method`
1993
-         *
1994
-         */
1995
-        do_action('AHEE__EEM_Base__delete__before_query',
1996
-            $this,
1997
-            $query_params,
1998
-            $allow_blocking,
1999
-            $columns_and_ids_for_deleting
2000
-        );
2001
-        if ($deletion_where_query_part) {
2002
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2003
-            $table_aliases = array_keys($this->_tables);
2004
-            $SQL = "DELETE "
2005
-                   . implode(", ", $table_aliases)
2006
-                   . " FROM "
2007
-                   . $model_query_info->get_full_join_sql()
2008
-                   . " WHERE "
2009
-                   . $deletion_where_query_part;
2010
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2011
-        } else {
2012
-            $rows_deleted = 0;
2013
-        }
2014
-
2015
-        //Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2016
-        //there was no error with the delete query.
2017
-        if ($this->has_primary_key_field()
2018
-            && $rows_deleted !== false
2019
-            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2020
-        ) {
2021
-            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2022
-            foreach ($ids_for_removal as $id) {
2023
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2024
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2025
-                }
2026
-            }
2027
-
2028
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2029
-            //`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2030
-            //unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2031
-            // (although it is possible).
2032
-            //Note this can be skipped by using the provided filter and returning false.
2033
-            if (apply_filters(
2034
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2035
-                ! $this instanceof EEM_Extra_Meta,
2036
-                $this
2037
-            )) {
2038
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2039
-                    0 => array(
2040
-                        'EXM_type' => $this->get_this_model_name(),
2041
-                        'OBJ_ID'   => array(
2042
-                            'IN',
2043
-                            $ids_for_removal
2044
-                        )
2045
-                    )
2046
-                ));
2047
-            }
2048
-        }
2049
-
2050
-        /**
2051
-         * Action called just after performing a real deletion query. Although at this point the
2052
-         * items should have been deleted
2053
-         *
2054
-         * @param EEM_Base $model
2055
-         * @param array    $query_params @see EEM_Base::get_all()
2056
-         * @param int      $rows_deleted
2057
-         */
2058
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2059
-        return $rows_deleted;//how many supposedly got deleted
2060
-    }
2061
-
2062
-
2063
-
2064
-    /**
2065
-     * Checks all the relations that throw error messages when there are blocking related objects
2066
-     * for related model objects. If there are any related model objects on those relations,
2067
-     * adds an EE_Error, and return true
2068
-     *
2069
-     * @param EE_Base_Class|int $this_model_obj_or_id
2070
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2071
-     *                                                 should be ignored when determining whether there are related
2072
-     *                                                 model objects which block this model object's deletion. Useful
2073
-     *                                                 if you know A is related to B and are considering deleting A,
2074
-     *                                                 but want to see if A has any other objects blocking its deletion
2075
-     *                                                 before removing the relation between A and B
2076
-     * @return boolean
2077
-     * @throws EE_Error
2078
-     */
2079
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2080
-    {
2081
-        //first, if $ignore_this_model_obj was supplied, get its model
2082
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2083
-            $ignored_model = $ignore_this_model_obj->get_model();
2084
-        } else {
2085
-            $ignored_model = null;
2086
-        }
2087
-        //now check all the relations of $this_model_obj_or_id and see if there
2088
-        //are any related model objects blocking it?
2089
-        $is_blocked = false;
2090
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2091
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2092
-                //if $ignore_this_model_obj was supplied, then for the query
2093
-                //on that model needs to be told to ignore $ignore_this_model_obj
2094
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2095
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2096
-                        array(
2097
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2098
-                                '!=',
2099
-                                $ignore_this_model_obj->ID(),
2100
-                            ),
2101
-                        ),
2102
-                    ));
2103
-                } else {
2104
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2105
-                }
2106
-                if ($related_model_objects) {
2107
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2108
-                    $is_blocked = true;
2109
-                }
2110
-            }
2111
-        }
2112
-        return $is_blocked;
2113
-    }
2114
-
2115
-
2116
-    /**
2117
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2118
-     * @param array $row_results_for_deleting
2119
-     * @param bool  $allow_blocking
2120
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2121
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2122
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2123
-     *                 deleted. Example:
2124
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2125
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2126
-     *                 where each element is a group of columns and values that get deleted. Example:
2127
-     *                      array(
2128
-     *                          0 => array(
2129
-     *                              'Term_Relationship.object_id' => 1
2130
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2131
-     *                          ),
2132
-     *                          1 => array(
2133
-     *                              'Term_Relationship.object_id' => 1
2134
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2135
-     *                          )
2136
-     *                      )
2137
-     * @throws EE_Error
2138
-     */
2139
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2140
-    {
2141
-        $ids_to_delete_indexed_by_column = array();
2142
-        if ($this->has_primary_key_field()) {
2143
-            $primary_table = $this->_get_main_table();
2144
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2145
-            $other_tables = $this->_get_other_tables();
2146
-            $ids_to_delete_indexed_by_column = $query = array();
2147
-            foreach ($row_results_for_deleting as $item_to_delete) {
2148
-                //before we mark this item for deletion,
2149
-                //make sure there's no related entities blocking its deletion (if we're checking)
2150
-                if (
2151
-                    $allow_blocking
2152
-                    && $this->delete_is_blocked_by_related_models(
2153
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2154
-                    )
2155
-                ) {
2156
-                    continue;
2157
-                }
2158
-                //primary table deletes
2159
-                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2160
-                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2161
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2162
-                }
2163
-            }
2164
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2165
-            $fields = $this->get_combined_primary_key_fields();
2166
-            foreach ($row_results_for_deleting as $item_to_delete) {
2167
-                $ids_to_delete_indexed_by_column_for_row = array();
2168
-                foreach ($fields as $cpk_field) {
2169
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2170
-                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2171
-                            $item_to_delete[$cpk_field->get_qualified_column()];
2172
-                    }
2173
-                }
2174
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2175
-            }
2176
-        } else {
2177
-            //so there's no primary key and no combined key...
2178
-            //sorry, can't help you
2179
-            throw new EE_Error(
2180
-                sprintf(
2181
-                    __(
2182
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2183
-                        "event_espresso"
2184
-                    ), get_class($this)
2185
-                )
2186
-            );
2187
-        }
2188
-        return $ids_to_delete_indexed_by_column;
2189
-    }
2190
-
2191
-
2192
-    /**
2193
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2194
-     * the corresponding query_part for the query performing the delete.
2195
-     *
2196
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2197
-     * @return string
2198
-     * @throws EE_Error
2199
-     */
2200
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2201
-        $query_part = '';
2202
-        if (empty($ids_to_delete_indexed_by_column)) {
2203
-            return $query_part;
2204
-        } elseif ($this->has_primary_key_field()) {
2205
-            $query = array();
2206
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2207
-                //make sure we have unique $ids
2208
-                $ids = array_unique($ids);
2209
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2210
-            }
2211
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2212
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2213
-            $ways_to_identify_a_row = array();
2214
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2215
-                $values_for_each_combined_primary_key_for_a_row = array();
2216
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2217
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2218
-                }
2219
-                $ways_to_identify_a_row[] = '('
2220
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2221
-                                            . ')';
2222
-            }
2223
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2224
-        }
2225
-        return $query_part;
2226
-    }
2227
-
2228
-
2229
-
2230
-    /**
2231
-     * Gets the model field by the fully qualified name
2232
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2233
-     * @return EE_Model_Field_Base
2234
-     */
2235
-    public function get_field_by_column($qualified_column_name)
2236
-    {
2237
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2238
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2239
-               return $field_obj;
2240
-           }
2241
-       }
2242
-        throw new EE_Error(
2243
-            sprintf(
2244
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2245
-                $this->get_this_model_name(),
2246
-                $qualified_column_name
2247
-            )
2248
-        );
2249
-    }
2250
-
2251
-
2252
-
2253
-    /**
2254
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2255
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2256
-     * column
2257
-     *
2258
-     * @param array  $query_params   like EEM_Base::get_all's
2259
-     * @param string $field_to_count field on model to count by (not column name)
2260
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2261
-     *                               that by the setting $distinct to TRUE;
2262
-     * @return int
2263
-     * @throws EE_Error
2264
-     */
2265
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2266
-    {
2267
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2268
-        if ($field_to_count) {
2269
-            $field_obj = $this->field_settings_for($field_to_count);
2270
-            $column_to_count = $field_obj->get_qualified_column();
2271
-        } elseif ($this->has_primary_key_field()) {
2272
-            $pk_field_obj = $this->get_primary_key_field();
2273
-            $column_to_count = $pk_field_obj->get_qualified_column();
2274
-        } else {
2275
-            //there's no primary key
2276
-            //if we're counting distinct items, and there's no primary key,
2277
-            //we need to list out the columns for distinction;
2278
-            //otherwise we can just use star
2279
-            if ($distinct) {
2280
-                $columns_to_use = array();
2281
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2282
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2283
-                }
2284
-                $column_to_count = implode(',', $columns_to_use);
2285
-            } else {
2286
-                $column_to_count = '*';
2287
-            }
2288
-        }
2289
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2290
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2291
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2292
-    }
2293
-
2294
-
2295
-
2296
-    /**
2297
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2298
-     *
2299
-     * @param array  $query_params like EEM_Base::get_all
2300
-     * @param string $field_to_sum name of field (array key in $_fields array)
2301
-     * @return float
2302
-     * @throws EE_Error
2303
-     */
2304
-    public function sum($query_params, $field_to_sum = null)
2305
-    {
2306
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2307
-        if ($field_to_sum) {
2308
-            $field_obj = $this->field_settings_for($field_to_sum);
2309
-        } else {
2310
-            $field_obj = $this->get_primary_key_field();
2311
-        }
2312
-        $column_to_count = $field_obj->get_qualified_column();
2313
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2314
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2315
-        $data_type = $field_obj->get_wpdb_data_type();
2316
-        if ($data_type === '%d' || $data_type === '%s') {
2317
-            return (float)$return_value;
2318
-        }
2319
-        //must be %f
2320
-        return (float)$return_value;
2321
-    }
2322
-
2323
-
2324
-
2325
-    /**
2326
-     * Just calls the specified method on $wpdb with the given arguments
2327
-     * Consolidates a little extra error handling code
2328
-     *
2329
-     * @param string $wpdb_method
2330
-     * @param array  $arguments_to_provide
2331
-     * @throws EE_Error
2332
-     * @global wpdb  $wpdb
2333
-     * @return mixed
2334
-     */
2335
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2336
-    {
2337
-        //if we're in maintenance mode level 2, DON'T run any queries
2338
-        //because level 2 indicates the database needs updating and
2339
-        //is probably out of sync with the code
2340
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2341
-            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.",
2342
-                "event_espresso")));
2343
-        }
2344
-        /** @type WPDB $wpdb */
2345
-        global $wpdb;
2346
-        if (! method_exists($wpdb, $wpdb_method)) {
2347
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2348
-                'event_espresso'), $wpdb_method));
2349
-        }
2350
-        if (WP_DEBUG) {
2351
-            $old_show_errors_value = $wpdb->show_errors;
2352
-            $wpdb->show_errors(false);
2353
-        }
2354
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2355
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2356
-        if (WP_DEBUG) {
2357
-            $wpdb->show_errors($old_show_errors_value);
2358
-            if (! empty($wpdb->last_error)) {
2359
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2360
-            }
2361
-            if ($result === false) {
2362
-                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"',
2363
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2364
-            }
2365
-        } elseif ($result === false) {
2366
-            EE_Error::add_error(
2367
-                sprintf(
2368
-                    __('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"',
2369
-                        'event_espresso'),
2370
-                    $wpdb_method,
2371
-                    var_export($arguments_to_provide, true),
2372
-                    $wpdb->last_error
2373
-                ),
2374
-                __FILE__,
2375
-                __FUNCTION__,
2376
-                __LINE__
2377
-            );
2378
-        }
2379
-        return $result;
2380
-    }
2381
-
2382
-
2383
-
2384
-    /**
2385
-     * Attempts to run the indicated WPDB method with the provided arguments,
2386
-     * and if there's an error tries to verify the DB is correct. Uses
2387
-     * the static property EEM_Base::$_db_verification_level to determine whether
2388
-     * we should try to fix the EE core db, the addons, or just give up
2389
-     *
2390
-     * @param string $wpdb_method
2391
-     * @param array  $arguments_to_provide
2392
-     * @return mixed
2393
-     */
2394
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2395
-    {
2396
-        /** @type WPDB $wpdb */
2397
-        global $wpdb;
2398
-        $wpdb->last_error = null;
2399
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2400
-        // was there an error running the query? but we don't care on new activations
2401
-        // (we're going to setup the DB anyway on new activations)
2402
-        if (($result === false || ! empty($wpdb->last_error))
2403
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2404
-        ) {
2405
-            switch (EEM_Base::$_db_verification_level) {
2406
-                case EEM_Base::db_verified_none :
2407
-                    // let's double-check core's DB
2408
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2409
-                    break;
2410
-                case EEM_Base::db_verified_core :
2411
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2412
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2413
-                    break;
2414
-                case EEM_Base::db_verified_addons :
2415
-                    // ummmm... you in trouble
2416
-                    return $result;
2417
-                    break;
2418
-            }
2419
-            if (! empty($error_message)) {
2420
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2421
-                trigger_error($error_message);
2422
-            }
2423
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2424
-        }
2425
-        return $result;
2426
-    }
2427
-
2428
-
2429
-
2430
-    /**
2431
-     * Verifies the EE core database is up-to-date and records that we've done it on
2432
-     * EEM_Base::$_db_verification_level
2433
-     *
2434
-     * @param string $wpdb_method
2435
-     * @param array  $arguments_to_provide
2436
-     * @return string
2437
-     */
2438
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2439
-    {
2440
-        /** @type WPDB $wpdb */
2441
-        global $wpdb;
2442
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2443
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2444
-        $error_message = sprintf(
2445
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2446
-                'event_espresso'),
2447
-            $wpdb->last_error,
2448
-            $wpdb_method,
2449
-            wp_json_encode($arguments_to_provide)
2450
-        );
2451
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2452
-        return $error_message;
2453
-    }
2454
-
2455
-
2456
-
2457
-    /**
2458
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2459
-     * EEM_Base::$_db_verification_level
2460
-     *
2461
-     * @param $wpdb_method
2462
-     * @param $arguments_to_provide
2463
-     * @return string
2464
-     */
2465
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2466
-    {
2467
-        /** @type WPDB $wpdb */
2468
-        global $wpdb;
2469
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2470
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2471
-        $error_message = sprintf(
2472
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2473
-                'event_espresso'),
2474
-            $wpdb->last_error,
2475
-            $wpdb_method,
2476
-            wp_json_encode($arguments_to_provide)
2477
-        );
2478
-        EE_System::instance()->initialize_addons();
2479
-        return $error_message;
2480
-    }
2481
-
2482
-
2483
-
2484
-    /**
2485
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2486
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2487
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2488
-     * ..."
2489
-     *
2490
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2491
-     * @return string
2492
-     */
2493
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2494
-    {
2495
-        return " FROM " . $model_query_info->get_full_join_sql() .
2496
-               $model_query_info->get_where_sql() .
2497
-               $model_query_info->get_group_by_sql() .
2498
-               $model_query_info->get_having_sql() .
2499
-               $model_query_info->get_order_by_sql() .
2500
-               $model_query_info->get_limit_sql();
2501
-    }
2502
-
2503
-
2504
-
2505
-    /**
2506
-     * Set to easily debug the next X queries ran from this model.
2507
-     *
2508
-     * @param int $count
2509
-     */
2510
-    public function show_next_x_db_queries($count = 1)
2511
-    {
2512
-        $this->_show_next_x_db_queries = $count;
2513
-    }
2514
-
2515
-
2516
-
2517
-    /**
2518
-     * @param $sql_query
2519
-     */
2520
-    public function show_db_query_if_previously_requested($sql_query)
2521
-    {
2522
-        if ($this->_show_next_x_db_queries > 0) {
2523
-            echo $sql_query;
2524
-            $this->_show_next_x_db_queries--;
2525
-        }
2526
-    }
2527
-
2528
-
2529
-
2530
-    /**
2531
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2532
-     * There are the 3 cases:
2533
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2534
-     * $otherModelObject has no ID, it is first saved.
2535
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2536
-     * has no ID, it is first saved.
2537
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2538
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2539
-     * join table
2540
-     *
2541
-     * @param        EE_Base_Class                     /int $thisModelObject
2542
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2543
-     * @param string $relationName                     , key in EEM_Base::_relations
2544
-     *                                                 an attendee to a group, you also want to specify which role they
2545
-     *                                                 will have in that group. So you would use this parameter to
2546
-     *                                                 specify array('role-column-name'=>'role-id')
2547
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2548
-     *                                                 to for relation to methods that allow you to further specify
2549
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2550
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2551
-     *                                                 because these will be inserted in any new rows created as well.
2552
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2553
-     * @throws EE_Error
2554
-     */
2555
-    public function add_relationship_to(
2556
-        $id_or_obj,
2557
-        $other_model_id_or_obj,
2558
-        $relationName,
2559
-        $extra_join_model_fields_n_values = array()
2560
-    ) {
2561
-        $relation_obj = $this->related_settings_for($relationName);
2562
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2563
-    }
2564
-
2565
-
2566
-
2567
-    /**
2568
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2569
-     * There are the 3 cases:
2570
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2571
-     * error
2572
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2573
-     * an error
2574
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2575
-     *
2576
-     * @param        EE_Base_Class /int $id_or_obj
2577
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2578
-     * @param string $relationName key in EEM_Base::_relations
2579
-     * @return boolean of success
2580
-     * @throws EE_Error
2581
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2582
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2583
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2584
-     *                             because these will be inserted in any new rows created as well.
2585
-     */
2586
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2587
-    {
2588
-        $relation_obj = $this->related_settings_for($relationName);
2589
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2590
-    }
2591
-
2592
-
2593
-
2594
-    /**
2595
-     * @param mixed           $id_or_obj
2596
-     * @param string          $relationName
2597
-     * @param array           $where_query_params
2598
-     * @param EE_Base_Class[] objects to which relations were removed
2599
-     * @return \EE_Base_Class[]
2600
-     * @throws EE_Error
2601
-     */
2602
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2603
-    {
2604
-        $relation_obj = $this->related_settings_for($relationName);
2605
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2606
-    }
2607
-
2608
-
2609
-
2610
-    /**
2611
-     * Gets all the related items of the specified $model_name, using $query_params.
2612
-     * Note: by default, we remove the "default query params"
2613
-     * because we want to get even deleted items etc.
2614
-     *
2615
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2616
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2617
-     * @param array  $query_params like EEM_Base::get_all
2618
-     * @return EE_Base_Class[]
2619
-     * @throws EE_Error
2620
-     */
2621
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2622
-    {
2623
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2624
-        $relation_settings = $this->related_settings_for($model_name);
2625
-        return $relation_settings->get_all_related($model_obj, $query_params);
2626
-    }
2627
-
2628
-
2629
-
2630
-    /**
2631
-     * Deletes all the model objects across the relation indicated by $model_name
2632
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2633
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2634
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2635
-     *
2636
-     * @param EE_Base_Class|int|string $id_or_obj
2637
-     * @param string                   $model_name
2638
-     * @param array                    $query_params
2639
-     * @return int how many deleted
2640
-     * @throws EE_Error
2641
-     */
2642
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2643
-    {
2644
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2645
-        $relation_settings = $this->related_settings_for($model_name);
2646
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2647
-    }
2648
-
2649
-
2650
-
2651
-    /**
2652
-     * Hard deletes all the model objects across the relation indicated by $model_name
2653
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2654
-     * the model objects can't be hard deleted because of blocking related model objects,
2655
-     * just does a soft-delete on them instead.
2656
-     *
2657
-     * @param EE_Base_Class|int|string $id_or_obj
2658
-     * @param string                   $model_name
2659
-     * @param array                    $query_params
2660
-     * @return int how many deleted
2661
-     * @throws EE_Error
2662
-     */
2663
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2664
-    {
2665
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2666
-        $relation_settings = $this->related_settings_for($model_name);
2667
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2668
-    }
2669
-
2670
-
2671
-
2672
-    /**
2673
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2674
-     * unless otherwise specified in the $query_params
2675
-     *
2676
-     * @param        int             /EE_Base_Class $id_or_obj
2677
-     * @param string $model_name     like 'Event', or 'Registration'
2678
-     * @param array  $query_params   like EEM_Base::get_all's
2679
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2680
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2681
-     *                               that by the setting $distinct to TRUE;
2682
-     * @return int
2683
-     * @throws EE_Error
2684
-     */
2685
-    public function count_related(
2686
-        $id_or_obj,
2687
-        $model_name,
2688
-        $query_params = array(),
2689
-        $field_to_count = null,
2690
-        $distinct = false
2691
-    ) {
2692
-        $related_model = $this->get_related_model_obj($model_name);
2693
-        //we're just going to use the query params on the related model's normal get_all query,
2694
-        //except add a condition to say to match the current mod
2695
-        if (! isset($query_params['default_where_conditions'])) {
2696
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2697
-        }
2698
-        $this_model_name = $this->get_this_model_name();
2699
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2700
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2701
-        return $related_model->count($query_params, $field_to_count, $distinct);
2702
-    }
2703
-
2704
-
2705
-
2706
-    /**
2707
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2708
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2709
-     *
2710
-     * @param        int           /EE_Base_Class $id_or_obj
2711
-     * @param string $model_name   like 'Event', or 'Registration'
2712
-     * @param array  $query_params like EEM_Base::get_all's
2713
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2714
-     * @return float
2715
-     * @throws EE_Error
2716
-     */
2717
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2718
-    {
2719
-        $related_model = $this->get_related_model_obj($model_name);
2720
-        if (! is_array($query_params)) {
2721
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2722
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2723
-                    gettype($query_params)), '4.6.0');
2724
-            $query_params = array();
2725
-        }
2726
-        //we're just going to use the query params on the related model's normal get_all query,
2727
-        //except add a condition to say to match the current mod
2728
-        if (! isset($query_params['default_where_conditions'])) {
2729
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2730
-        }
2731
-        $this_model_name = $this->get_this_model_name();
2732
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2733
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2734
-        return $related_model->sum($query_params, $field_to_sum);
2735
-    }
2736
-
2737
-
2738
-
2739
-    /**
2740
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2741
-     * $modelObject
2742
-     *
2743
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2744
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2745
-     * @param array               $query_params     like EEM_Base::get_all's
2746
-     * @return EE_Base_Class
2747
-     * @throws EE_Error
2748
-     */
2749
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2750
-    {
2751
-        $query_params['limit'] = 1;
2752
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2753
-        if ($results) {
2754
-            return array_shift($results);
2755
-        }
2756
-        return null;
2757
-    }
2758
-
2759
-
2760
-
2761
-    /**
2762
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2763
-     *
2764
-     * @return string
2765
-     */
2766
-    public function get_this_model_name()
2767
-    {
2768
-        return str_replace("EEM_", "", get_class($this));
2769
-    }
2770
-
2771
-
2772
-
2773
-    /**
2774
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2775
-     *
2776
-     * @return EE_Any_Foreign_Model_Name_Field
2777
-     * @throws EE_Error
2778
-     */
2779
-    public function get_field_containing_related_model_name()
2780
-    {
2781
-        foreach ($this->field_settings(true) as $field) {
2782
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2783
-                $field_with_model_name = $field;
2784
-            }
2785
-        }
2786
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2787
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2788
-                $this->get_this_model_name()));
2789
-        }
2790
-        return $field_with_model_name;
2791
-    }
2792
-
2793
-
2794
-
2795
-    /**
2796
-     * Inserts a new entry into the database, for each table.
2797
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2798
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2799
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2800
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2801
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2802
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2803
-     *
2804
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2805
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2806
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2807
-     *                              of EEM_Base)
2808
-     * @return int new primary key on main table that got inserted
2809
-     * @throws EE_Error
2810
-     */
2811
-    public function insert($field_n_values)
2812
-    {
2813
-        /**
2814
-         * Filters the fields and their values before inserting an item using the models
2815
-         *
2816
-         * @param array    $fields_n_values keys are the fields and values are their new values
2817
-         * @param EEM_Base $model           the model used
2818
-         */
2819
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2820
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2821
-            $main_table = $this->_get_main_table();
2822
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2823
-            if ($new_id !== false) {
2824
-                foreach ($this->_get_other_tables() as $other_table) {
2825
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2826
-                }
2827
-            }
2828
-            /**
2829
-             * Done just after attempting to insert a new model object
2830
-             *
2831
-             * @param EEM_Base   $model           used
2832
-             * @param array      $fields_n_values fields and their values
2833
-             * @param int|string the              ID of the newly-inserted model object
2834
-             */
2835
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2836
-            return $new_id;
2837
-        }
2838
-        return false;
2839
-    }
2840
-
2841
-
2842
-
2843
-    /**
2844
-     * Checks that the result would satisfy the unique indexes on this model
2845
-     *
2846
-     * @param array  $field_n_values
2847
-     * @param string $action
2848
-     * @return boolean
2849
-     * @throws EE_Error
2850
-     */
2851
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2852
-    {
2853
-        foreach ($this->unique_indexes() as $index_name => $index) {
2854
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2855
-            if ($this->exists(array($uniqueness_where_params))) {
2856
-                EE_Error::add_error(
2857
-                    sprintf(
2858
-                        __(
2859
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2860
-                            "event_espresso"
2861
-                        ),
2862
-                        $action,
2863
-                        $this->_get_class_name(),
2864
-                        $index_name,
2865
-                        implode(",", $index->field_names()),
2866
-                        http_build_query($uniqueness_where_params)
2867
-                    ),
2868
-                    __FILE__,
2869
-                    __FUNCTION__,
2870
-                    __LINE__
2871
-                );
2872
-                return false;
2873
-            }
2874
-        }
2875
-        return true;
2876
-    }
2877
-
2878
-
2879
-
2880
-    /**
2881
-     * Checks the database for an item that conflicts (ie, if this item were
2882
-     * saved to the DB would break some uniqueness requirement, like a primary key
2883
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2884
-     * can be either an EE_Base_Class or an array of fields n values
2885
-     *
2886
-     * @param EE_Base_Class|array $obj_or_fields_array
2887
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2888
-     *                                                 when looking for conflicts
2889
-     *                                                 (ie, if false, we ignore the model object's primary key
2890
-     *                                                 when finding "conflicts". If true, it's also considered).
2891
-     *                                                 Only works for INT primary key,
2892
-     *                                                 STRING primary keys cannot be ignored
2893
-     * @throws EE_Error
2894
-     * @return EE_Base_Class|array
2895
-     */
2896
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2897
-    {
2898
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2899
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2900
-        } elseif (is_array($obj_or_fields_array)) {
2901
-            $fields_n_values = $obj_or_fields_array;
2902
-        } else {
2903
-            throw new EE_Error(
2904
-                sprintf(
2905
-                    __(
2906
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2907
-                        "event_espresso"
2908
-                    ),
2909
-                    get_class($this),
2910
-                    $obj_or_fields_array
2911
-                )
2912
-            );
2913
-        }
2914
-        $query_params = array();
2915
-        if ($this->has_primary_key_field()
2916
-            && ($include_primary_key
2917
-                || $this->get_primary_key_field()
2918
-                   instanceof
2919
-                   EE_Primary_Key_String_Field)
2920
-            && isset($fields_n_values[$this->primary_key_name()])
2921
-        ) {
2922
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2923
-        }
2924
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2925
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2926
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2927
-        }
2928
-        //if there is nothing to base this search on, then we shouldn't find anything
2929
-        if (empty($query_params)) {
2930
-            return array();
2931
-        }
2932
-        return $this->get_one($query_params);
2933
-    }
2934
-
2935
-
2936
-
2937
-    /**
2938
-     * Like count, but is optimized and returns a boolean instead of an int
2939
-     *
2940
-     * @param array $query_params
2941
-     * @return boolean
2942
-     * @throws EE_Error
2943
-     */
2944
-    public function exists($query_params)
2945
-    {
2946
-        $query_params['limit'] = 1;
2947
-        return $this->count($query_params) > 0;
2948
-    }
2949
-
2950
-
2951
-
2952
-    /**
2953
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2954
-     *
2955
-     * @param int|string $id
2956
-     * @return boolean
2957
-     * @throws EE_Error
2958
-     */
2959
-    public function exists_by_ID($id)
2960
-    {
2961
-        return $this->exists(
2962
-            array(
2963
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2964
-                array(
2965
-                    $this->primary_key_name() => $id,
2966
-                ),
2967
-            )
2968
-        );
2969
-    }
2970
-
2971
-
2972
-
2973
-    /**
2974
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2975
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2976
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2977
-     * on the main table)
2978
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2979
-     * cases where we want to call it directly rather than via insert().
2980
-     *
2981
-     * @access   protected
2982
-     * @param EE_Table_Base $table
2983
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2984
-     *                                       float
2985
-     * @param int           $new_id          for now we assume only int keys
2986
-     * @throws EE_Error
2987
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2988
-     * @return int ID of new row inserted, or FALSE on failure
2989
-     */
2990
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2991
-    {
2992
-        global $wpdb;
2993
-        $insertion_col_n_values = array();
2994
-        $format_for_insertion = array();
2995
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2996
-        foreach ($fields_on_table as $field_name => $field_obj) {
2997
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2998
-            if ($field_obj->is_auto_increment()) {
2999
-                continue;
3000
-            }
3001
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3002
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
3003
-            if ($prepared_value !== null) {
3004
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3005
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
3006
-            }
3007
-        }
3008
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3009
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
3010
-            //so add the fk to the main table as a column
3011
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3012
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
3013
-        }
3014
-        //insert the new entry
3015
-        $result = $this->_do_wpdb_query('insert',
3016
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
3017
-        if ($result === false) {
3018
-            return false;
3019
-        }
3020
-        //ok, now what do we return for the ID of the newly-inserted thing?
3021
-        if ($this->has_primary_key_field()) {
3022
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3023
-                return $wpdb->insert_id;
3024
-            }
3025
-            //it's not an auto-increment primary key, so
3026
-            //it must have been supplied
3027
-            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3028
-        }
3029
-        //we can't return a  primary key because there is none. instead return
3030
-        //a unique string indicating this model
3031
-        return $this->get_index_primary_key_string($fields_n_values);
3032
-    }
3033
-
3034
-
3035
-
3036
-    /**
3037
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3038
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3039
-     * and there is no default, we pass it along. WPDB will take care of it)
3040
-     *
3041
-     * @param EE_Model_Field_Base $field_obj
3042
-     * @param array               $fields_n_values
3043
-     * @return mixed string|int|float depending on what the table column will be expecting
3044
-     * @throws EE_Error
3045
-     */
3046
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3047
-    {
3048
-        //if this field doesn't allow nullable, don't allow it
3049
-        if (
3050
-            ! $field_obj->is_nullable()
3051
-            && (
3052
-                ! isset($fields_n_values[$field_obj->get_name()])
3053
-                || $fields_n_values[$field_obj->get_name()] === null
3054
-            )
3055
-        ) {
3056
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3057
-        }
3058
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3059
-            ? $fields_n_values[$field_obj->get_name()]
3060
-            : null;
3061
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3062
-    }
3063
-
3064
-
3065
-
3066
-    /**
3067
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3068
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3069
-     * the field's prepare_for_set() method.
3070
-     *
3071
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3072
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3073
-     *                                   top of file)
3074
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3075
-     *                                   $value is a custom selection
3076
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3077
-     */
3078
-    private function _prepare_value_for_use_in_db($value, $field)
3079
-    {
3080
-        if ($field && $field instanceof EE_Model_Field_Base) {
3081
-            switch ($this->_values_already_prepared_by_model_object) {
3082
-                /** @noinspection PhpMissingBreakStatementInspection */
3083
-                case self::not_prepared_by_model_object:
3084
-                    $value = $field->prepare_for_set($value);
3085
-                //purposefully left out "return"
3086
-                case self::prepared_by_model_object:
3087
-                    /** @noinspection SuspiciousAssignmentsInspection */
3088
-                    $value = $field->prepare_for_use_in_db($value);
3089
-                case self::prepared_for_use_in_db:
3090
-                    //leave the value alone
3091
-            }
3092
-            return $value;
3093
-        }
3094
-        return $value;
3095
-    }
3096
-
3097
-
3098
-
3099
-    /**
3100
-     * Returns the main table on this model
3101
-     *
3102
-     * @return EE_Primary_Table
3103
-     * @throws EE_Error
3104
-     */
3105
-    protected function _get_main_table()
3106
-    {
3107
-        foreach ($this->_tables as $table) {
3108
-            if ($table instanceof EE_Primary_Table) {
3109
-                return $table;
3110
-            }
3111
-        }
3112
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3113
-            'event_espresso'), get_class($this)));
3114
-    }
3115
-
3116
-
3117
-
3118
-    /**
3119
-     * table
3120
-     * returns EE_Primary_Table table name
3121
-     *
3122
-     * @return string
3123
-     * @throws EE_Error
3124
-     */
3125
-    public function table()
3126
-    {
3127
-        return $this->_get_main_table()->get_table_name();
3128
-    }
3129
-
3130
-
3131
-
3132
-    /**
3133
-     * table
3134
-     * returns first EE_Secondary_Table table name
3135
-     *
3136
-     * @return string
3137
-     */
3138
-    public function second_table()
3139
-    {
3140
-        // grab second table from tables array
3141
-        $second_table = end($this->_tables);
3142
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3143
-    }
3144
-
3145
-
3146
-
3147
-    /**
3148
-     * get_table_obj_by_alias
3149
-     * returns table name given it's alias
3150
-     *
3151
-     * @param string $table_alias
3152
-     * @return EE_Primary_Table | EE_Secondary_Table
3153
-     */
3154
-    public function get_table_obj_by_alias($table_alias = '')
3155
-    {
3156
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3157
-    }
3158
-
3159
-
3160
-
3161
-    /**
3162
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3163
-     *
3164
-     * @return EE_Secondary_Table[]
3165
-     */
3166
-    protected function _get_other_tables()
3167
-    {
3168
-        $other_tables = array();
3169
-        foreach ($this->_tables as $table_alias => $table) {
3170
-            if ($table instanceof EE_Secondary_Table) {
3171
-                $other_tables[$table_alias] = $table;
3172
-            }
3173
-        }
3174
-        return $other_tables;
3175
-    }
3176
-
3177
-
3178
-
3179
-    /**
3180
-     * Finds all the fields that correspond to the given table
3181
-     *
3182
-     * @param string $table_alias , array key in EEM_Base::_tables
3183
-     * @return EE_Model_Field_Base[]
3184
-     */
3185
-    public function _get_fields_for_table($table_alias)
3186
-    {
3187
-        return $this->_fields[$table_alias];
3188
-    }
3189
-
3190
-
3191
-
3192
-    /**
3193
-     * Recurses through all the where parameters, and finds all the related models we'll need
3194
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3195
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3196
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3197
-     * related Registration, Transaction, and Payment models.
3198
-     *
3199
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3200
-     * @return EE_Model_Query_Info_Carrier
3201
-     * @throws EE_Error
3202
-     */
3203
-    public function _extract_related_models_from_query($query_params)
3204
-    {
3205
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3206
-        if (array_key_exists(0, $query_params)) {
3207
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3208
-        }
3209
-        if (array_key_exists('group_by', $query_params)) {
3210
-            if (is_array($query_params['group_by'])) {
3211
-                $this->_extract_related_models_from_sub_params_array_values(
3212
-                    $query_params['group_by'],
3213
-                    $query_info_carrier,
3214
-                    'group_by'
3215
-                );
3216
-            } elseif (! empty ($query_params['group_by'])) {
3217
-                $this->_extract_related_model_info_from_query_param(
3218
-                    $query_params['group_by'],
3219
-                    $query_info_carrier,
3220
-                    'group_by'
3221
-                );
3222
-            }
3223
-        }
3224
-        if (array_key_exists('having', $query_params)) {
3225
-            $this->_extract_related_models_from_sub_params_array_keys(
3226
-                $query_params[0],
3227
-                $query_info_carrier,
3228
-                'having'
3229
-            );
3230
-        }
3231
-        if (array_key_exists('order_by', $query_params)) {
3232
-            if (is_array($query_params['order_by'])) {
3233
-                $this->_extract_related_models_from_sub_params_array_keys(
3234
-                    $query_params['order_by'],
3235
-                    $query_info_carrier,
3236
-                    'order_by'
3237
-                );
3238
-            } elseif (! empty($query_params['order_by'])) {
3239
-                $this->_extract_related_model_info_from_query_param(
3240
-                    $query_params['order_by'],
3241
-                    $query_info_carrier,
3242
-                    'order_by'
3243
-                );
3244
-            }
3245
-        }
3246
-        if (array_key_exists('force_join', $query_params)) {
3247
-            $this->_extract_related_models_from_sub_params_array_values(
3248
-                $query_params['force_join'],
3249
-                $query_info_carrier,
3250
-                'force_join'
3251
-            );
3252
-        }
3253
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3254
-        return $query_info_carrier;
3255
-    }
3256
-
3257
-
3258
-
3259
-    /**
3260
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3261
-     *
3262
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3263
-     *                                                      $query_params['having']
3264
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3265
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3266
-     * @throws EE_Error
3267
-     * @return \EE_Model_Query_Info_Carrier
3268
-     */
3269
-    private function _extract_related_models_from_sub_params_array_keys(
3270
-        $sub_query_params,
3271
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3272
-        $query_param_type
3273
-    ) {
3274
-        if (! empty($sub_query_params)) {
3275
-            $sub_query_params = (array)$sub_query_params;
3276
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3277
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3278
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3279
-                    $query_param_type);
3280
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3281
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3282
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3283
-                //of array('Registration.TXN_ID'=>23)
3284
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3285
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3286
-                    if (! is_array($possibly_array_of_params)) {
3287
-                        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'))",
3288
-                            "event_espresso"),
3289
-                            $param, $possibly_array_of_params));
3290
-                    }
3291
-                    $this->_extract_related_models_from_sub_params_array_keys(
3292
-                        $possibly_array_of_params,
3293
-                        $model_query_info_carrier, $query_param_type
3294
-                    );
3295
-                } elseif ($query_param_type === 0 //ie WHERE
3296
-                          && is_array($possibly_array_of_params)
3297
-                          && isset($possibly_array_of_params[2])
3298
-                          && $possibly_array_of_params[2] == true
3299
-                ) {
3300
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3301
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3302
-                    //from which we should extract query parameters!
3303
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3304
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3305
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3306
-                    }
3307
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3308
-                        $model_query_info_carrier, $query_param_type);
3309
-                }
3310
-            }
3311
-        }
3312
-        return $model_query_info_carrier;
3313
-    }
3314
-
3315
-
3316
-
3317
-    /**
3318
-     * For extracting related models from forced_joins, where the array values contain the info about what
3319
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3320
-     *
3321
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3322
-     *                                                      $query_params['having']
3323
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3324
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3325
-     * @throws EE_Error
3326
-     * @return \EE_Model_Query_Info_Carrier
3327
-     */
3328
-    private function _extract_related_models_from_sub_params_array_values(
3329
-        $sub_query_params,
3330
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3331
-        $query_param_type
3332
-    ) {
3333
-        if (! empty($sub_query_params)) {
3334
-            if (! is_array($sub_query_params)) {
3335
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3336
-                    $sub_query_params));
3337
-            }
3338
-            foreach ($sub_query_params as $param) {
3339
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3340
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3341
-                    $query_param_type);
3342
-            }
3343
-        }
3344
-        return $model_query_info_carrier;
3345
-    }
3346
-
3347
-
3348
-
3349
-    /**
3350
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3351
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3352
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3353
-     * but use them in a different order. Eg, we need to know what models we are querying
3354
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3355
-     * other models before we can finalize the where clause SQL.
3356
-     *
3357
-     * @param array $query_params
3358
-     * @throws EE_Error
3359
-     * @return EE_Model_Query_Info_Carrier
3360
-     */
3361
-    public function _create_model_query_info_carrier($query_params)
3362
-    {
3363
-        if (! is_array($query_params)) {
3364
-            EE_Error::doing_it_wrong(
3365
-                'EEM_Base::_create_model_query_info_carrier',
3366
-                sprintf(
3367
-                    __(
3368
-                        '$query_params should be an array, you passed a variable of type %s',
3369
-                        'event_espresso'
3370
-                    ),
3371
-                    gettype($query_params)
3372
-                ),
3373
-                '4.6.0'
3374
-            );
3375
-            $query_params = array();
3376
-        }
3377
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3378
-        //first check if we should alter the query to account for caps or not
3379
-        //because the caps might require us to do extra joins
3380
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3381
-            $query_params[0] = $where_query_params = array_replace_recursive(
3382
-                $where_query_params,
3383
-                $this->caps_where_conditions(
3384
-                    $query_params['caps']
3385
-                )
3386
-            );
3387
-        }
3388
-        $query_object = $this->_extract_related_models_from_query($query_params);
3389
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3390
-        foreach ($where_query_params as $key => $value) {
3391
-            if (is_int($key)) {
3392
-                throw new EE_Error(
3393
-                    sprintf(
3394
-                        __(
3395
-                            "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.",
3396
-                            "event_espresso"
3397
-                        ),
3398
-                        $key,
3399
-                        var_export($value, true),
3400
-                        var_export($query_params, true),
3401
-                        get_class($this)
3402
-                    )
3403
-                );
3404
-            }
3405
-        }
3406
-        if (
3407
-            array_key_exists('default_where_conditions', $query_params)
3408
-            && ! empty($query_params['default_where_conditions'])
3409
-        ) {
3410
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3411
-        } else {
3412
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3413
-        }
3414
-        $where_query_params = array_merge(
3415
-            $this->_get_default_where_conditions_for_models_in_query(
3416
-                $query_object,
3417
-                $use_default_where_conditions,
3418
-                $where_query_params
3419
-            ),
3420
-            $where_query_params
3421
-        );
3422
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3423
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3424
-        // So we need to setup a subquery and use that for the main join.
3425
-        // Note for now this only works on the primary table for the model.
3426
-        // So for instance, you could set the limit array like this:
3427
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3428
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3429
-            $query_object->set_main_model_join_sql(
3430
-                $this->_construct_limit_join_select(
3431
-                    $query_params['on_join_limit'][0],
3432
-                    $query_params['on_join_limit'][1]
3433
-                )
3434
-            );
3435
-        }
3436
-        //set limit
3437
-        if (array_key_exists('limit', $query_params)) {
3438
-            if (is_array($query_params['limit'])) {
3439
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3440
-                    $e = sprintf(
3441
-                        __(
3442
-                            "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)",
3443
-                            "event_espresso"
3444
-                        ),
3445
-                        http_build_query($query_params['limit'])
3446
-                    );
3447
-                    throw new EE_Error($e . "|" . $e);
3448
-                }
3449
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3450
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3451
-            } elseif (! empty ($query_params['limit'])) {
3452
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3453
-            }
3454
-        }
3455
-        //set order by
3456
-        if (array_key_exists('order_by', $query_params)) {
3457
-            if (is_array($query_params['order_by'])) {
3458
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3459
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3460
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3461
-                if (array_key_exists('order', $query_params)) {
3462
-                    throw new EE_Error(
3463
-                        sprintf(
3464
-                            __(
3465
-                                "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 ",
3466
-                                "event_espresso"
3467
-                            ),
3468
-                            get_class($this),
3469
-                            implode(", ", array_keys($query_params['order_by'])),
3470
-                            implode(", ", $query_params['order_by']),
3471
-                            $query_params['order']
3472
-                        )
3473
-                    );
3474
-                }
3475
-                $this->_extract_related_models_from_sub_params_array_keys(
3476
-                    $query_params['order_by'],
3477
-                    $query_object,
3478
-                    'order_by'
3479
-                );
3480
-                //assume it's an array of fields to order by
3481
-                $order_array = array();
3482
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3483
-                    $order = $this->_extract_order($order);
3484
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3485
-                }
3486
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3487
-            } elseif (! empty ($query_params['order_by'])) {
3488
-                $this->_extract_related_model_info_from_query_param(
3489
-                    $query_params['order_by'],
3490
-                    $query_object,
3491
-                    'order',
3492
-                    $query_params['order_by']
3493
-                );
3494
-                $order = isset($query_params['order'])
3495
-                    ? $this->_extract_order($query_params['order'])
3496
-                    : 'DESC';
3497
-                $query_object->set_order_by_sql(
3498
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3499
-                );
3500
-            }
3501
-        }
3502
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3503
-        if (! array_key_exists('order_by', $query_params)
3504
-            && array_key_exists('order', $query_params)
3505
-            && ! empty($query_params['order'])
3506
-        ) {
3507
-            $pk_field = $this->get_primary_key_field();
3508
-            $order = $this->_extract_order($query_params['order']);
3509
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3510
-        }
3511
-        //set group by
3512
-        if (array_key_exists('group_by', $query_params)) {
3513
-            if (is_array($query_params['group_by'])) {
3514
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3515
-                $group_by_array = array();
3516
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3517
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3518
-                }
3519
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3520
-            } elseif (! empty ($query_params['group_by'])) {
3521
-                $query_object->set_group_by_sql(
3522
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3523
-                );
3524
-            }
3525
-        }
3526
-        //set having
3527
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3528
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3529
-        }
3530
-        //now, just verify they didn't pass anything wack
3531
-        foreach ($query_params as $query_key => $query_value) {
3532
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3533
-                throw new EE_Error(
3534
-                    sprintf(
3535
-                        __(
3536
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3537
-                            'event_espresso'
3538
-                        ),
3539
-                        $query_key,
3540
-                        get_class($this),
3541
-                        //						print_r( $this->_allowed_query_params, TRUE )
3542
-                        implode(',', $this->_allowed_query_params)
3543
-                    )
3544
-                );
3545
-            }
3546
-        }
3547
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3548
-        if (empty($main_model_join_sql)) {
3549
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3550
-        }
3551
-        return $query_object;
3552
-    }
3553
-
3554
-
3555
-
3556
-    /**
3557
-     * Gets the where conditions that should be imposed on the query based on the
3558
-     * context (eg reading frontend, backend, edit or delete).
3559
-     *
3560
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3561
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3562
-     * @throws EE_Error
3563
-     */
3564
-    public function caps_where_conditions($context = self::caps_read)
3565
-    {
3566
-        EEM_Base::verify_is_valid_cap_context($context);
3567
-        $cap_where_conditions = array();
3568
-        $cap_restrictions = $this->caps_missing($context);
3569
-        /**
3570
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3571
-         */
3572
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3573
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3574
-                $restriction_if_no_cap->get_default_where_conditions());
3575
-        }
3576
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3577
-            $cap_restrictions);
3578
-    }
3579
-
3580
-
3581
-
3582
-    /**
3583
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3584
-     * otherwise throws an exception
3585
-     *
3586
-     * @param string $should_be_order_string
3587
-     * @return string either ASC, asc, DESC or desc
3588
-     * @throws EE_Error
3589
-     */
3590
-    private function _extract_order($should_be_order_string)
3591
-    {
3592
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3593
-            return $should_be_order_string;
3594
-        }
3595
-        throw new EE_Error(
3596
-            sprintf(
3597
-                __(
3598
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3599
-                    "event_espresso"
3600
-                ), get_class($this), $should_be_order_string
3601
-            )
3602
-        );
3603
-    }
3604
-
3605
-
3606
-
3607
-    /**
3608
-     * Looks at all the models which are included in this query, and asks each
3609
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3610
-     * so they can be merged
3611
-     *
3612
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3613
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3614
-     *                                                                  'none' means NO default where conditions will
3615
-     *                                                                  be used AT ALL during this query.
3616
-     *                                                                  'other_models_only' means default where
3617
-     *                                                                  conditions from other models will be used, but
3618
-     *                                                                  not for this primary model. 'all', the default,
3619
-     *                                                                  means default where conditions will apply as
3620
-     *                                                                  normal
3621
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3622
-     * @throws EE_Error
3623
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3624
-     */
3625
-    private function _get_default_where_conditions_for_models_in_query(
3626
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3627
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3628
-        $where_query_params = array()
3629
-    ) {
3630
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3631
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3632
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3633
-                "event_espresso"), $use_default_where_conditions,
3634
-                implode(", ", $allowed_used_default_where_conditions_values)));
3635
-        }
3636
-        $universal_query_params = array();
3637
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3638
-            $universal_query_params = $this->_get_default_where_conditions();
3639
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3640
-            $universal_query_params = $this->_get_minimum_where_conditions();
3641
-        }
3642
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3643
-            $related_model = $this->get_related_model_obj($model_name);
3644
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3645
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3646
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3647
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3648
-            } else {
3649
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3650
-                continue;
3651
-            }
3652
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3653
-                $related_model_universal_where_params,
3654
-                $where_query_params,
3655
-                $related_model,
3656
-                $model_relation_path
3657
-            );
3658
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3659
-                $universal_query_params,
3660
-                $overrides
3661
-            );
3662
-        }
3663
-        return $universal_query_params;
3664
-    }
3665
-
3666
-
3667
-
3668
-    /**
3669
-     * Determines whether or not we should use default where conditions for the model in question
3670
-     * (this model, or other related models).
3671
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3672
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3673
-     * We should use default where conditions on related models when they requested to use default where conditions
3674
-     * on all models, or specifically just on other related models
3675
-     * @param      $default_where_conditions_value
3676
-     * @param bool $for_this_model false means this is for OTHER related models
3677
-     * @return bool
3678
-     */
3679
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3680
-    {
3681
-        return (
3682
-                   $for_this_model
3683
-                   && in_array(
3684
-                       $default_where_conditions_value,
3685
-                       array(
3686
-                           EEM_Base::default_where_conditions_all,
3687
-                           EEM_Base::default_where_conditions_this_only,
3688
-                           EEM_Base::default_where_conditions_minimum_others,
3689
-                       ),
3690
-                       true
3691
-                   )
3692
-               )
3693
-               || (
3694
-                   ! $for_this_model
3695
-                   && in_array(
3696
-                       $default_where_conditions_value,
3697
-                       array(
3698
-                           EEM_Base::default_where_conditions_all,
3699
-                           EEM_Base::default_where_conditions_others_only,
3700
-                       ),
3701
-                       true
3702
-                   )
3703
-               );
3704
-    }
3705
-
3706
-    /**
3707
-     * Determines whether or not we should use default minimum conditions for the model in question
3708
-     * (this model, or other related models).
3709
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3710
-     * where conditions.
3711
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3712
-     * on this model or others
3713
-     * @param      $default_where_conditions_value
3714
-     * @param bool $for_this_model false means this is for OTHER related models
3715
-     * @return bool
3716
-     */
3717
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3718
-    {
3719
-        return (
3720
-                   $for_this_model
3721
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3722
-               )
3723
-               || (
3724
-                   ! $for_this_model
3725
-                   && in_array(
3726
-                       $default_where_conditions_value,
3727
-                       array(
3728
-                           EEM_Base::default_where_conditions_minimum_others,
3729
-                           EEM_Base::default_where_conditions_minimum_all,
3730
-                       ),
3731
-                       true
3732
-                   )
3733
-               );
3734
-    }
3735
-
3736
-
3737
-    /**
3738
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3739
-     * then we also add a special where condition which allows for that model's primary key
3740
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3741
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3742
-     *
3743
-     * @param array    $default_where_conditions
3744
-     * @param array    $provided_where_conditions
3745
-     * @param EEM_Base $model
3746
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3747
-     * @return array like EEM_Base::get_all's $query_params[0]
3748
-     * @throws EE_Error
3749
-     */
3750
-    private function _override_defaults_or_make_null_friendly(
3751
-        $default_where_conditions,
3752
-        $provided_where_conditions,
3753
-        $model,
3754
-        $model_relation_path
3755
-    ) {
3756
-        $null_friendly_where_conditions = array();
3757
-        $none_overridden = true;
3758
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3759
-        foreach ($default_where_conditions as $key => $val) {
3760
-            if (isset($provided_where_conditions[$key])) {
3761
-                $none_overridden = false;
3762
-            } else {
3763
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3764
-            }
3765
-        }
3766
-        if ($none_overridden && $default_where_conditions) {
3767
-            if ($model->has_primary_key_field()) {
3768
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3769
-                                                                                . "."
3770
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3771
-            }/*else{
37
+	/**
38
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
41
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
+	 *
43
+	 * @var boolean
44
+	 */
45
+	private $_values_already_prepared_by_model_object = 0;
46
+
47
+	/**
48
+	 * when $_values_already_prepared_by_model_object equals this, we assume
49
+	 * the data is just like form input that needs to have the model fields'
50
+	 * prepare_for_set and prepare_for_use_in_db called on it
51
+	 */
52
+	const not_prepared_by_model_object = 0;
53
+
54
+	/**
55
+	 * when $_values_already_prepared_by_model_object equals this, we
56
+	 * assume this value is coming from a model object and doesn't need to have
57
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
58
+	 */
59
+	const prepared_by_model_object = 1;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the values are already to be used in the database (ie no processing is done
64
+	 * on them by the model's fields)
65
+	 */
66
+	const prepared_for_use_in_db = 2;
67
+
68
+
69
+	protected $singular_item = 'Item';
70
+
71
+	protected $plural_item   = 'Items';
72
+
73
+	/**
74
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
+	 */
76
+	protected $_tables;
77
+
78
+	/**
79
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
+	 *
83
+	 * @var \EE_Model_Field_Base[][] $_fields
84
+	 */
85
+	protected $_fields;
86
+
87
+	/**
88
+	 * array of different kinds of relations
89
+	 *
90
+	 * @var \EE_Model_Relation_Base[] $_model_relations
91
+	 */
92
+	protected $_model_relations;
93
+
94
+	/**
95
+	 * @var \EE_Index[] $_indexes
96
+	 */
97
+	protected $_indexes = array();
98
+
99
+	/**
100
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
101
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
+	 * by setting the same columns as used in these queries in the query yourself.
103
+	 *
104
+	 * @var EE_Default_Where_Conditions
105
+	 */
106
+	protected $_default_where_conditions_strategy;
107
+
108
+	/**
109
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
+	 * This is particularly useful when you want something between 'none' and 'default'
111
+	 *
112
+	 * @var EE_Default_Where_Conditions
113
+	 */
114
+	protected $_minimum_where_conditions_strategy;
115
+
116
+	/**
117
+	 * String describing how to find the "owner" of this model's objects.
118
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
+	 * But when there isn't, this indicates which related model, or transiently-related model,
120
+	 * has the foreign key to the wp_users table.
121
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
+	 * related to events, and events have a foreign key to wp_users.
123
+	 * On EEM_Transaction, this would be 'Transaction.Event'
124
+	 *
125
+	 * @var string
126
+	 */
127
+	protected $_model_chain_to_wp_user = '';
128
+
129
+	/**
130
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
+	 * don't need it (particularly CPT models)
132
+	 *
133
+	 * @var bool
134
+	 */
135
+	protected $_ignore_where_strategy = false;
136
+
137
+	/**
138
+	 * String used in caps relating to this model. Eg, if the caps relating to this
139
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
+	 *
141
+	 * @var string. If null it hasn't been initialized yet. If false then we
142
+	 * have indicated capabilities don't apply to this
143
+	 */
144
+	protected $_caps_slug = null;
145
+
146
+	/**
147
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
+	 * and next-level keys are capability names, and each's value is a
149
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
151
+	 * and then each capability in the corresponding sub-array that they're missing
152
+	 * adds the where conditions onto the query.
153
+	 *
154
+	 * @var array
155
+	 */
156
+	protected $_cap_restrictions = array(
157
+		self::caps_read       => array(),
158
+		self::caps_read_admin => array(),
159
+		self::caps_edit       => array(),
160
+		self::caps_delete     => array(),
161
+	);
162
+
163
+	/**
164
+	 * Array defining which cap restriction generators to use to create default
165
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
166
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
+	 * automatically set this to false (not just null).
169
+	 *
170
+	 * @var EE_Restriction_Generator_Base[]
171
+	 */
172
+	protected $_cap_restriction_generators = array();
173
+
174
+	/**
175
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
+	 */
177
+	const caps_read       = 'read';
178
+
179
+	const caps_read_admin = 'read_admin';
180
+
181
+	const caps_edit       = 'edit';
182
+
183
+	const caps_delete     = 'delete';
184
+
185
+	/**
186
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
+	 * maps to 'read' because when looking for relevant permissions we're going to use
189
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
190
+	 *
191
+	 * @var array
192
+	 */
193
+	protected $_cap_contexts_to_cap_action_map = array(
194
+		self::caps_read       => 'read',
195
+		self::caps_read_admin => 'read',
196
+		self::caps_edit       => 'edit',
197
+		self::caps_delete     => 'delete',
198
+	);
199
+
200
+	/**
201
+	 * Timezone
202
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
+	 * EE_Datetime_Field data type will have access to it.
206
+	 *
207
+	 * @var string
208
+	 */
209
+	protected $_timezone;
210
+
211
+
212
+	/**
213
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
+	 * multisite.
215
+	 *
216
+	 * @var int
217
+	 */
218
+	protected static $_model_query_blog_id;
219
+
220
+	/**
221
+	 * A copy of _fields, except the array keys are the model names pointed to by
222
+	 * the field
223
+	 *
224
+	 * @var EE_Model_Field_Base[]
225
+	 */
226
+	private $_cache_foreign_key_to_fields = array();
227
+
228
+	/**
229
+	 * Cached list of all the fields on the model, indexed by their name
230
+	 *
231
+	 * @var EE_Model_Field_Base[]
232
+	 */
233
+	private $_cached_fields = null;
234
+
235
+	/**
236
+	 * Cached list of all the fields on the model, except those that are
237
+	 * marked as only pertinent to the database
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cached_fields_non_db_only = null;
242
+
243
+	/**
244
+	 * A cached reference to the primary key for quick lookup
245
+	 *
246
+	 * @var EE_Model_Field_Base
247
+	 */
248
+	private $_primary_key_field = null;
249
+
250
+	/**
251
+	 * Flag indicating whether this model has a primary key or not
252
+	 *
253
+	 * @var boolean
254
+	 */
255
+	protected $_has_primary_key_field = null;
256
+
257
+	/**
258
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
259
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
+	 * This should be true for models that deal with data that should exist independent of EE.
261
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
263
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
265
+	 * @var boolean
266
+	 */
267
+	protected $_wp_core_model = false;
268
+
269
+	/**
270
+	 *    List of valid operators that can be used for querying.
271
+	 * The keys are all operators we'll accept, the values are the real SQL
272
+	 * operators used
273
+	 *
274
+	 * @var array
275
+	 */
276
+	protected $_valid_operators = array(
277
+		'='           => '=',
278
+		'<='          => '<=',
279
+		'<'           => '<',
280
+		'>='          => '>=',
281
+		'>'           => '>',
282
+		'!='          => '!=',
283
+		'LIKE'        => 'LIKE',
284
+		'like'        => 'LIKE',
285
+		'NOT_LIKE'    => 'NOT LIKE',
286
+		'not_like'    => 'NOT LIKE',
287
+		'NOT LIKE'    => 'NOT LIKE',
288
+		'not like'    => 'NOT LIKE',
289
+		'IN'          => 'IN',
290
+		'in'          => 'IN',
291
+		'NOT_IN'      => 'NOT IN',
292
+		'not_in'      => 'NOT IN',
293
+		'NOT IN'      => 'NOT IN',
294
+		'not in'      => 'NOT IN',
295
+		'between'     => 'BETWEEN',
296
+		'BETWEEN'     => 'BETWEEN',
297
+		'IS_NOT_NULL' => 'IS NOT NULL',
298
+		'is_not_null' => 'IS NOT NULL',
299
+		'IS NOT NULL' => 'IS NOT NULL',
300
+		'is not null' => 'IS NOT NULL',
301
+		'IS_NULL'     => 'IS NULL',
302
+		'is_null'     => 'IS NULL',
303
+		'IS NULL'     => 'IS NULL',
304
+		'is null'     => 'IS NULL',
305
+		'REGEXP'      => 'REGEXP',
306
+		'regexp'      => 'REGEXP',
307
+		'NOT_REGEXP'  => 'NOT REGEXP',
308
+		'not_regexp'  => 'NOT REGEXP',
309
+		'NOT REGEXP'  => 'NOT REGEXP',
310
+		'not regexp'  => 'NOT REGEXP',
311
+	);
312
+
313
+	/**
314
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
+	 *
316
+	 * @var array
317
+	 */
318
+	protected $_in_style_operators = array('IN', 'NOT IN');
319
+
320
+	/**
321
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
+	 * '12-31-2012'"
323
+	 *
324
+	 * @var array
325
+	 */
326
+	protected $_between_style_operators = array('BETWEEN');
327
+
328
+	/**
329
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
+	 * @var array
331
+	 */
332
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
+	/**
334
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
+	 * on a join table.
336
+	 *
337
+	 * @var array
338
+	 */
339
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
+
341
+	/**
342
+	 * Allowed values for $query_params['order'] for ordering in queries
343
+	 *
344
+	 * @var array
345
+	 */
346
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
+
348
+	/**
349
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
351
+	 *
352
+	 * @var array
353
+	 */
354
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
+
356
+	/**
357
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
359
+	 *
360
+	 * @var array
361
+	 */
362
+	private $_allowed_query_params = array(
363
+		0,
364
+		'limit',
365
+		'order_by',
366
+		'group_by',
367
+		'having',
368
+		'force_join',
369
+		'order',
370
+		'on_join_limit',
371
+		'default_where_conditions',
372
+		'caps',
373
+		'extra_selects'
374
+	);
375
+
376
+	/**
377
+	 * All the data types that can be used in $wpdb->prepare statements.
378
+	 *
379
+	 * @var array
380
+	 */
381
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
+
383
+	/**
384
+	 * @var EE_Registry $EE
385
+	 */
386
+	protected $EE = null;
387
+
388
+
389
+	/**
390
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
+	 *
392
+	 * @var int
393
+	 */
394
+	protected $_show_next_x_db_queries = 0;
395
+
396
+	/**
397
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
+	 * WHERE, GROUP_BY, etc.
400
+	 *
401
+	 * @var CustomSelects
402
+	 */
403
+	protected $_custom_selections = array();
404
+
405
+	/**
406
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
+	 * caches every model object we've fetched from the DB on this request
408
+	 *
409
+	 * @var array
410
+	 */
411
+	protected $_entity_map;
412
+
413
+	/**
414
+	 * @var LoaderInterface $loader
415
+	 */
416
+	private static $loader;
417
+
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has not yet verified the db on this http request
421
+	 */
422
+	const db_verified_none = 0;
423
+
424
+	/**
425
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
426
+	 * but not the addons' dbs
427
+	 */
428
+	const db_verified_core = 1;
429
+
430
+	/**
431
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
+	 * the EE core db too)
433
+	 */
434
+	const db_verified_addons = 2;
435
+
436
+	/**
437
+	 * indicates whether an EEM_Base child has already re-verified the DB
438
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
439
+	 * looking like EEM_Base::db_verified_*
440
+	 *
441
+	 * @var int - 0 = none, 1 = core, 2 = addons
442
+	 */
443
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
444
+
445
+	/**
446
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
449
+	 */
450
+	const default_where_conditions_all = 'all';
451
+
452
+	/**
453
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
+	 *        models which share tables with other models, this can return data for the wrong model.
458
+	 */
459
+	const default_where_conditions_this_only = 'this_model_only';
460
+
461
+	/**
462
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
+	 */
466
+	const default_where_conditions_others_only = 'other_models_only';
467
+
468
+	/**
469
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
472
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
+	 *        (regardless of whether those events and venues are trashed)
474
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
+	 *        events.
476
+	 */
477
+	const default_where_conditions_minimum_all = 'minimum';
478
+
479
+	/**
480
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
+	 *        not)
484
+	 */
485
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
+
487
+	/**
488
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
+	 *        it's possible it will return table entries for other models. You should use
491
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
492
+	 */
493
+	const default_where_conditions_none = 'none';
494
+
495
+
496
+
497
+	/**
498
+	 * About all child constructors:
499
+	 * they should define the _tables, _fields and _model_relations arrays.
500
+	 * Should ALWAYS be called after child constructor.
501
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
502
+	 * finalizes constructing all the object's attributes.
503
+	 * Generally, rather than requiring a child to code
504
+	 * $this->_tables = array(
505
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
+	 *        ...);
507
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
+	 * each EE_Table has a function to set the table's alias after the constructor, using
509
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
+	 * do something similar.
511
+	 *
512
+	 * @param null $timezone
513
+	 * @throws EE_Error
514
+	 */
515
+	protected function __construct($timezone = null)
516
+	{
517
+		// check that the model has not been loaded too soon
518
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+			throw new EE_Error (
520
+				sprintf(
521
+					__('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
+						'event_espresso'),
523
+					get_class($this)
524
+				)
525
+			);
526
+		}
527
+		/**
528
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
+		 */
530
+		if (empty(EEM_Base::$_model_query_blog_id)) {
531
+			EEM_Base::set_model_query_blog_id();
532
+		}
533
+		/**
534
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
+		 * just use EE_Register_Model_Extension
536
+		 *
537
+		 * @var EE_Table_Base[] $_tables
538
+		 */
539
+		$this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
+		foreach ($this->_tables as $table_alias => $table_obj) {
541
+			/** @var $table_obj EE_Table_Base */
542
+			$table_obj->_construct_finalize_with_alias($table_alias);
543
+			if ($table_obj instanceof EE_Secondary_Table) {
544
+				/** @var $table_obj EE_Secondary_Table */
545
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
+			}
547
+		}
548
+		/**
549
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
+		 * EE_Register_Model_Extension
551
+		 *
552
+		 * @param EE_Model_Field_Base[] $_fields
553
+		 */
554
+		$this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
+		$this->_invalidate_field_caches();
556
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
557
+			if (! array_key_exists($table_alias, $this->_tables)) {
558
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
+			}
561
+			foreach ($fields_for_table as $field_name => $field_obj) {
562
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
+				//primary key field base has a slightly different _construct_finalize
564
+				/** @var $field_obj EE_Model_Field_Base */
565
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
+			}
567
+		}
568
+		// everything is related to Extra_Meta
569
+		if (get_class($this) !== 'EEM_Extra_Meta') {
570
+			//make extra meta related to everything, but don't block deleting things just
571
+			//because they have related extra meta info. For now just orphan those extra meta
572
+			//in the future we should automatically delete them
573
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
+		}
575
+		//and change logs
576
+		if (get_class($this) !== 'EEM_Change_Log') {
577
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		/**
580
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
+		 * EE_Register_Model_Extension
582
+		 *
583
+		 * @param EE_Model_Relation_Base[] $_model_relations
584
+		 */
585
+		$this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
+			$this->_model_relations);
587
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
588
+			/** @var $relation_obj EE_Model_Relation_Base */
589
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
+		}
591
+		foreach ($this->_indexes as $index_name => $index_obj) {
592
+			/** @var $index_obj EE_Index */
593
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
+		}
595
+		$this->set_timezone($timezone);
596
+		//finalize default where condition strategy, or set default
597
+		if (! $this->_default_where_conditions_strategy) {
598
+			//nothing was set during child constructor, so set default
599
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
+		}
601
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
602
+		if (! $this->_minimum_where_conditions_strategy) {
603
+			//nothing was set during child constructor, so set default
604
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
+		}
606
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
608
+		//to indicate to NOT set it, set it to the logical default
609
+		if ($this->_caps_slug === null) {
610
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
+		}
612
+		//initialize the standard cap restriction generators if none were specified by the child constructor
613
+		if ($this->_cap_restriction_generators !== false) {
614
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
617
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
+						new EE_Restriction_Generator_Protected(),
619
+						$cap_context,
620
+						$this
621
+					);
622
+				}
623
+			}
624
+		}
625
+		//if there are cap restriction generators, use them to make the default cap restrictions
626
+		if ($this->_cap_restriction_generators !== false) {
627
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
+				if (! $generator_object) {
629
+					continue;
630
+				}
631
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
+					throw new EE_Error(
633
+						sprintf(
634
+							__('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
+								'event_espresso'),
636
+							$context,
637
+							$this->get_this_model_name()
638
+						)
639
+					);
640
+				}
641
+				$action = $this->cap_action_for_context($context);
642
+				if (! $generator_object->construction_finalized()) {
643
+					$generator_object->_construct_finalize($this, $action);
644
+				}
645
+			}
646
+		}
647
+		do_action('AHEE__' . get_class($this) . '__construct__end');
648
+	}
649
+
650
+
651
+
652
+	/**
653
+	 * Used to set the $_model_query_blog_id static property.
654
+	 *
655
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
656
+	 *                      value for get_current_blog_id() will be used.
657
+	 */
658
+	public static function set_model_query_blog_id($blog_id = 0)
659
+	{
660
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
661
+	}
662
+
663
+
664
+
665
+	/**
666
+	 * Returns whatever is set as the internal $model_query_blog_id.
667
+	 *
668
+	 * @return int
669
+	 */
670
+	public static function get_model_query_blog_id()
671
+	{
672
+		return EEM_Base::$_model_query_blog_id;
673
+	}
674
+
675
+
676
+
677
+	/**
678
+	 * This function is a singleton method used to instantiate the Espresso_model object
679
+	 *
680
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
681
+	 *                                (and any incoming timezone data that gets saved).
682
+	 *                                Note this just sends the timezone info to the date time model field objects.
683
+	 *                                Default is NULL
684
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
685
+	 * @return static (as in the concrete child class)
686
+	 * @throws EE_Error
687
+	 * @throws InvalidArgumentException
688
+	 * @throws InvalidDataTypeException
689
+	 * @throws InvalidInterfaceException
690
+	 */
691
+	public static function instance($timezone = null)
692
+	{
693
+		// check if instance of Espresso_model already exists
694
+		if (! static::$_instance instanceof static) {
695
+			// instantiate Espresso_model
696
+			static::$_instance = new static(
697
+				$timezone,
698
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
699
+			);
700
+		}
701
+		//we might have a timezone set, let set_timezone decide what to do with it
702
+		static::$_instance->set_timezone($timezone);
703
+		// Espresso_model object
704
+		return static::$_instance;
705
+	}
706
+
707
+
708
+
709
+	/**
710
+	 * resets the model and returns it
711
+	 *
712
+	 * @param null | string $timezone
713
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
714
+	 * all its properties reset; if it wasn't instantiated, returns null)
715
+	 * @throws EE_Error
716
+	 * @throws ReflectionException
717
+	 * @throws InvalidArgumentException
718
+	 * @throws InvalidDataTypeException
719
+	 * @throws InvalidInterfaceException
720
+	 */
721
+	public static function reset($timezone = null)
722
+	{
723
+		if (static::$_instance instanceof EEM_Base) {
724
+			//let's try to NOT swap out the current instance for a new one
725
+			//because if someone has a reference to it, we can't remove their reference
726
+			//so it's best to keep using the same reference, but change the original object
727
+			//reset all its properties to their original values as defined in the class
728
+			$r = new ReflectionClass(get_class(static::$_instance));
729
+			$static_properties = $r->getStaticProperties();
730
+			foreach ($r->getDefaultProperties() as $property => $value) {
731
+				//don't set instance to null like it was originally,
732
+				//but it's static anyways, and we're ignoring static properties (for now at least)
733
+				if (! isset($static_properties[$property])) {
734
+					static::$_instance->{$property} = $value;
735
+				}
736
+			}
737
+			//and then directly call its constructor again, like we would if we were creating a new one
738
+			static::$_instance->__construct(
739
+				$timezone,
740
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
741
+			);
742
+			return self::instance();
743
+		}
744
+		return null;
745
+	}
746
+
747
+
748
+
749
+	/**
750
+	 * @return LoaderInterface
751
+	 * @throws InvalidArgumentException
752
+	 * @throws InvalidDataTypeException
753
+	 * @throws InvalidInterfaceException
754
+	 */
755
+	private static function getLoader()
756
+	{
757
+		if(! EEM_Base::$loader instanceof LoaderInterface) {
758
+			EEM_Base::$loader = LoaderFactory::getLoader();
759
+		}
760
+		return EEM_Base::$loader;
761
+	}
762
+
763
+
764
+
765
+	/**
766
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
767
+	 *
768
+	 * @param  boolean $translated return localized strings or JUST the array.
769
+	 * @return array
770
+	 * @throws EE_Error
771
+	 * @throws InvalidArgumentException
772
+	 * @throws InvalidDataTypeException
773
+	 * @throws InvalidInterfaceException
774
+	 */
775
+	public function status_array($translated = false)
776
+	{
777
+		if (! array_key_exists('Status', $this->_model_relations)) {
778
+			return array();
779
+		}
780
+		$model_name = $this->get_this_model_name();
781
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
782
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
783
+		$status_array = array();
784
+		foreach ($stati as $status) {
785
+			$status_array[$status->ID()] = $status->get('STS_code');
786
+		}
787
+		return $translated
788
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
789
+			: $status_array;
790
+	}
791
+
792
+
793
+
794
+	/**
795
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
796
+	 *
797
+	 * @param array $query_params             {
798
+	 * @var array $0 (where) array {
799
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
800
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
801
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
802
+	 *                                        conditions based on related models (and even
803
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
804
+	 *                                        name. Eg,
805
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
806
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
807
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
808
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
809
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
810
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
811
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
812
+	 *                                        to Venues (even when each of those models actually consisted of two
813
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
814
+	 *                                        just having
815
+	 *                                        "Venue.VNU_ID", you could have
816
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
817
+	 *                                        events are related to Registrations, which are related to Attendees). You
818
+	 *                                        can take it even further with
819
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
820
+	 *                                        (from the default of '='), change the value to an numerically-indexed
821
+	 *                                        array, where the first item in the list is the operator. eg: array(
822
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
823
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
824
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
825
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
826
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
827
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
828
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
829
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
830
+	 *                                        the value is a field, simply provide a third array item (true) to the
831
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
832
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
833
+	 *                                        Note: you can also use related model field names like you would any other
834
+	 *                                        field name. eg:
835
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
836
+	 *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
837
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
838
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
839
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
840
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
841
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
842
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
843
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
844
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
845
+	 *                                        "stick" until you specify an AND. eg
846
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
847
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
848
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
849
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
850
+	 *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
851
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
852
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
853
+	 *                                        too, eg:
854
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
855
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
856
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
857
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
858
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
859
+	 *                                        the OFFSET, the 2nd is the LIMIT
860
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
861
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
862
+	 *                                        following format array('on_join_limit'
863
+	 *                                        => array( 'table_alias', array(1,2) ) ).
864
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
865
+	 *                                        values are either 'ASC' or 'DESC'.
866
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
867
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
868
+	 *                                        DESC..." respectively. Like the
869
+	 *                                        'where' conditions, these fields can be on related models. Eg
870
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
871
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
872
+	 *                                        Attendee, Price, Datetime, etc.)
873
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
874
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
875
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
876
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
877
+	 *                                        order by the primary key. Eg,
878
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
879
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
880
+	 *                                        DTT_EVT_start) or
881
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
882
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
883
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
884
+	 *                                        'group_by'=>'VNU_ID', or
885
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
886
+	 *                                        if no
887
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
888
+	 *                                        model's primary key (or combined primary keys). This avoids some
889
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
890
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
891
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
892
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
893
+	 *                                        results)
894
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
895
+	 *                                        array where values are models to be joined in the query.Eg
896
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
897
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
898
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
899
+	 *                                        related models which belongs to the current model
900
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
901
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
902
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
903
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
904
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
905
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
906
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
907
+	 *                                        this model's default where conditions added to the query, use
908
+	 *                                        'this_model_only'. If you want to use all default where conditions
909
+	 *                                        (default), set to 'all'.
910
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
911
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
912
+	 *                                        everything? Or should we only show the current user items they should be
913
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
914
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
915
+	 *                                        }
916
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
917
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
918
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
919
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
920
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
921
+	 *                                        array( array(
922
+	 *                                        'OR'=>array(
923
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
924
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
925
+	 *                                        )
926
+	 *                                        ),
927
+	 *                                        'limit'=>10,
928
+	 *                                        'group_by'=>'TXN_ID'
929
+	 *                                        ));
930
+	 *                                        get all the answers to the question titled "shirt size" for event with id
931
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
932
+	 *                                        'Question.QST_display_text'=>'shirt size',
933
+	 *                                        'Registration.Event.EVT_ID'=>12
934
+	 *                                        ),
935
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
936
+	 *                                        ));
937
+	 * @throws EE_Error
938
+	 */
939
+	public function get_all($query_params = array())
940
+	{
941
+		if (isset($query_params['limit'])
942
+			&& ! isset($query_params['group_by'])
943
+		) {
944
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
945
+		}
946
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
947
+	}
948
+
949
+
950
+
951
+	/**
952
+	 * Modifies the query parameters so we only get back model objects
953
+	 * that "belong" to the current user
954
+	 *
955
+	 * @param array $query_params @see EEM_Base::get_all()
956
+	 * @return array like EEM_Base::get_all
957
+	 */
958
+	public function alter_query_params_to_only_include_mine($query_params = array())
959
+	{
960
+		$wp_user_field_name = $this->wp_user_field_name();
961
+		if ($wp_user_field_name) {
962
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
963
+		}
964
+		return $query_params;
965
+	}
966
+
967
+
968
+
969
+	/**
970
+	 * Returns the name of the field's name that points to the WP_User table
971
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
972
+	 * foreign key to the WP_User table)
973
+	 *
974
+	 * @return string|boolean string on success, boolean false when there is no
975
+	 * foreign key to the WP_User table
976
+	 */
977
+	public function wp_user_field_name()
978
+	{
979
+		try {
980
+			if (! empty($this->_model_chain_to_wp_user)) {
981
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
982
+				$last_model_name = end($models_to_follow_to_wp_users);
983
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
984
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
985
+			} else {
986
+				$model_with_fk_to_wp_users = $this;
987
+				$model_chain_to_wp_user = '';
988
+			}
989
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
990
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
991
+		} catch (EE_Error $e) {
992
+			return false;
993
+		}
994
+	}
995
+
996
+
997
+
998
+	/**
999
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
1000
+	 * (or transiently-related model) has a foreign key to the wp_users table;
1001
+	 * useful for finding if model objects of this type are 'owned' by the current user.
1002
+	 * This is an empty string when the foreign key is on this model and when it isn't,
1003
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
1004
+	 * (or transiently-related model)
1005
+	 *
1006
+	 * @return string
1007
+	 */
1008
+	public function model_chain_to_wp_user()
1009
+	{
1010
+		return $this->_model_chain_to_wp_user;
1011
+	}
1012
+
1013
+
1014
+
1015
+	/**
1016
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1017
+	 * like how registrations don't have a foreign key to wp_users, but the
1018
+	 * events they are for are), or is unrelated to wp users.
1019
+	 * generally available
1020
+	 *
1021
+	 * @return boolean
1022
+	 */
1023
+	public function is_owned()
1024
+	{
1025
+		if ($this->model_chain_to_wp_user()) {
1026
+			return true;
1027
+		}
1028
+		try {
1029
+			$this->get_foreign_key_to('WP_User');
1030
+			return true;
1031
+		} catch (EE_Error $e) {
1032
+			return false;
1033
+		}
1034
+	}
1035
+
1036
+
1037
+	/**
1038
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1039
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1040
+	 * the model)
1041
+	 *
1042
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1043
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1044
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1045
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1046
+	 *                                  override this and set the select to "*", or a specific column name, like
1047
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1048
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1049
+	 *                                  the aliases used to refer to this selection, and values are to be
1050
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1051
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1052
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1053
+	 * @throws EE_Error
1054
+	 * @throws InvalidArgumentException
1055
+	 */
1056
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1057
+	{
1058
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);;
1059
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1060
+		$select_expressions = $columns_to_select === null
1061
+			? $this->_construct_default_select_sql($model_query_info)
1062
+			: '';
1063
+		if ($this->_custom_selections instanceof CustomSelects) {
1064
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1065
+			$select_expressions .= $select_expressions
1066
+				? ', ' . $custom_expressions
1067
+				: $custom_expressions;
1068
+		}
1069
+
1070
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1071
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1072
+	}
1073
+
1074
+
1075
+	/**
1076
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1077
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1078
+	 * method of including extra select information.
1079
+	 *
1080
+	 * @param array             $query_params
1081
+	 * @param null|array|string $columns_to_select
1082
+	 * @return null|CustomSelects
1083
+	 * @throws InvalidArgumentException
1084
+	 */
1085
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1086
+	{
1087
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1088
+			return null;
1089
+		}
1090
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1091
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1092
+		return new CustomSelects($selects);
1093
+	}
1094
+
1095
+
1096
+
1097
+	/**
1098
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1099
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1100
+	 * take care of joins, field preparation etc.
1101
+	 *
1102
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1103
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1104
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1105
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1106
+	 *                                  override this and set the select to "*", or a specific column name, like
1107
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1108
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1109
+	 *                                  the aliases used to refer to this selection, and values are to be
1110
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1111
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1112
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1113
+	 * @throws EE_Error
1114
+	 */
1115
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1116
+	{
1117
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1118
+	}
1119
+
1120
+
1121
+
1122
+	/**
1123
+	 * For creating a custom select statement
1124
+	 *
1125
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1126
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1127
+	 *                                 SQL, and 1=>is the datatype
1128
+	 * @throws EE_Error
1129
+	 * @return string
1130
+	 */
1131
+	private function _construct_select_from_input($columns_to_select)
1132
+	{
1133
+		if (is_array($columns_to_select)) {
1134
+			$select_sql_array = array();
1135
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1136
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1137
+					throw new EE_Error(
1138
+						sprintf(
1139
+							__(
1140
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1141
+								'event_espresso'
1142
+							),
1143
+							$selection_and_datatype,
1144
+							$alias
1145
+						)
1146
+					);
1147
+				}
1148
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1149
+					throw new EE_Error(
1150
+						sprintf(
1151
+							esc_html__(
1152
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1153
+								'event_espresso'
1154
+							),
1155
+							$selection_and_datatype[1],
1156
+							$selection_and_datatype[0],
1157
+							$alias,
1158
+							implode(', ', $this->_valid_wpdb_data_types)
1159
+						)
1160
+					);
1161
+				}
1162
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1163
+			}
1164
+			$columns_to_select_string = implode(', ', $select_sql_array);
1165
+		} else {
1166
+			$columns_to_select_string = $columns_to_select;
1167
+		}
1168
+		return $columns_to_select_string;
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1175
+	 *
1176
+	 * @return string
1177
+	 * @throws EE_Error
1178
+	 */
1179
+	public function primary_key_name()
1180
+	{
1181
+		return $this->get_primary_key_field()->get_name();
1182
+	}
1183
+
1184
+
1185
+
1186
+	/**
1187
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1188
+	 * If there is no primary key on this model, $id is treated as primary key string
1189
+	 *
1190
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1191
+	 * @return EE_Base_Class
1192
+	 */
1193
+	public function get_one_by_ID($id)
1194
+	{
1195
+		if ($this->get_from_entity_map($id)) {
1196
+			return $this->get_from_entity_map($id);
1197
+		}
1198
+		return $this->get_one(
1199
+			$this->alter_query_params_to_restrict_by_ID(
1200
+				$id,
1201
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1202
+			)
1203
+		);
1204
+	}
1205
+
1206
+
1207
+
1208
+	/**
1209
+	 * Alters query parameters to only get items with this ID are returned.
1210
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1211
+	 * or could just be a simple primary key ID
1212
+	 *
1213
+	 * @param int   $id
1214
+	 * @param array $query_params
1215
+	 * @return array of normal query params, @see EEM_Base::get_all
1216
+	 * @throws EE_Error
1217
+	 */
1218
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1219
+	{
1220
+		if (! isset($query_params[0])) {
1221
+			$query_params[0] = array();
1222
+		}
1223
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1224
+		if ($conditions_from_id === null) {
1225
+			$query_params[0][$this->primary_key_name()] = $id;
1226
+		} else {
1227
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1228
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1229
+		}
1230
+		return $query_params;
1231
+	}
1232
+
1233
+
1234
+
1235
+	/**
1236
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1237
+	 * array. If no item is found, null is returned.
1238
+	 *
1239
+	 * @param array $query_params like EEM_Base's $query_params variable.
1240
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1241
+	 * @throws EE_Error
1242
+	 */
1243
+	public function get_one($query_params = array())
1244
+	{
1245
+		if (! is_array($query_params)) {
1246
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1247
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1248
+					gettype($query_params)), '4.6.0');
1249
+			$query_params = array();
1250
+		}
1251
+		$query_params['limit'] = 1;
1252
+		$items = $this->get_all($query_params);
1253
+		if (empty($items)) {
1254
+			return null;
1255
+		}
1256
+		return array_shift($items);
1257
+	}
1258
+
1259
+
1260
+
1261
+	/**
1262
+	 * Returns the next x number of items in sequence from the given value as
1263
+	 * found in the database matching the given query conditions.
1264
+	 *
1265
+	 * @param mixed $current_field_value    Value used for the reference point.
1266
+	 * @param null  $field_to_order_by      What field is used for the
1267
+	 *                                      reference point.
1268
+	 * @param int   $limit                  How many to return.
1269
+	 * @param array $query_params           Extra conditions on the query.
1270
+	 * @param null  $columns_to_select      If left null, then an array of
1271
+	 *                                      EE_Base_Class objects is returned,
1272
+	 *                                      otherwise you can indicate just the
1273
+	 *                                      columns you want returned.
1274
+	 * @return EE_Base_Class[]|array
1275
+	 * @throws EE_Error
1276
+	 */
1277
+	public function next_x(
1278
+		$current_field_value,
1279
+		$field_to_order_by = null,
1280
+		$limit = 1,
1281
+		$query_params = array(),
1282
+		$columns_to_select = null
1283
+	) {
1284
+		return $this->_get_consecutive(
1285
+			$current_field_value,
1286
+			'>',
1287
+			$field_to_order_by,
1288
+			$limit,
1289
+			$query_params,
1290
+			$columns_to_select
1291
+		);
1292
+	}
1293
+
1294
+
1295
+
1296
+	/**
1297
+	 * Returns the previous x number of items in sequence from the given value
1298
+	 * as found in the database matching the given query conditions.
1299
+	 *
1300
+	 * @param mixed $current_field_value    Value used for the reference point.
1301
+	 * @param null  $field_to_order_by      What field is used for the
1302
+	 *                                      reference point.
1303
+	 * @param int   $limit                  How many to return.
1304
+	 * @param array $query_params           Extra conditions on the query.
1305
+	 * @param null  $columns_to_select      If left null, then an array of
1306
+	 *                                      EE_Base_Class objects is returned,
1307
+	 *                                      otherwise you can indicate just the
1308
+	 *                                      columns you want returned.
1309
+	 * @return EE_Base_Class[]|array
1310
+	 * @throws EE_Error
1311
+	 */
1312
+	public function previous_x(
1313
+		$current_field_value,
1314
+		$field_to_order_by = null,
1315
+		$limit = 1,
1316
+		$query_params = array(),
1317
+		$columns_to_select = null
1318
+	) {
1319
+		return $this->_get_consecutive(
1320
+			$current_field_value,
1321
+			'<',
1322
+			$field_to_order_by,
1323
+			$limit,
1324
+			$query_params,
1325
+			$columns_to_select
1326
+		);
1327
+	}
1328
+
1329
+
1330
+
1331
+	/**
1332
+	 * Returns the next item in sequence from the given value as found in the
1333
+	 * database matching the given query conditions.
1334
+	 *
1335
+	 * @param mixed $current_field_value    Value used for the reference point.
1336
+	 * @param null  $field_to_order_by      What field is used for the
1337
+	 *                                      reference point.
1338
+	 * @param array $query_params           Extra conditions on the query.
1339
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1340
+	 *                                      object is returned, otherwise you
1341
+	 *                                      can indicate just the columns you
1342
+	 *                                      want and a single array indexed by
1343
+	 *                                      the columns will be returned.
1344
+	 * @return EE_Base_Class|null|array()
1345
+	 * @throws EE_Error
1346
+	 */
1347
+	public function next(
1348
+		$current_field_value,
1349
+		$field_to_order_by = null,
1350
+		$query_params = array(),
1351
+		$columns_to_select = null
1352
+	) {
1353
+		$results = $this->_get_consecutive(
1354
+			$current_field_value,
1355
+			'>',
1356
+			$field_to_order_by,
1357
+			1,
1358
+			$query_params,
1359
+			$columns_to_select
1360
+		);
1361
+		return empty($results) ? null : reset($results);
1362
+	}
1363
+
1364
+
1365
+
1366
+	/**
1367
+	 * Returns the previous item in sequence from the given value as found in
1368
+	 * the database matching the given query conditions.
1369
+	 *
1370
+	 * @param mixed $current_field_value    Value used for the reference point.
1371
+	 * @param null  $field_to_order_by      What field is used for the
1372
+	 *                                      reference point.
1373
+	 * @param array $query_params           Extra conditions on the query.
1374
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1375
+	 *                                      object is returned, otherwise you
1376
+	 *                                      can indicate just the columns you
1377
+	 *                                      want and a single array indexed by
1378
+	 *                                      the columns will be returned.
1379
+	 * @return EE_Base_Class|null|array()
1380
+	 * @throws EE_Error
1381
+	 */
1382
+	public function previous(
1383
+		$current_field_value,
1384
+		$field_to_order_by = null,
1385
+		$query_params = array(),
1386
+		$columns_to_select = null
1387
+	) {
1388
+		$results = $this->_get_consecutive(
1389
+			$current_field_value,
1390
+			'<',
1391
+			$field_to_order_by,
1392
+			1,
1393
+			$query_params,
1394
+			$columns_to_select
1395
+		);
1396
+		return empty($results) ? null : reset($results);
1397
+	}
1398
+
1399
+
1400
+
1401
+	/**
1402
+	 * Returns the a consecutive number of items in sequence from the given
1403
+	 * value as found in the database matching the given query conditions.
1404
+	 *
1405
+	 * @param mixed  $current_field_value   Value used for the reference point.
1406
+	 * @param string $operand               What operand is used for the sequence.
1407
+	 * @param string $field_to_order_by     What field is used for the reference point.
1408
+	 * @param int    $limit                 How many to return.
1409
+	 * @param array  $query_params          Extra conditions on the query.
1410
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1411
+	 *                                      otherwise you can indicate just the columns you want returned.
1412
+	 * @return EE_Base_Class[]|array
1413
+	 * @throws EE_Error
1414
+	 */
1415
+	protected function _get_consecutive(
1416
+		$current_field_value,
1417
+		$operand = '>',
1418
+		$field_to_order_by = null,
1419
+		$limit = 1,
1420
+		$query_params = array(),
1421
+		$columns_to_select = null
1422
+	) {
1423
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1424
+		if (empty($field_to_order_by)) {
1425
+			if ($this->has_primary_key_field()) {
1426
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1427
+			} else {
1428
+				if (WP_DEBUG) {
1429
+					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).',
1430
+						'event_espresso'));
1431
+				}
1432
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1433
+				return array();
1434
+			}
1435
+		}
1436
+		if (! is_array($query_params)) {
1437
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1438
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1439
+					gettype($query_params)), '4.6.0');
1440
+			$query_params = array();
1441
+		}
1442
+		//let's add the where query param for consecutive look up.
1443
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1444
+		$query_params['limit'] = $limit;
1445
+		//set direction
1446
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1447
+		$query_params['order_by'] = $operand === '>'
1448
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1449
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1450
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1451
+		if (empty($columns_to_select)) {
1452
+			return $this->get_all($query_params);
1453
+		}
1454
+		//getting just the fields
1455
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1456
+	}
1457
+
1458
+
1459
+
1460
+	/**
1461
+	 * This sets the _timezone property after model object has been instantiated.
1462
+	 *
1463
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1464
+	 */
1465
+	public function set_timezone($timezone)
1466
+	{
1467
+		if ($timezone !== null) {
1468
+			$this->_timezone = $timezone;
1469
+		}
1470
+		//note we need to loop through relations and set the timezone on those objects as well.
1471
+		foreach ($this->_model_relations as $relation) {
1472
+			$relation->set_timezone($timezone);
1473
+		}
1474
+		//and finally we do the same for any datetime fields
1475
+		foreach ($this->_fields as $field) {
1476
+			if ($field instanceof EE_Datetime_Field) {
1477
+				$field->set_timezone($timezone);
1478
+			}
1479
+		}
1480
+	}
1481
+
1482
+
1483
+
1484
+	/**
1485
+	 * This just returns whatever is set for the current timezone.
1486
+	 *
1487
+	 * @access public
1488
+	 * @return string
1489
+	 */
1490
+	public function get_timezone()
1491
+	{
1492
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1493
+		if (empty($this->_timezone)) {
1494
+			foreach ($this->_fields as $field) {
1495
+				if ($field instanceof EE_Datetime_Field) {
1496
+					$this->set_timezone($field->get_timezone());
1497
+					break;
1498
+				}
1499
+			}
1500
+		}
1501
+		//if timezone STILL empty then return the default timezone for the site.
1502
+		if (empty($this->_timezone)) {
1503
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1504
+		}
1505
+		return $this->_timezone;
1506
+	}
1507
+
1508
+
1509
+
1510
+	/**
1511
+	 * This returns the date formats set for the given field name and also ensures that
1512
+	 * $this->_timezone property is set correctly.
1513
+	 *
1514
+	 * @since 4.6.x
1515
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1516
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1517
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1518
+	 * @return array formats in an array with the date format first, and the time format last.
1519
+	 */
1520
+	public function get_formats_for($field_name, $pretty = false)
1521
+	{
1522
+		$field_settings = $this->field_settings_for($field_name);
1523
+		//if not a valid EE_Datetime_Field then throw error
1524
+		if (! $field_settings instanceof EE_Datetime_Field) {
1525
+			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.',
1526
+				'event_espresso'), $field_name));
1527
+		}
1528
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1529
+		//the field.
1530
+		$this->_timezone = $field_settings->get_timezone();
1531
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1532
+	}
1533
+
1534
+
1535
+
1536
+	/**
1537
+	 * This returns the current time in a format setup for a query on this model.
1538
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1539
+	 * it will return:
1540
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1541
+	 *  NOW
1542
+	 *  - or a unix timestamp (equivalent to time())
1543
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1544
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1545
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1546
+	 * @since 4.6.x
1547
+	 * @param string $field_name       The field the current time is needed for.
1548
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1549
+	 *                                 formatted string matching the set format for the field in the set timezone will
1550
+	 *                                 be returned.
1551
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1552
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1553
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1554
+	 *                                 exception is triggered.
1555
+	 */
1556
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1557
+	{
1558
+		$formats = $this->get_formats_for($field_name);
1559
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1560
+		if ($timestamp) {
1561
+			return $DateTime->format('U');
1562
+		}
1563
+		//not returning timestamp, so return formatted string in timezone.
1564
+		switch ($what) {
1565
+			case 'time' :
1566
+				return $DateTime->format($formats[1]);
1567
+				break;
1568
+			case 'date' :
1569
+				return $DateTime->format($formats[0]);
1570
+				break;
1571
+			default :
1572
+				return $DateTime->format(implode(' ', $formats));
1573
+				break;
1574
+		}
1575
+	}
1576
+
1577
+
1578
+
1579
+	/**
1580
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1581
+	 * for the model are.  Returns a DateTime object.
1582
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1583
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1584
+	 * ignored.
1585
+	 *
1586
+	 * @param string $field_name      The field being setup.
1587
+	 * @param string $timestring      The date time string being used.
1588
+	 * @param string $incoming_format The format for the time string.
1589
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1590
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1591
+	 *                                format is
1592
+	 *                                'U', this is ignored.
1593
+	 * @return DateTime
1594
+	 * @throws EE_Error
1595
+	 */
1596
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1597
+	{
1598
+		//just using this to ensure the timezone is set correctly internally
1599
+		$this->get_formats_for($field_name);
1600
+		//load EEH_DTT_Helper
1601
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1602
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1603
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1604
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1605
+	}
1606
+
1607
+
1608
+
1609
+	/**
1610
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1611
+	 *
1612
+	 * @return EE_Table_Base[]
1613
+	 */
1614
+	public function get_tables()
1615
+	{
1616
+		return $this->_tables;
1617
+	}
1618
+
1619
+
1620
+
1621
+	/**
1622
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1623
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1624
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1625
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1626
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1627
+	 * model object with EVT_ID = 1
1628
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1629
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1630
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1631
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1632
+	 * are not specified)
1633
+	 *
1634
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1635
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1636
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1637
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1638
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1639
+	 *                                         ID=34, we'd use this method as follows:
1640
+	 *                                         EEM_Transaction::instance()->update(
1641
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1642
+	 *                                         array(array('TXN_ID'=>34)));
1643
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1644
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1645
+	 *                                         consider updating Question's QST_admin_label field is of type
1646
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1647
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1648
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1649
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1650
+	 *                                         TRUE, it is assumed that you've already called
1651
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1652
+	 *                                         malicious javascript. However, if
1653
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1654
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1655
+	 *                                         and every other field, before insertion. We provide this parameter
1656
+	 *                                         because model objects perform their prepare_for_set function on all
1657
+	 *                                         their values, and so don't need to be called again (and in many cases,
1658
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1659
+	 *                                         prepare_for_set method...)
1660
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1661
+	 *                                         in this model's entity map according to $fields_n_values that match
1662
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1663
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1664
+	 *                                         could get out-of-sync with the database
1665
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1666
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1667
+	 *                                         bad)
1668
+	 * @throws EE_Error
1669
+	 */
1670
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1671
+	{
1672
+		if (! is_array($query_params)) {
1673
+			EE_Error::doing_it_wrong('EEM_Base::update',
1674
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1675
+					gettype($query_params)), '4.6.0');
1676
+			$query_params = array();
1677
+		}
1678
+		/**
1679
+		 * Action called before a model update call has been made.
1680
+		 *
1681
+		 * @param EEM_Base $model
1682
+		 * @param array    $fields_n_values the updated fields and their new values
1683
+		 * @param array    $query_params    @see EEM_Base::get_all()
1684
+		 */
1685
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1686
+		/**
1687
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1688
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1689
+		 *
1690
+		 * @param array    $fields_n_values fields and their new values
1691
+		 * @param EEM_Base $model           the model being queried
1692
+		 * @param array    $query_params    see EEM_Base::get_all()
1693
+		 */
1694
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1695
+			$query_params);
1696
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1697
+		//to do that, for each table, verify that it's PK isn't null.
1698
+		$tables = $this->get_tables();
1699
+		//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
1700
+		//NOTE: we should make this code more efficient by NOT querying twice
1701
+		//before the real update, but that needs to first go through ALPHA testing
1702
+		//as it's dangerous. says Mike August 8 2014
1703
+		//we want to make sure the default_where strategy is ignored
1704
+		$this->_ignore_where_strategy = true;
1705
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1706
+		foreach ($wpdb_select_results as $wpdb_result) {
1707
+			// type cast stdClass as array
1708
+			$wpdb_result = (array)$wpdb_result;
1709
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1710
+			if ($this->has_primary_key_field()) {
1711
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1712
+			} else {
1713
+				//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)
1714
+				$main_table_pk_value = null;
1715
+			}
1716
+			//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
1717
+			//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
1718
+			if (count($tables) > 1) {
1719
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1720
+				//in that table, and so we'll want to insert one
1721
+				foreach ($tables as $table_obj) {
1722
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1723
+					//if there is no private key for this table on the results, it means there's no entry
1724
+					//in this table, right? so insert a row in the current table, using any fields available
1725
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1726
+						   && $wpdb_result[$this_table_pk_column])
1727
+					) {
1728
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1729
+							$main_table_pk_value);
1730
+						//if we died here, report the error
1731
+						if (! $success) {
1732
+							return false;
1733
+						}
1734
+					}
1735
+				}
1736
+			}
1737
+			//				//and now check that if we have cached any models by that ID on the model, that
1738
+			//				//they also get updated properly
1739
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1740
+			//				if( $model_object ){
1741
+			//					foreach( $fields_n_values as $field => $value ){
1742
+			//						$model_object->set($field, $value);
1743
+			//let's make sure default_where strategy is followed now
1744
+			$this->_ignore_where_strategy = false;
1745
+		}
1746
+		//if we want to keep model objects in sync, AND
1747
+		//if this wasn't called from a model object (to update itself)
1748
+		//then we want to make sure we keep all the existing
1749
+		//model objects in sync with the db
1750
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1751
+			if ($this->has_primary_key_field()) {
1752
+				$model_objs_affected_ids = $this->get_col($query_params);
1753
+			} else {
1754
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1755
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1756
+				$model_objs_affected_ids = array();
1757
+				foreach ($models_affected_key_columns as $row) {
1758
+					$combined_index_key = $this->get_index_primary_key_string($row);
1759
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1760
+				}
1761
+			}
1762
+			if (! $model_objs_affected_ids) {
1763
+				//wait wait wait- if nothing was affected let's stop here
1764
+				return 0;
1765
+			}
1766
+			foreach ($model_objs_affected_ids as $id) {
1767
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1768
+				if ($model_obj_in_entity_map) {
1769
+					foreach ($fields_n_values as $field => $new_value) {
1770
+						$model_obj_in_entity_map->set($field, $new_value);
1771
+					}
1772
+				}
1773
+			}
1774
+			//if there is a primary key on this model, we can now do a slight optimization
1775
+			if ($this->has_primary_key_field()) {
1776
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1777
+				$query_params = array(
1778
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1779
+					'limit'                    => count($model_objs_affected_ids),
1780
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1781
+				);
1782
+			}
1783
+		}
1784
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1785
+		$SQL = "UPDATE "
1786
+			   . $model_query_info->get_full_join_sql()
1787
+			   . " SET "
1788
+			   . $this->_construct_update_sql($fields_n_values)
1789
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1790
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1791
+		/**
1792
+		 * Action called after a model update call has been made.
1793
+		 *
1794
+		 * @param EEM_Base $model
1795
+		 * @param array    $fields_n_values the updated fields and their new values
1796
+		 * @param array    $query_params    @see EEM_Base::get_all()
1797
+		 * @param int      $rows_affected
1798
+		 */
1799
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1800
+		return $rows_affected;//how many supposedly got updated
1801
+	}
1802
+
1803
+
1804
+
1805
+	/**
1806
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1807
+	 * are teh values of the field specified (or by default the primary key field)
1808
+	 * that matched the query params. Note that you should pass the name of the
1809
+	 * model FIELD, not the database table's column name.
1810
+	 *
1811
+	 * @param array  $query_params @see EEM_Base::get_all()
1812
+	 * @param string $field_to_select
1813
+	 * @return array just like $wpdb->get_col()
1814
+	 * @throws EE_Error
1815
+	 */
1816
+	public function get_col($query_params = array(), $field_to_select = null)
1817
+	{
1818
+		if ($field_to_select) {
1819
+			$field = $this->field_settings_for($field_to_select);
1820
+		} elseif ($this->has_primary_key_field()) {
1821
+			$field = $this->get_primary_key_field();
1822
+		} else {
1823
+			//no primary key, just grab the first column
1824
+			$field = reset($this->field_settings());
1825
+		}
1826
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1827
+		$select_expressions = $field->get_qualified_column();
1828
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1829
+		return $this->_do_wpdb_query('get_col', array($SQL));
1830
+	}
1831
+
1832
+
1833
+
1834
+	/**
1835
+	 * Returns a single column value for a single row from the database
1836
+	 *
1837
+	 * @param array  $query_params    @see EEM_Base::get_all()
1838
+	 * @param string $field_to_select @see EEM_Base::get_col()
1839
+	 * @return string
1840
+	 * @throws EE_Error
1841
+	 */
1842
+	public function get_var($query_params = array(), $field_to_select = null)
1843
+	{
1844
+		$query_params['limit'] = 1;
1845
+		$col = $this->get_col($query_params, $field_to_select);
1846
+		if (! empty($col)) {
1847
+			return reset($col);
1848
+		}
1849
+		return null;
1850
+	}
1851
+
1852
+
1853
+
1854
+	/**
1855
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1856
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1857
+	 * injection, but currently no further filtering is done
1858
+	 *
1859
+	 * @global      $wpdb
1860
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1861
+	 *                               be updated to in the DB
1862
+	 * @return string of SQL
1863
+	 * @throws EE_Error
1864
+	 */
1865
+	public function _construct_update_sql($fields_n_values)
1866
+	{
1867
+		/** @type WPDB $wpdb */
1868
+		global $wpdb;
1869
+		$cols_n_values = array();
1870
+		foreach ($fields_n_values as $field_name => $value) {
1871
+			$field_obj = $this->field_settings_for($field_name);
1872
+			//if the value is NULL, we want to assign the value to that.
1873
+			//wpdb->prepare doesn't really handle that properly
1874
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1875
+			$value_sql = $prepared_value === null ? 'NULL'
1876
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1877
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1878
+		}
1879
+		return implode(",", $cols_n_values);
1880
+	}
1881
+
1882
+
1883
+
1884
+	/**
1885
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1886
+	 * Performs a HARD delete, meaning the database row should always be removed,
1887
+	 * not just have a flag field on it switched
1888
+	 * Wrapper for EEM_Base::delete_permanently()
1889
+	 *
1890
+	 * @param mixed $id
1891
+	 * @param boolean $allow_blocking
1892
+	 * @return int the number of rows deleted
1893
+	 * @throws EE_Error
1894
+	 */
1895
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1896
+	{
1897
+		return $this->delete_permanently(
1898
+			array(
1899
+				array($this->get_primary_key_field()->get_name() => $id),
1900
+				'limit' => 1,
1901
+			),
1902
+			$allow_blocking
1903
+		);
1904
+	}
1905
+
1906
+
1907
+
1908
+	/**
1909
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1910
+	 * Wrapper for EEM_Base::delete()
1911
+	 *
1912
+	 * @param mixed $id
1913
+	 * @param boolean $allow_blocking
1914
+	 * @return int the number of rows deleted
1915
+	 * @throws EE_Error
1916
+	 */
1917
+	public function delete_by_ID($id, $allow_blocking = true)
1918
+	{
1919
+		return $this->delete(
1920
+			array(
1921
+				array($this->get_primary_key_field()->get_name() => $id),
1922
+				'limit' => 1,
1923
+			),
1924
+			$allow_blocking
1925
+		);
1926
+	}
1927
+
1928
+
1929
+
1930
+	/**
1931
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1932
+	 * meaning if the model has a field that indicates its been "trashed" or
1933
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1934
+	 *
1935
+	 * @see EEM_Base::delete_permanently
1936
+	 * @param array   $query_params
1937
+	 * @param boolean $allow_blocking
1938
+	 * @return int how many rows got deleted
1939
+	 * @throws EE_Error
1940
+	 */
1941
+	public function delete($query_params, $allow_blocking = true)
1942
+	{
1943
+		return $this->delete_permanently($query_params, $allow_blocking);
1944
+	}
1945
+
1946
+
1947
+
1948
+	/**
1949
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1950
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1951
+	 * as archived, not actually deleted
1952
+	 *
1953
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1954
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1955
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1956
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1957
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1958
+	 *                                DB
1959
+	 * @return int how many rows got deleted
1960
+	 * @throws EE_Error
1961
+	 */
1962
+	public function delete_permanently($query_params, $allow_blocking = true)
1963
+	{
1964
+		/**
1965
+		 * Action called just before performing a real deletion query. You can use the
1966
+		 * model and its $query_params to find exactly which items will be deleted
1967
+		 *
1968
+		 * @param EEM_Base $model
1969
+		 * @param array    $query_params   @see EEM_Base::get_all()
1970
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1971
+		 *                                 to block (prevent) this deletion
1972
+		 */
1973
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1974
+		//some MySQL databases may be running safe mode, which may restrict
1975
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1976
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1977
+		//to delete them
1978
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1979
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1980
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1981
+			$columns_and_ids_for_deleting
1982
+		);
1983
+		/**
1984
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1985
+		 *
1986
+		 * @param EEM_Base $this  The model instance being acted on.
1987
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1988
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1989
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1990
+		 *                                                  derived from the incoming query parameters.
1991
+		 *                                                  @see details on the structure of this array in the phpdocs
1992
+		 *                                                  for the `_get_ids_for_delete_method`
1993
+		 *
1994
+		 */
1995
+		do_action('AHEE__EEM_Base__delete__before_query',
1996
+			$this,
1997
+			$query_params,
1998
+			$allow_blocking,
1999
+			$columns_and_ids_for_deleting
2000
+		);
2001
+		if ($deletion_where_query_part) {
2002
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2003
+			$table_aliases = array_keys($this->_tables);
2004
+			$SQL = "DELETE "
2005
+				   . implode(", ", $table_aliases)
2006
+				   . " FROM "
2007
+				   . $model_query_info->get_full_join_sql()
2008
+				   . " WHERE "
2009
+				   . $deletion_where_query_part;
2010
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2011
+		} else {
2012
+			$rows_deleted = 0;
2013
+		}
2014
+
2015
+		//Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2016
+		//there was no error with the delete query.
2017
+		if ($this->has_primary_key_field()
2018
+			&& $rows_deleted !== false
2019
+			&& isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2020
+		) {
2021
+			$ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2022
+			foreach ($ids_for_removal as $id) {
2023
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2024
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2025
+				}
2026
+			}
2027
+
2028
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2029
+			//`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2030
+			//unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2031
+			// (although it is possible).
2032
+			//Note this can be skipped by using the provided filter and returning false.
2033
+			if (apply_filters(
2034
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2035
+				! $this instanceof EEM_Extra_Meta,
2036
+				$this
2037
+			)) {
2038
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2039
+					0 => array(
2040
+						'EXM_type' => $this->get_this_model_name(),
2041
+						'OBJ_ID'   => array(
2042
+							'IN',
2043
+							$ids_for_removal
2044
+						)
2045
+					)
2046
+				));
2047
+			}
2048
+		}
2049
+
2050
+		/**
2051
+		 * Action called just after performing a real deletion query. Although at this point the
2052
+		 * items should have been deleted
2053
+		 *
2054
+		 * @param EEM_Base $model
2055
+		 * @param array    $query_params @see EEM_Base::get_all()
2056
+		 * @param int      $rows_deleted
2057
+		 */
2058
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2059
+		return $rows_deleted;//how many supposedly got deleted
2060
+	}
2061
+
2062
+
2063
+
2064
+	/**
2065
+	 * Checks all the relations that throw error messages when there are blocking related objects
2066
+	 * for related model objects. If there are any related model objects on those relations,
2067
+	 * adds an EE_Error, and return true
2068
+	 *
2069
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2070
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2071
+	 *                                                 should be ignored when determining whether there are related
2072
+	 *                                                 model objects which block this model object's deletion. Useful
2073
+	 *                                                 if you know A is related to B and are considering deleting A,
2074
+	 *                                                 but want to see if A has any other objects blocking its deletion
2075
+	 *                                                 before removing the relation between A and B
2076
+	 * @return boolean
2077
+	 * @throws EE_Error
2078
+	 */
2079
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2080
+	{
2081
+		//first, if $ignore_this_model_obj was supplied, get its model
2082
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2083
+			$ignored_model = $ignore_this_model_obj->get_model();
2084
+		} else {
2085
+			$ignored_model = null;
2086
+		}
2087
+		//now check all the relations of $this_model_obj_or_id and see if there
2088
+		//are any related model objects blocking it?
2089
+		$is_blocked = false;
2090
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2091
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2092
+				//if $ignore_this_model_obj was supplied, then for the query
2093
+				//on that model needs to be told to ignore $ignore_this_model_obj
2094
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2095
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2096
+						array(
2097
+							$ignored_model->get_primary_key_field()->get_name() => array(
2098
+								'!=',
2099
+								$ignore_this_model_obj->ID(),
2100
+							),
2101
+						),
2102
+					));
2103
+				} else {
2104
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2105
+				}
2106
+				if ($related_model_objects) {
2107
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2108
+					$is_blocked = true;
2109
+				}
2110
+			}
2111
+		}
2112
+		return $is_blocked;
2113
+	}
2114
+
2115
+
2116
+	/**
2117
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2118
+	 * @param array $row_results_for_deleting
2119
+	 * @param bool  $allow_blocking
2120
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2121
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2122
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2123
+	 *                 deleted. Example:
2124
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2125
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2126
+	 *                 where each element is a group of columns and values that get deleted. Example:
2127
+	 *                      array(
2128
+	 *                          0 => array(
2129
+	 *                              'Term_Relationship.object_id' => 1
2130
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2131
+	 *                          ),
2132
+	 *                          1 => array(
2133
+	 *                              'Term_Relationship.object_id' => 1
2134
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2135
+	 *                          )
2136
+	 *                      )
2137
+	 * @throws EE_Error
2138
+	 */
2139
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2140
+	{
2141
+		$ids_to_delete_indexed_by_column = array();
2142
+		if ($this->has_primary_key_field()) {
2143
+			$primary_table = $this->_get_main_table();
2144
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2145
+			$other_tables = $this->_get_other_tables();
2146
+			$ids_to_delete_indexed_by_column = $query = array();
2147
+			foreach ($row_results_for_deleting as $item_to_delete) {
2148
+				//before we mark this item for deletion,
2149
+				//make sure there's no related entities blocking its deletion (if we're checking)
2150
+				if (
2151
+					$allow_blocking
2152
+					&& $this->delete_is_blocked_by_related_models(
2153
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2154
+					)
2155
+				) {
2156
+					continue;
2157
+				}
2158
+				//primary table deletes
2159
+				if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2160
+					$ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2161
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2162
+				}
2163
+			}
2164
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2165
+			$fields = $this->get_combined_primary_key_fields();
2166
+			foreach ($row_results_for_deleting as $item_to_delete) {
2167
+				$ids_to_delete_indexed_by_column_for_row = array();
2168
+				foreach ($fields as $cpk_field) {
2169
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2170
+						$ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2171
+							$item_to_delete[$cpk_field->get_qualified_column()];
2172
+					}
2173
+				}
2174
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2175
+			}
2176
+		} else {
2177
+			//so there's no primary key and no combined key...
2178
+			//sorry, can't help you
2179
+			throw new EE_Error(
2180
+				sprintf(
2181
+					__(
2182
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2183
+						"event_espresso"
2184
+					), get_class($this)
2185
+				)
2186
+			);
2187
+		}
2188
+		return $ids_to_delete_indexed_by_column;
2189
+	}
2190
+
2191
+
2192
+	/**
2193
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2194
+	 * the corresponding query_part for the query performing the delete.
2195
+	 *
2196
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2197
+	 * @return string
2198
+	 * @throws EE_Error
2199
+	 */
2200
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2201
+		$query_part = '';
2202
+		if (empty($ids_to_delete_indexed_by_column)) {
2203
+			return $query_part;
2204
+		} elseif ($this->has_primary_key_field()) {
2205
+			$query = array();
2206
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2207
+				//make sure we have unique $ids
2208
+				$ids = array_unique($ids);
2209
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2210
+			}
2211
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2212
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2213
+			$ways_to_identify_a_row = array();
2214
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2215
+				$values_for_each_combined_primary_key_for_a_row = array();
2216
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2217
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2218
+				}
2219
+				$ways_to_identify_a_row[] = '('
2220
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2221
+											. ')';
2222
+			}
2223
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2224
+		}
2225
+		return $query_part;
2226
+	}
2227
+
2228
+
2229
+
2230
+	/**
2231
+	 * Gets the model field by the fully qualified name
2232
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2233
+	 * @return EE_Model_Field_Base
2234
+	 */
2235
+	public function get_field_by_column($qualified_column_name)
2236
+	{
2237
+	   foreach($this->field_settings(true) as $field_name => $field_obj){
2238
+		   if($field_obj->get_qualified_column() === $qualified_column_name){
2239
+			   return $field_obj;
2240
+		   }
2241
+	   }
2242
+		throw new EE_Error(
2243
+			sprintf(
2244
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2245
+				$this->get_this_model_name(),
2246
+				$qualified_column_name
2247
+			)
2248
+		);
2249
+	}
2250
+
2251
+
2252
+
2253
+	/**
2254
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2255
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2256
+	 * column
2257
+	 *
2258
+	 * @param array  $query_params   like EEM_Base::get_all's
2259
+	 * @param string $field_to_count field on model to count by (not column name)
2260
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2261
+	 *                               that by the setting $distinct to TRUE;
2262
+	 * @return int
2263
+	 * @throws EE_Error
2264
+	 */
2265
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2266
+	{
2267
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2268
+		if ($field_to_count) {
2269
+			$field_obj = $this->field_settings_for($field_to_count);
2270
+			$column_to_count = $field_obj->get_qualified_column();
2271
+		} elseif ($this->has_primary_key_field()) {
2272
+			$pk_field_obj = $this->get_primary_key_field();
2273
+			$column_to_count = $pk_field_obj->get_qualified_column();
2274
+		} else {
2275
+			//there's no primary key
2276
+			//if we're counting distinct items, and there's no primary key,
2277
+			//we need to list out the columns for distinction;
2278
+			//otherwise we can just use star
2279
+			if ($distinct) {
2280
+				$columns_to_use = array();
2281
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2282
+					$columns_to_use[] = $field_obj->get_qualified_column();
2283
+				}
2284
+				$column_to_count = implode(',', $columns_to_use);
2285
+			} else {
2286
+				$column_to_count = '*';
2287
+			}
2288
+		}
2289
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2290
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2291
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2292
+	}
2293
+
2294
+
2295
+
2296
+	/**
2297
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2298
+	 *
2299
+	 * @param array  $query_params like EEM_Base::get_all
2300
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2301
+	 * @return float
2302
+	 * @throws EE_Error
2303
+	 */
2304
+	public function sum($query_params, $field_to_sum = null)
2305
+	{
2306
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2307
+		if ($field_to_sum) {
2308
+			$field_obj = $this->field_settings_for($field_to_sum);
2309
+		} else {
2310
+			$field_obj = $this->get_primary_key_field();
2311
+		}
2312
+		$column_to_count = $field_obj->get_qualified_column();
2313
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2314
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2315
+		$data_type = $field_obj->get_wpdb_data_type();
2316
+		if ($data_type === '%d' || $data_type === '%s') {
2317
+			return (float)$return_value;
2318
+		}
2319
+		//must be %f
2320
+		return (float)$return_value;
2321
+	}
2322
+
2323
+
2324
+
2325
+	/**
2326
+	 * Just calls the specified method on $wpdb with the given arguments
2327
+	 * Consolidates a little extra error handling code
2328
+	 *
2329
+	 * @param string $wpdb_method
2330
+	 * @param array  $arguments_to_provide
2331
+	 * @throws EE_Error
2332
+	 * @global wpdb  $wpdb
2333
+	 * @return mixed
2334
+	 */
2335
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2336
+	{
2337
+		//if we're in maintenance mode level 2, DON'T run any queries
2338
+		//because level 2 indicates the database needs updating and
2339
+		//is probably out of sync with the code
2340
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2341
+			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.",
2342
+				"event_espresso")));
2343
+		}
2344
+		/** @type WPDB $wpdb */
2345
+		global $wpdb;
2346
+		if (! method_exists($wpdb, $wpdb_method)) {
2347
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2348
+				'event_espresso'), $wpdb_method));
2349
+		}
2350
+		if (WP_DEBUG) {
2351
+			$old_show_errors_value = $wpdb->show_errors;
2352
+			$wpdb->show_errors(false);
2353
+		}
2354
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2355
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2356
+		if (WP_DEBUG) {
2357
+			$wpdb->show_errors($old_show_errors_value);
2358
+			if (! empty($wpdb->last_error)) {
2359
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2360
+			}
2361
+			if ($result === false) {
2362
+				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"',
2363
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2364
+			}
2365
+		} elseif ($result === false) {
2366
+			EE_Error::add_error(
2367
+				sprintf(
2368
+					__('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"',
2369
+						'event_espresso'),
2370
+					$wpdb_method,
2371
+					var_export($arguments_to_provide, true),
2372
+					$wpdb->last_error
2373
+				),
2374
+				__FILE__,
2375
+				__FUNCTION__,
2376
+				__LINE__
2377
+			);
2378
+		}
2379
+		return $result;
2380
+	}
2381
+
2382
+
2383
+
2384
+	/**
2385
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2386
+	 * and if there's an error tries to verify the DB is correct. Uses
2387
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2388
+	 * we should try to fix the EE core db, the addons, or just give up
2389
+	 *
2390
+	 * @param string $wpdb_method
2391
+	 * @param array  $arguments_to_provide
2392
+	 * @return mixed
2393
+	 */
2394
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2395
+	{
2396
+		/** @type WPDB $wpdb */
2397
+		global $wpdb;
2398
+		$wpdb->last_error = null;
2399
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2400
+		// was there an error running the query? but we don't care on new activations
2401
+		// (we're going to setup the DB anyway on new activations)
2402
+		if (($result === false || ! empty($wpdb->last_error))
2403
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2404
+		) {
2405
+			switch (EEM_Base::$_db_verification_level) {
2406
+				case EEM_Base::db_verified_none :
2407
+					// let's double-check core's DB
2408
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2409
+					break;
2410
+				case EEM_Base::db_verified_core :
2411
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2412
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2413
+					break;
2414
+				case EEM_Base::db_verified_addons :
2415
+					// ummmm... you in trouble
2416
+					return $result;
2417
+					break;
2418
+			}
2419
+			if (! empty($error_message)) {
2420
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2421
+				trigger_error($error_message);
2422
+			}
2423
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2424
+		}
2425
+		return $result;
2426
+	}
2427
+
2428
+
2429
+
2430
+	/**
2431
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2432
+	 * EEM_Base::$_db_verification_level
2433
+	 *
2434
+	 * @param string $wpdb_method
2435
+	 * @param array  $arguments_to_provide
2436
+	 * @return string
2437
+	 */
2438
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2439
+	{
2440
+		/** @type WPDB $wpdb */
2441
+		global $wpdb;
2442
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2443
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2444
+		$error_message = sprintf(
2445
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2446
+				'event_espresso'),
2447
+			$wpdb->last_error,
2448
+			$wpdb_method,
2449
+			wp_json_encode($arguments_to_provide)
2450
+		);
2451
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2452
+		return $error_message;
2453
+	}
2454
+
2455
+
2456
+
2457
+	/**
2458
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2459
+	 * EEM_Base::$_db_verification_level
2460
+	 *
2461
+	 * @param $wpdb_method
2462
+	 * @param $arguments_to_provide
2463
+	 * @return string
2464
+	 */
2465
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2466
+	{
2467
+		/** @type WPDB $wpdb */
2468
+		global $wpdb;
2469
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2470
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2471
+		$error_message = sprintf(
2472
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2473
+				'event_espresso'),
2474
+			$wpdb->last_error,
2475
+			$wpdb_method,
2476
+			wp_json_encode($arguments_to_provide)
2477
+		);
2478
+		EE_System::instance()->initialize_addons();
2479
+		return $error_message;
2480
+	}
2481
+
2482
+
2483
+
2484
+	/**
2485
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2486
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2487
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2488
+	 * ..."
2489
+	 *
2490
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2491
+	 * @return string
2492
+	 */
2493
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2494
+	{
2495
+		return " FROM " . $model_query_info->get_full_join_sql() .
2496
+			   $model_query_info->get_where_sql() .
2497
+			   $model_query_info->get_group_by_sql() .
2498
+			   $model_query_info->get_having_sql() .
2499
+			   $model_query_info->get_order_by_sql() .
2500
+			   $model_query_info->get_limit_sql();
2501
+	}
2502
+
2503
+
2504
+
2505
+	/**
2506
+	 * Set to easily debug the next X queries ran from this model.
2507
+	 *
2508
+	 * @param int $count
2509
+	 */
2510
+	public function show_next_x_db_queries($count = 1)
2511
+	{
2512
+		$this->_show_next_x_db_queries = $count;
2513
+	}
2514
+
2515
+
2516
+
2517
+	/**
2518
+	 * @param $sql_query
2519
+	 */
2520
+	public function show_db_query_if_previously_requested($sql_query)
2521
+	{
2522
+		if ($this->_show_next_x_db_queries > 0) {
2523
+			echo $sql_query;
2524
+			$this->_show_next_x_db_queries--;
2525
+		}
2526
+	}
2527
+
2528
+
2529
+
2530
+	/**
2531
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2532
+	 * There are the 3 cases:
2533
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2534
+	 * $otherModelObject has no ID, it is first saved.
2535
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2536
+	 * has no ID, it is first saved.
2537
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2538
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2539
+	 * join table
2540
+	 *
2541
+	 * @param        EE_Base_Class                     /int $thisModelObject
2542
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2543
+	 * @param string $relationName                     , key in EEM_Base::_relations
2544
+	 *                                                 an attendee to a group, you also want to specify which role they
2545
+	 *                                                 will have in that group. So you would use this parameter to
2546
+	 *                                                 specify array('role-column-name'=>'role-id')
2547
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2548
+	 *                                                 to for relation to methods that allow you to further specify
2549
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2550
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2551
+	 *                                                 because these will be inserted in any new rows created as well.
2552
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2553
+	 * @throws EE_Error
2554
+	 */
2555
+	public function add_relationship_to(
2556
+		$id_or_obj,
2557
+		$other_model_id_or_obj,
2558
+		$relationName,
2559
+		$extra_join_model_fields_n_values = array()
2560
+	) {
2561
+		$relation_obj = $this->related_settings_for($relationName);
2562
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2563
+	}
2564
+
2565
+
2566
+
2567
+	/**
2568
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2569
+	 * There are the 3 cases:
2570
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2571
+	 * error
2572
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2573
+	 * an error
2574
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2575
+	 *
2576
+	 * @param        EE_Base_Class /int $id_or_obj
2577
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2578
+	 * @param string $relationName key in EEM_Base::_relations
2579
+	 * @return boolean of success
2580
+	 * @throws EE_Error
2581
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2582
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2583
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2584
+	 *                             because these will be inserted in any new rows created as well.
2585
+	 */
2586
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2587
+	{
2588
+		$relation_obj = $this->related_settings_for($relationName);
2589
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2590
+	}
2591
+
2592
+
2593
+
2594
+	/**
2595
+	 * @param mixed           $id_or_obj
2596
+	 * @param string          $relationName
2597
+	 * @param array           $where_query_params
2598
+	 * @param EE_Base_Class[] objects to which relations were removed
2599
+	 * @return \EE_Base_Class[]
2600
+	 * @throws EE_Error
2601
+	 */
2602
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2603
+	{
2604
+		$relation_obj = $this->related_settings_for($relationName);
2605
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2606
+	}
2607
+
2608
+
2609
+
2610
+	/**
2611
+	 * Gets all the related items of the specified $model_name, using $query_params.
2612
+	 * Note: by default, we remove the "default query params"
2613
+	 * because we want to get even deleted items etc.
2614
+	 *
2615
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2616
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2617
+	 * @param array  $query_params like EEM_Base::get_all
2618
+	 * @return EE_Base_Class[]
2619
+	 * @throws EE_Error
2620
+	 */
2621
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2622
+	{
2623
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2624
+		$relation_settings = $this->related_settings_for($model_name);
2625
+		return $relation_settings->get_all_related($model_obj, $query_params);
2626
+	}
2627
+
2628
+
2629
+
2630
+	/**
2631
+	 * Deletes all the model objects across the relation indicated by $model_name
2632
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2633
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2634
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2635
+	 *
2636
+	 * @param EE_Base_Class|int|string $id_or_obj
2637
+	 * @param string                   $model_name
2638
+	 * @param array                    $query_params
2639
+	 * @return int how many deleted
2640
+	 * @throws EE_Error
2641
+	 */
2642
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2643
+	{
2644
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2645
+		$relation_settings = $this->related_settings_for($model_name);
2646
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2647
+	}
2648
+
2649
+
2650
+
2651
+	/**
2652
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2653
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2654
+	 * the model objects can't be hard deleted because of blocking related model objects,
2655
+	 * just does a soft-delete on them instead.
2656
+	 *
2657
+	 * @param EE_Base_Class|int|string $id_or_obj
2658
+	 * @param string                   $model_name
2659
+	 * @param array                    $query_params
2660
+	 * @return int how many deleted
2661
+	 * @throws EE_Error
2662
+	 */
2663
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2664
+	{
2665
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2666
+		$relation_settings = $this->related_settings_for($model_name);
2667
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2668
+	}
2669
+
2670
+
2671
+
2672
+	/**
2673
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2674
+	 * unless otherwise specified in the $query_params
2675
+	 *
2676
+	 * @param        int             /EE_Base_Class $id_or_obj
2677
+	 * @param string $model_name     like 'Event', or 'Registration'
2678
+	 * @param array  $query_params   like EEM_Base::get_all's
2679
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2680
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2681
+	 *                               that by the setting $distinct to TRUE;
2682
+	 * @return int
2683
+	 * @throws EE_Error
2684
+	 */
2685
+	public function count_related(
2686
+		$id_or_obj,
2687
+		$model_name,
2688
+		$query_params = array(),
2689
+		$field_to_count = null,
2690
+		$distinct = false
2691
+	) {
2692
+		$related_model = $this->get_related_model_obj($model_name);
2693
+		//we're just going to use the query params on the related model's normal get_all query,
2694
+		//except add a condition to say to match the current mod
2695
+		if (! isset($query_params['default_where_conditions'])) {
2696
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2697
+		}
2698
+		$this_model_name = $this->get_this_model_name();
2699
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2700
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2701
+		return $related_model->count($query_params, $field_to_count, $distinct);
2702
+	}
2703
+
2704
+
2705
+
2706
+	/**
2707
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2708
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2709
+	 *
2710
+	 * @param        int           /EE_Base_Class $id_or_obj
2711
+	 * @param string $model_name   like 'Event', or 'Registration'
2712
+	 * @param array  $query_params like EEM_Base::get_all's
2713
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2714
+	 * @return float
2715
+	 * @throws EE_Error
2716
+	 */
2717
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2718
+	{
2719
+		$related_model = $this->get_related_model_obj($model_name);
2720
+		if (! is_array($query_params)) {
2721
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2722
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2723
+					gettype($query_params)), '4.6.0');
2724
+			$query_params = array();
2725
+		}
2726
+		//we're just going to use the query params on the related model's normal get_all query,
2727
+		//except add a condition to say to match the current mod
2728
+		if (! isset($query_params['default_where_conditions'])) {
2729
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2730
+		}
2731
+		$this_model_name = $this->get_this_model_name();
2732
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2733
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2734
+		return $related_model->sum($query_params, $field_to_sum);
2735
+	}
2736
+
2737
+
2738
+
2739
+	/**
2740
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2741
+	 * $modelObject
2742
+	 *
2743
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2744
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2745
+	 * @param array               $query_params     like EEM_Base::get_all's
2746
+	 * @return EE_Base_Class
2747
+	 * @throws EE_Error
2748
+	 */
2749
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2750
+	{
2751
+		$query_params['limit'] = 1;
2752
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2753
+		if ($results) {
2754
+			return array_shift($results);
2755
+		}
2756
+		return null;
2757
+	}
2758
+
2759
+
2760
+
2761
+	/**
2762
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2763
+	 *
2764
+	 * @return string
2765
+	 */
2766
+	public function get_this_model_name()
2767
+	{
2768
+		return str_replace("EEM_", "", get_class($this));
2769
+	}
2770
+
2771
+
2772
+
2773
+	/**
2774
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2775
+	 *
2776
+	 * @return EE_Any_Foreign_Model_Name_Field
2777
+	 * @throws EE_Error
2778
+	 */
2779
+	public function get_field_containing_related_model_name()
2780
+	{
2781
+		foreach ($this->field_settings(true) as $field) {
2782
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2783
+				$field_with_model_name = $field;
2784
+			}
2785
+		}
2786
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2787
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2788
+				$this->get_this_model_name()));
2789
+		}
2790
+		return $field_with_model_name;
2791
+	}
2792
+
2793
+
2794
+
2795
+	/**
2796
+	 * Inserts a new entry into the database, for each table.
2797
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2798
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2799
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2800
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2801
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2802
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2803
+	 *
2804
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2805
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2806
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2807
+	 *                              of EEM_Base)
2808
+	 * @return int new primary key on main table that got inserted
2809
+	 * @throws EE_Error
2810
+	 */
2811
+	public function insert($field_n_values)
2812
+	{
2813
+		/**
2814
+		 * Filters the fields and their values before inserting an item using the models
2815
+		 *
2816
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2817
+		 * @param EEM_Base $model           the model used
2818
+		 */
2819
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2820
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2821
+			$main_table = $this->_get_main_table();
2822
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2823
+			if ($new_id !== false) {
2824
+				foreach ($this->_get_other_tables() as $other_table) {
2825
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2826
+				}
2827
+			}
2828
+			/**
2829
+			 * Done just after attempting to insert a new model object
2830
+			 *
2831
+			 * @param EEM_Base   $model           used
2832
+			 * @param array      $fields_n_values fields and their values
2833
+			 * @param int|string the              ID of the newly-inserted model object
2834
+			 */
2835
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2836
+			return $new_id;
2837
+		}
2838
+		return false;
2839
+	}
2840
+
2841
+
2842
+
2843
+	/**
2844
+	 * Checks that the result would satisfy the unique indexes on this model
2845
+	 *
2846
+	 * @param array  $field_n_values
2847
+	 * @param string $action
2848
+	 * @return boolean
2849
+	 * @throws EE_Error
2850
+	 */
2851
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2852
+	{
2853
+		foreach ($this->unique_indexes() as $index_name => $index) {
2854
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2855
+			if ($this->exists(array($uniqueness_where_params))) {
2856
+				EE_Error::add_error(
2857
+					sprintf(
2858
+						__(
2859
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2860
+							"event_espresso"
2861
+						),
2862
+						$action,
2863
+						$this->_get_class_name(),
2864
+						$index_name,
2865
+						implode(",", $index->field_names()),
2866
+						http_build_query($uniqueness_where_params)
2867
+					),
2868
+					__FILE__,
2869
+					__FUNCTION__,
2870
+					__LINE__
2871
+				);
2872
+				return false;
2873
+			}
2874
+		}
2875
+		return true;
2876
+	}
2877
+
2878
+
2879
+
2880
+	/**
2881
+	 * Checks the database for an item that conflicts (ie, if this item were
2882
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2883
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2884
+	 * can be either an EE_Base_Class or an array of fields n values
2885
+	 *
2886
+	 * @param EE_Base_Class|array $obj_or_fields_array
2887
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2888
+	 *                                                 when looking for conflicts
2889
+	 *                                                 (ie, if false, we ignore the model object's primary key
2890
+	 *                                                 when finding "conflicts". If true, it's also considered).
2891
+	 *                                                 Only works for INT primary key,
2892
+	 *                                                 STRING primary keys cannot be ignored
2893
+	 * @throws EE_Error
2894
+	 * @return EE_Base_Class|array
2895
+	 */
2896
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2897
+	{
2898
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2899
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2900
+		} elseif (is_array($obj_or_fields_array)) {
2901
+			$fields_n_values = $obj_or_fields_array;
2902
+		} else {
2903
+			throw new EE_Error(
2904
+				sprintf(
2905
+					__(
2906
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2907
+						"event_espresso"
2908
+					),
2909
+					get_class($this),
2910
+					$obj_or_fields_array
2911
+				)
2912
+			);
2913
+		}
2914
+		$query_params = array();
2915
+		if ($this->has_primary_key_field()
2916
+			&& ($include_primary_key
2917
+				|| $this->get_primary_key_field()
2918
+				   instanceof
2919
+				   EE_Primary_Key_String_Field)
2920
+			&& isset($fields_n_values[$this->primary_key_name()])
2921
+		) {
2922
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2923
+		}
2924
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2925
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2926
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2927
+		}
2928
+		//if there is nothing to base this search on, then we shouldn't find anything
2929
+		if (empty($query_params)) {
2930
+			return array();
2931
+		}
2932
+		return $this->get_one($query_params);
2933
+	}
2934
+
2935
+
2936
+
2937
+	/**
2938
+	 * Like count, but is optimized and returns a boolean instead of an int
2939
+	 *
2940
+	 * @param array $query_params
2941
+	 * @return boolean
2942
+	 * @throws EE_Error
2943
+	 */
2944
+	public function exists($query_params)
2945
+	{
2946
+		$query_params['limit'] = 1;
2947
+		return $this->count($query_params) > 0;
2948
+	}
2949
+
2950
+
2951
+
2952
+	/**
2953
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2954
+	 *
2955
+	 * @param int|string $id
2956
+	 * @return boolean
2957
+	 * @throws EE_Error
2958
+	 */
2959
+	public function exists_by_ID($id)
2960
+	{
2961
+		return $this->exists(
2962
+			array(
2963
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2964
+				array(
2965
+					$this->primary_key_name() => $id,
2966
+				),
2967
+			)
2968
+		);
2969
+	}
2970
+
2971
+
2972
+
2973
+	/**
2974
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2975
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2976
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2977
+	 * on the main table)
2978
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2979
+	 * cases where we want to call it directly rather than via insert().
2980
+	 *
2981
+	 * @access   protected
2982
+	 * @param EE_Table_Base $table
2983
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2984
+	 *                                       float
2985
+	 * @param int           $new_id          for now we assume only int keys
2986
+	 * @throws EE_Error
2987
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2988
+	 * @return int ID of new row inserted, or FALSE on failure
2989
+	 */
2990
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2991
+	{
2992
+		global $wpdb;
2993
+		$insertion_col_n_values = array();
2994
+		$format_for_insertion = array();
2995
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2996
+		foreach ($fields_on_table as $field_name => $field_obj) {
2997
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2998
+			if ($field_obj->is_auto_increment()) {
2999
+				continue;
3000
+			}
3001
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3002
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
3003
+			if ($prepared_value !== null) {
3004
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3005
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
3006
+			}
3007
+		}
3008
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3009
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
3010
+			//so add the fk to the main table as a column
3011
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3012
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
3013
+		}
3014
+		//insert the new entry
3015
+		$result = $this->_do_wpdb_query('insert',
3016
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
3017
+		if ($result === false) {
3018
+			return false;
3019
+		}
3020
+		//ok, now what do we return for the ID of the newly-inserted thing?
3021
+		if ($this->has_primary_key_field()) {
3022
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3023
+				return $wpdb->insert_id;
3024
+			}
3025
+			//it's not an auto-increment primary key, so
3026
+			//it must have been supplied
3027
+			return $fields_n_values[$this->get_primary_key_field()->get_name()];
3028
+		}
3029
+		//we can't return a  primary key because there is none. instead return
3030
+		//a unique string indicating this model
3031
+		return $this->get_index_primary_key_string($fields_n_values);
3032
+	}
3033
+
3034
+
3035
+
3036
+	/**
3037
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3038
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3039
+	 * and there is no default, we pass it along. WPDB will take care of it)
3040
+	 *
3041
+	 * @param EE_Model_Field_Base $field_obj
3042
+	 * @param array               $fields_n_values
3043
+	 * @return mixed string|int|float depending on what the table column will be expecting
3044
+	 * @throws EE_Error
3045
+	 */
3046
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3047
+	{
3048
+		//if this field doesn't allow nullable, don't allow it
3049
+		if (
3050
+			! $field_obj->is_nullable()
3051
+			&& (
3052
+				! isset($fields_n_values[$field_obj->get_name()])
3053
+				|| $fields_n_values[$field_obj->get_name()] === null
3054
+			)
3055
+		) {
3056
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3057
+		}
3058
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3059
+			? $fields_n_values[$field_obj->get_name()]
3060
+			: null;
3061
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3062
+	}
3063
+
3064
+
3065
+
3066
+	/**
3067
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3068
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3069
+	 * the field's prepare_for_set() method.
3070
+	 *
3071
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3072
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3073
+	 *                                   top of file)
3074
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3075
+	 *                                   $value is a custom selection
3076
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3077
+	 */
3078
+	private function _prepare_value_for_use_in_db($value, $field)
3079
+	{
3080
+		if ($field && $field instanceof EE_Model_Field_Base) {
3081
+			switch ($this->_values_already_prepared_by_model_object) {
3082
+				/** @noinspection PhpMissingBreakStatementInspection */
3083
+				case self::not_prepared_by_model_object:
3084
+					$value = $field->prepare_for_set($value);
3085
+				//purposefully left out "return"
3086
+				case self::prepared_by_model_object:
3087
+					/** @noinspection SuspiciousAssignmentsInspection */
3088
+					$value = $field->prepare_for_use_in_db($value);
3089
+				case self::prepared_for_use_in_db:
3090
+					//leave the value alone
3091
+			}
3092
+			return $value;
3093
+		}
3094
+		return $value;
3095
+	}
3096
+
3097
+
3098
+
3099
+	/**
3100
+	 * Returns the main table on this model
3101
+	 *
3102
+	 * @return EE_Primary_Table
3103
+	 * @throws EE_Error
3104
+	 */
3105
+	protected function _get_main_table()
3106
+	{
3107
+		foreach ($this->_tables as $table) {
3108
+			if ($table instanceof EE_Primary_Table) {
3109
+				return $table;
3110
+			}
3111
+		}
3112
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3113
+			'event_espresso'), get_class($this)));
3114
+	}
3115
+
3116
+
3117
+
3118
+	/**
3119
+	 * table
3120
+	 * returns EE_Primary_Table table name
3121
+	 *
3122
+	 * @return string
3123
+	 * @throws EE_Error
3124
+	 */
3125
+	public function table()
3126
+	{
3127
+		return $this->_get_main_table()->get_table_name();
3128
+	}
3129
+
3130
+
3131
+
3132
+	/**
3133
+	 * table
3134
+	 * returns first EE_Secondary_Table table name
3135
+	 *
3136
+	 * @return string
3137
+	 */
3138
+	public function second_table()
3139
+	{
3140
+		// grab second table from tables array
3141
+		$second_table = end($this->_tables);
3142
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3143
+	}
3144
+
3145
+
3146
+
3147
+	/**
3148
+	 * get_table_obj_by_alias
3149
+	 * returns table name given it's alias
3150
+	 *
3151
+	 * @param string $table_alias
3152
+	 * @return EE_Primary_Table | EE_Secondary_Table
3153
+	 */
3154
+	public function get_table_obj_by_alias($table_alias = '')
3155
+	{
3156
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3157
+	}
3158
+
3159
+
3160
+
3161
+	/**
3162
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3163
+	 *
3164
+	 * @return EE_Secondary_Table[]
3165
+	 */
3166
+	protected function _get_other_tables()
3167
+	{
3168
+		$other_tables = array();
3169
+		foreach ($this->_tables as $table_alias => $table) {
3170
+			if ($table instanceof EE_Secondary_Table) {
3171
+				$other_tables[$table_alias] = $table;
3172
+			}
3173
+		}
3174
+		return $other_tables;
3175
+	}
3176
+
3177
+
3178
+
3179
+	/**
3180
+	 * Finds all the fields that correspond to the given table
3181
+	 *
3182
+	 * @param string $table_alias , array key in EEM_Base::_tables
3183
+	 * @return EE_Model_Field_Base[]
3184
+	 */
3185
+	public function _get_fields_for_table($table_alias)
3186
+	{
3187
+		return $this->_fields[$table_alias];
3188
+	}
3189
+
3190
+
3191
+
3192
+	/**
3193
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3194
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3195
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3196
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3197
+	 * related Registration, Transaction, and Payment models.
3198
+	 *
3199
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3200
+	 * @return EE_Model_Query_Info_Carrier
3201
+	 * @throws EE_Error
3202
+	 */
3203
+	public function _extract_related_models_from_query($query_params)
3204
+	{
3205
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3206
+		if (array_key_exists(0, $query_params)) {
3207
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3208
+		}
3209
+		if (array_key_exists('group_by', $query_params)) {
3210
+			if (is_array($query_params['group_by'])) {
3211
+				$this->_extract_related_models_from_sub_params_array_values(
3212
+					$query_params['group_by'],
3213
+					$query_info_carrier,
3214
+					'group_by'
3215
+				);
3216
+			} elseif (! empty ($query_params['group_by'])) {
3217
+				$this->_extract_related_model_info_from_query_param(
3218
+					$query_params['group_by'],
3219
+					$query_info_carrier,
3220
+					'group_by'
3221
+				);
3222
+			}
3223
+		}
3224
+		if (array_key_exists('having', $query_params)) {
3225
+			$this->_extract_related_models_from_sub_params_array_keys(
3226
+				$query_params[0],
3227
+				$query_info_carrier,
3228
+				'having'
3229
+			);
3230
+		}
3231
+		if (array_key_exists('order_by', $query_params)) {
3232
+			if (is_array($query_params['order_by'])) {
3233
+				$this->_extract_related_models_from_sub_params_array_keys(
3234
+					$query_params['order_by'],
3235
+					$query_info_carrier,
3236
+					'order_by'
3237
+				);
3238
+			} elseif (! empty($query_params['order_by'])) {
3239
+				$this->_extract_related_model_info_from_query_param(
3240
+					$query_params['order_by'],
3241
+					$query_info_carrier,
3242
+					'order_by'
3243
+				);
3244
+			}
3245
+		}
3246
+		if (array_key_exists('force_join', $query_params)) {
3247
+			$this->_extract_related_models_from_sub_params_array_values(
3248
+				$query_params['force_join'],
3249
+				$query_info_carrier,
3250
+				'force_join'
3251
+			);
3252
+		}
3253
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3254
+		return $query_info_carrier;
3255
+	}
3256
+
3257
+
3258
+
3259
+	/**
3260
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3261
+	 *
3262
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3263
+	 *                                                      $query_params['having']
3264
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3265
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3266
+	 * @throws EE_Error
3267
+	 * @return \EE_Model_Query_Info_Carrier
3268
+	 */
3269
+	private function _extract_related_models_from_sub_params_array_keys(
3270
+		$sub_query_params,
3271
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3272
+		$query_param_type
3273
+	) {
3274
+		if (! empty($sub_query_params)) {
3275
+			$sub_query_params = (array)$sub_query_params;
3276
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3277
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3278
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3279
+					$query_param_type);
3280
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3281
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3282
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3283
+				//of array('Registration.TXN_ID'=>23)
3284
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3285
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3286
+					if (! is_array($possibly_array_of_params)) {
3287
+						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'))",
3288
+							"event_espresso"),
3289
+							$param, $possibly_array_of_params));
3290
+					}
3291
+					$this->_extract_related_models_from_sub_params_array_keys(
3292
+						$possibly_array_of_params,
3293
+						$model_query_info_carrier, $query_param_type
3294
+					);
3295
+				} elseif ($query_param_type === 0 //ie WHERE
3296
+						  && is_array($possibly_array_of_params)
3297
+						  && isset($possibly_array_of_params[2])
3298
+						  && $possibly_array_of_params[2] == true
3299
+				) {
3300
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3301
+					//indicating that $possible_array_of_params[1] is actually a field name,
3302
+					//from which we should extract query parameters!
3303
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3304
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3305
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3306
+					}
3307
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3308
+						$model_query_info_carrier, $query_param_type);
3309
+				}
3310
+			}
3311
+		}
3312
+		return $model_query_info_carrier;
3313
+	}
3314
+
3315
+
3316
+
3317
+	/**
3318
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3319
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3320
+	 *
3321
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3322
+	 *                                                      $query_params['having']
3323
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3324
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3325
+	 * @throws EE_Error
3326
+	 * @return \EE_Model_Query_Info_Carrier
3327
+	 */
3328
+	private function _extract_related_models_from_sub_params_array_values(
3329
+		$sub_query_params,
3330
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3331
+		$query_param_type
3332
+	) {
3333
+		if (! empty($sub_query_params)) {
3334
+			if (! is_array($sub_query_params)) {
3335
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3336
+					$sub_query_params));
3337
+			}
3338
+			foreach ($sub_query_params as $param) {
3339
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3340
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3341
+					$query_param_type);
3342
+			}
3343
+		}
3344
+		return $model_query_info_carrier;
3345
+	}
3346
+
3347
+
3348
+
3349
+	/**
3350
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3351
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3352
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3353
+	 * but use them in a different order. Eg, we need to know what models we are querying
3354
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3355
+	 * other models before we can finalize the where clause SQL.
3356
+	 *
3357
+	 * @param array $query_params
3358
+	 * @throws EE_Error
3359
+	 * @return EE_Model_Query_Info_Carrier
3360
+	 */
3361
+	public function _create_model_query_info_carrier($query_params)
3362
+	{
3363
+		if (! is_array($query_params)) {
3364
+			EE_Error::doing_it_wrong(
3365
+				'EEM_Base::_create_model_query_info_carrier',
3366
+				sprintf(
3367
+					__(
3368
+						'$query_params should be an array, you passed a variable of type %s',
3369
+						'event_espresso'
3370
+					),
3371
+					gettype($query_params)
3372
+				),
3373
+				'4.6.0'
3374
+			);
3375
+			$query_params = array();
3376
+		}
3377
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3378
+		//first check if we should alter the query to account for caps or not
3379
+		//because the caps might require us to do extra joins
3380
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3381
+			$query_params[0] = $where_query_params = array_replace_recursive(
3382
+				$where_query_params,
3383
+				$this->caps_where_conditions(
3384
+					$query_params['caps']
3385
+				)
3386
+			);
3387
+		}
3388
+		$query_object = $this->_extract_related_models_from_query($query_params);
3389
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3390
+		foreach ($where_query_params as $key => $value) {
3391
+			if (is_int($key)) {
3392
+				throw new EE_Error(
3393
+					sprintf(
3394
+						__(
3395
+							"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.",
3396
+							"event_espresso"
3397
+						),
3398
+						$key,
3399
+						var_export($value, true),
3400
+						var_export($query_params, true),
3401
+						get_class($this)
3402
+					)
3403
+				);
3404
+			}
3405
+		}
3406
+		if (
3407
+			array_key_exists('default_where_conditions', $query_params)
3408
+			&& ! empty($query_params['default_where_conditions'])
3409
+		) {
3410
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3411
+		} else {
3412
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3413
+		}
3414
+		$where_query_params = array_merge(
3415
+			$this->_get_default_where_conditions_for_models_in_query(
3416
+				$query_object,
3417
+				$use_default_where_conditions,
3418
+				$where_query_params
3419
+			),
3420
+			$where_query_params
3421
+		);
3422
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3423
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3424
+		// So we need to setup a subquery and use that for the main join.
3425
+		// Note for now this only works on the primary table for the model.
3426
+		// So for instance, you could set the limit array like this:
3427
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3428
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3429
+			$query_object->set_main_model_join_sql(
3430
+				$this->_construct_limit_join_select(
3431
+					$query_params['on_join_limit'][0],
3432
+					$query_params['on_join_limit'][1]
3433
+				)
3434
+			);
3435
+		}
3436
+		//set limit
3437
+		if (array_key_exists('limit', $query_params)) {
3438
+			if (is_array($query_params['limit'])) {
3439
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3440
+					$e = sprintf(
3441
+						__(
3442
+							"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)",
3443
+							"event_espresso"
3444
+						),
3445
+						http_build_query($query_params['limit'])
3446
+					);
3447
+					throw new EE_Error($e . "|" . $e);
3448
+				}
3449
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3450
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3451
+			} elseif (! empty ($query_params['limit'])) {
3452
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3453
+			}
3454
+		}
3455
+		//set order by
3456
+		if (array_key_exists('order_by', $query_params)) {
3457
+			if (is_array($query_params['order_by'])) {
3458
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3459
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3460
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3461
+				if (array_key_exists('order', $query_params)) {
3462
+					throw new EE_Error(
3463
+						sprintf(
3464
+							__(
3465
+								"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 ",
3466
+								"event_espresso"
3467
+							),
3468
+							get_class($this),
3469
+							implode(", ", array_keys($query_params['order_by'])),
3470
+							implode(", ", $query_params['order_by']),
3471
+							$query_params['order']
3472
+						)
3473
+					);
3474
+				}
3475
+				$this->_extract_related_models_from_sub_params_array_keys(
3476
+					$query_params['order_by'],
3477
+					$query_object,
3478
+					'order_by'
3479
+				);
3480
+				//assume it's an array of fields to order by
3481
+				$order_array = array();
3482
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3483
+					$order = $this->_extract_order($order);
3484
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3485
+				}
3486
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3487
+			} elseif (! empty ($query_params['order_by'])) {
3488
+				$this->_extract_related_model_info_from_query_param(
3489
+					$query_params['order_by'],
3490
+					$query_object,
3491
+					'order',
3492
+					$query_params['order_by']
3493
+				);
3494
+				$order = isset($query_params['order'])
3495
+					? $this->_extract_order($query_params['order'])
3496
+					: 'DESC';
3497
+				$query_object->set_order_by_sql(
3498
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3499
+				);
3500
+			}
3501
+		}
3502
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3503
+		if (! array_key_exists('order_by', $query_params)
3504
+			&& array_key_exists('order', $query_params)
3505
+			&& ! empty($query_params['order'])
3506
+		) {
3507
+			$pk_field = $this->get_primary_key_field();
3508
+			$order = $this->_extract_order($query_params['order']);
3509
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3510
+		}
3511
+		//set group by
3512
+		if (array_key_exists('group_by', $query_params)) {
3513
+			if (is_array($query_params['group_by'])) {
3514
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3515
+				$group_by_array = array();
3516
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3517
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3518
+				}
3519
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3520
+			} elseif (! empty ($query_params['group_by'])) {
3521
+				$query_object->set_group_by_sql(
3522
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3523
+				);
3524
+			}
3525
+		}
3526
+		//set having
3527
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3528
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3529
+		}
3530
+		//now, just verify they didn't pass anything wack
3531
+		foreach ($query_params as $query_key => $query_value) {
3532
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3533
+				throw new EE_Error(
3534
+					sprintf(
3535
+						__(
3536
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3537
+							'event_espresso'
3538
+						),
3539
+						$query_key,
3540
+						get_class($this),
3541
+						//						print_r( $this->_allowed_query_params, TRUE )
3542
+						implode(',', $this->_allowed_query_params)
3543
+					)
3544
+				);
3545
+			}
3546
+		}
3547
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3548
+		if (empty($main_model_join_sql)) {
3549
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3550
+		}
3551
+		return $query_object;
3552
+	}
3553
+
3554
+
3555
+
3556
+	/**
3557
+	 * Gets the where conditions that should be imposed on the query based on the
3558
+	 * context (eg reading frontend, backend, edit or delete).
3559
+	 *
3560
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3561
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3562
+	 * @throws EE_Error
3563
+	 */
3564
+	public function caps_where_conditions($context = self::caps_read)
3565
+	{
3566
+		EEM_Base::verify_is_valid_cap_context($context);
3567
+		$cap_where_conditions = array();
3568
+		$cap_restrictions = $this->caps_missing($context);
3569
+		/**
3570
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3571
+		 */
3572
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3573
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3574
+				$restriction_if_no_cap->get_default_where_conditions());
3575
+		}
3576
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3577
+			$cap_restrictions);
3578
+	}
3579
+
3580
+
3581
+
3582
+	/**
3583
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3584
+	 * otherwise throws an exception
3585
+	 *
3586
+	 * @param string $should_be_order_string
3587
+	 * @return string either ASC, asc, DESC or desc
3588
+	 * @throws EE_Error
3589
+	 */
3590
+	private function _extract_order($should_be_order_string)
3591
+	{
3592
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3593
+			return $should_be_order_string;
3594
+		}
3595
+		throw new EE_Error(
3596
+			sprintf(
3597
+				__(
3598
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3599
+					"event_espresso"
3600
+				), get_class($this), $should_be_order_string
3601
+			)
3602
+		);
3603
+	}
3604
+
3605
+
3606
+
3607
+	/**
3608
+	 * Looks at all the models which are included in this query, and asks each
3609
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3610
+	 * so they can be merged
3611
+	 *
3612
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3613
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3614
+	 *                                                                  'none' means NO default where conditions will
3615
+	 *                                                                  be used AT ALL during this query.
3616
+	 *                                                                  'other_models_only' means default where
3617
+	 *                                                                  conditions from other models will be used, but
3618
+	 *                                                                  not for this primary model. 'all', the default,
3619
+	 *                                                                  means default where conditions will apply as
3620
+	 *                                                                  normal
3621
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3622
+	 * @throws EE_Error
3623
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3624
+	 */
3625
+	private function _get_default_where_conditions_for_models_in_query(
3626
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3627
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3628
+		$where_query_params = array()
3629
+	) {
3630
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3631
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3632
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3633
+				"event_espresso"), $use_default_where_conditions,
3634
+				implode(", ", $allowed_used_default_where_conditions_values)));
3635
+		}
3636
+		$universal_query_params = array();
3637
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3638
+			$universal_query_params = $this->_get_default_where_conditions();
3639
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3640
+			$universal_query_params = $this->_get_minimum_where_conditions();
3641
+		}
3642
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3643
+			$related_model = $this->get_related_model_obj($model_name);
3644
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3645
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3646
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3647
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3648
+			} else {
3649
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3650
+				continue;
3651
+			}
3652
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3653
+				$related_model_universal_where_params,
3654
+				$where_query_params,
3655
+				$related_model,
3656
+				$model_relation_path
3657
+			);
3658
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3659
+				$universal_query_params,
3660
+				$overrides
3661
+			);
3662
+		}
3663
+		return $universal_query_params;
3664
+	}
3665
+
3666
+
3667
+
3668
+	/**
3669
+	 * Determines whether or not we should use default where conditions for the model in question
3670
+	 * (this model, or other related models).
3671
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3672
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3673
+	 * We should use default where conditions on related models when they requested to use default where conditions
3674
+	 * on all models, or specifically just on other related models
3675
+	 * @param      $default_where_conditions_value
3676
+	 * @param bool $for_this_model false means this is for OTHER related models
3677
+	 * @return bool
3678
+	 */
3679
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3680
+	{
3681
+		return (
3682
+				   $for_this_model
3683
+				   && in_array(
3684
+					   $default_where_conditions_value,
3685
+					   array(
3686
+						   EEM_Base::default_where_conditions_all,
3687
+						   EEM_Base::default_where_conditions_this_only,
3688
+						   EEM_Base::default_where_conditions_minimum_others,
3689
+					   ),
3690
+					   true
3691
+				   )
3692
+			   )
3693
+			   || (
3694
+				   ! $for_this_model
3695
+				   && in_array(
3696
+					   $default_where_conditions_value,
3697
+					   array(
3698
+						   EEM_Base::default_where_conditions_all,
3699
+						   EEM_Base::default_where_conditions_others_only,
3700
+					   ),
3701
+					   true
3702
+				   )
3703
+			   );
3704
+	}
3705
+
3706
+	/**
3707
+	 * Determines whether or not we should use default minimum conditions for the model in question
3708
+	 * (this model, or other related models).
3709
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3710
+	 * where conditions.
3711
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3712
+	 * on this model or others
3713
+	 * @param      $default_where_conditions_value
3714
+	 * @param bool $for_this_model false means this is for OTHER related models
3715
+	 * @return bool
3716
+	 */
3717
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3718
+	{
3719
+		return (
3720
+				   $for_this_model
3721
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3722
+			   )
3723
+			   || (
3724
+				   ! $for_this_model
3725
+				   && in_array(
3726
+					   $default_where_conditions_value,
3727
+					   array(
3728
+						   EEM_Base::default_where_conditions_minimum_others,
3729
+						   EEM_Base::default_where_conditions_minimum_all,
3730
+					   ),
3731
+					   true
3732
+				   )
3733
+			   );
3734
+	}
3735
+
3736
+
3737
+	/**
3738
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3739
+	 * then we also add a special where condition which allows for that model's primary key
3740
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3741
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3742
+	 *
3743
+	 * @param array    $default_where_conditions
3744
+	 * @param array    $provided_where_conditions
3745
+	 * @param EEM_Base $model
3746
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3747
+	 * @return array like EEM_Base::get_all's $query_params[0]
3748
+	 * @throws EE_Error
3749
+	 */
3750
+	private function _override_defaults_or_make_null_friendly(
3751
+		$default_where_conditions,
3752
+		$provided_where_conditions,
3753
+		$model,
3754
+		$model_relation_path
3755
+	) {
3756
+		$null_friendly_where_conditions = array();
3757
+		$none_overridden = true;
3758
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3759
+		foreach ($default_where_conditions as $key => $val) {
3760
+			if (isset($provided_where_conditions[$key])) {
3761
+				$none_overridden = false;
3762
+			} else {
3763
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3764
+			}
3765
+		}
3766
+		if ($none_overridden && $default_where_conditions) {
3767
+			if ($model->has_primary_key_field()) {
3768
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3769
+																				. "."
3770
+																				. $model->primary_key_name()] = array('IS NULL');
3771
+			}/*else{
3772 3772
 				//@todo NO PK, use other defaults
3773 3773
 			}*/
3774
-        }
3775
-        return $null_friendly_where_conditions;
3776
-    }
3777
-
3778
-
3779
-
3780
-    /**
3781
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3782
-     * default where conditions on all get_all, update, and delete queries done by this model.
3783
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3784
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3785
-     *
3786
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3787
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3788
-     */
3789
-    private function _get_default_where_conditions($model_relation_path = null)
3790
-    {
3791
-        if ($this->_ignore_where_strategy) {
3792
-            return array();
3793
-        }
3794
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3795
-    }
3796
-
3797
-
3798
-
3799
-    /**
3800
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3801
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3802
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3803
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3804
-     * Similar to _get_default_where_conditions
3805
-     *
3806
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3807
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3808
-     */
3809
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3810
-    {
3811
-        if ($this->_ignore_where_strategy) {
3812
-            return array();
3813
-        }
3814
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3815
-    }
3816
-
3817
-
3818
-
3819
-    /**
3820
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3821
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3822
-     *
3823
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3824
-     * @return string
3825
-     * @throws EE_Error
3826
-     */
3827
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3828
-    {
3829
-        $selects = $this->_get_columns_to_select_for_this_model();
3830
-        foreach (
3831
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3832
-            $name_of_other_model_included
3833
-        ) {
3834
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3835
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3836
-            foreach ($other_model_selects as $key => $value) {
3837
-                $selects[] = $value;
3838
-            }
3839
-        }
3840
-        return implode(", ", $selects);
3841
-    }
3842
-
3843
-
3844
-
3845
-    /**
3846
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3847
-     * So that's going to be the columns for all the fields on the model
3848
-     *
3849
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3850
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3851
-     */
3852
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3853
-    {
3854
-        $fields = $this->field_settings();
3855
-        $selects = array();
3856
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3857
-            $this->get_this_model_name());
3858
-        foreach ($fields as $field_obj) {
3859
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3860
-                         . $field_obj->get_table_alias()
3861
-                         . "."
3862
-                         . $field_obj->get_table_column()
3863
-                         . " AS '"
3864
-                         . $table_alias_with_model_relation_chain_prefix
3865
-                         . $field_obj->get_table_alias()
3866
-                         . "."
3867
-                         . $field_obj->get_table_column()
3868
-                         . "'";
3869
-        }
3870
-        //make sure we are also getting the PKs of each table
3871
-        $tables = $this->get_tables();
3872
-        if (count($tables) > 1) {
3873
-            foreach ($tables as $table_obj) {
3874
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3875
-                                       . $table_obj->get_fully_qualified_pk_column();
3876
-                if (! in_array($qualified_pk_column, $selects)) {
3877
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3878
-                }
3879
-            }
3880
-        }
3881
-        return $selects;
3882
-    }
3883
-
3884
-
3885
-
3886
-    /**
3887
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3888
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3889
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3890
-     * SQL for joining, and the data types
3891
-     *
3892
-     * @param null|string                 $original_query_param
3893
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3894
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3895
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3896
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3897
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3898
-     *                                                          or 'Registration's
3899
-     * @param string                      $original_query_param what it originally was (eg
3900
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3901
-     *                                                          matches $query_param
3902
-     * @throws EE_Error
3903
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3904
-     */
3905
-    private function _extract_related_model_info_from_query_param(
3906
-        $query_param,
3907
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3908
-        $query_param_type,
3909
-        $original_query_param = null
3910
-    ) {
3911
-        if ($original_query_param === null) {
3912
-            $original_query_param = $query_param;
3913
-        }
3914
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3915
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3916
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3917
-        $allow_fields = in_array(
3918
-            $query_param_type,
3919
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3920
-            true
3921
-        );
3922
-        //check to see if we have a field on this model
3923
-        $this_model_fields = $this->field_settings(true);
3924
-        if (array_key_exists($query_param, $this_model_fields)) {
3925
-            if ($allow_fields) {
3926
-                return;
3927
-            }
3928
-            throw new EE_Error(
3929
-                sprintf(
3930
-                    __(
3931
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3932
-                        "event_espresso"
3933
-                    ),
3934
-                    $query_param, get_class($this), $query_param_type, $original_query_param
3935
-                )
3936
-            );
3937
-        }
3938
-        //check if this is a special logic query param
3939
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3940
-            if ($allow_logic_query_params) {
3941
-                return;
3942
-            }
3943
-            throw new EE_Error(
3944
-                sprintf(
3945
-                    __(
3946
-                        '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',
3947
-                        'event_espresso'
3948
-                    ),
3949
-                    implode('", "', $this->_logic_query_param_keys),
3950
-                    $query_param,
3951
-                    get_class($this),
3952
-                    '<br />',
3953
-                    "\t"
3954
-                    . ' $passed_in_query_info = <pre>'
3955
-                    . print_r($passed_in_query_info, true)
3956
-                    . '</pre>'
3957
-                    . "\n\t"
3958
-                    . ' $query_param_type = '
3959
-                    . $query_param_type
3960
-                    . "\n\t"
3961
-                    . ' $original_query_param = '
3962
-                    . $original_query_param
3963
-                )
3964
-            );
3965
-        }
3966
-        //check if it's a custom selection
3967
-        if ($this->_custom_selections instanceof CustomSelects
3968
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
3969
-        ) {
3970
-            return;
3971
-        }
3972
-        //check if has a model name at the beginning
3973
-        //and
3974
-        //check if it's a field on a related model
3975
-        if ($this->extractJoinModelFromQueryParams(
3976
-            $passed_in_query_info,
3977
-            $query_param,
3978
-            $original_query_param,
3979
-            $query_param_type
3980
-        )) {
3981
-            return;
3982
-        }
3983
-
3984
-        //ok so $query_param didn't start with a model name
3985
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3986
-        //it's wack, that's what it is
3987
-        throw new EE_Error(
3988
-            sprintf(
3989
-                esc_html__(
3990
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3991
-                    "event_espresso"
3992
-                ),
3993
-                $query_param,
3994
-                get_class($this),
3995
-                $query_param_type,
3996
-                $original_query_param
3997
-            )
3998
-        );
3999
-    }
4000
-
4001
-
4002
-    /**
4003
-     * Extracts any possible join model information from the provided possible_join_string.
4004
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4005
-     * parts that should be added to the query.
4006
-     *
4007
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4008
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4009
-     * @param null|string                 $original_query_param
4010
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4011
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4012
-     * @return bool  returns true if a join was added and false if not.
4013
-     * @throws EE_Error
4014
-     */
4015
-    private function extractJoinModelFromQueryParams(
4016
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4017
-        $possible_join_string,
4018
-        $original_query_param,
4019
-        $query_parameter_type
4020
-    ) {
4021
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4022
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4023
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4024
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4025
-                if ($possible_join_string === '') {
4026
-                    //nothing left to $query_param
4027
-                    //we should actually end in a field name, not a model like this!
4028
-                    throw new EE_Error(
4029
-                        sprintf(
4030
-                            esc_html__(
4031
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4032
-                                "event_espresso"
4033
-                            ),
4034
-                            $possible_join_string,
4035
-                            $query_parameter_type,
4036
-                            get_class($this),
4037
-                            $valid_related_model_name
4038
-                        )
4039
-                    );
4040
-                }
4041
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4042
-                $related_model_obj->_extract_related_model_info_from_query_param(
4043
-                    $possible_join_string,
4044
-                    $query_info_carrier,
4045
-                    $query_parameter_type,
4046
-                    $original_query_param
4047
-                );
4048
-                return true;
4049
-            }
4050
-            if ($possible_join_string === $valid_related_model_name) {
4051
-                $this->_add_join_to_model(
4052
-                    $valid_related_model_name,
4053
-                    $query_info_carrier,
4054
-                    $original_query_param
4055
-                );
4056
-                return true;
4057
-            }
4058
-        }
4059
-        return false;
4060
-    }
4061
-
4062
-
4063
-    /**
4064
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4065
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4066
-     * @throws EE_Error
4067
-     */
4068
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4069
-    {
4070
-        if ($this->_custom_selections instanceof CustomSelects
4071
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4072
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4073
-            )
4074
-        ) {
4075
-            $original_selects = $this->_custom_selections->originalSelects();
4076
-            foreach ($original_selects as $alias => $select_configuration) {
4077
-                $this->extractJoinModelFromQueryParams(
4078
-                    $query_info_carrier,
4079
-                    $select_configuration[0],
4080
-                    $select_configuration[0],
4081
-                    'custom_selects'
4082
-                );
4083
-            }
4084
-        }
4085
-    }
4086
-
4087
-
4088
-
4089
-    /**
4090
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4091
-     * and store it on $passed_in_query_info
4092
-     *
4093
-     * @param string                      $model_name
4094
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4095
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4096
-     *                                                          model and $model_name. Eg, if we are querying Event,
4097
-     *                                                          and are adding a join to 'Payment' with the original
4098
-     *                                                          query param key
4099
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4100
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4101
-     *                                                          Payment wants to add default query params so that it
4102
-     *                                                          will know what models to prepend onto its default query
4103
-     *                                                          params or in case it wants to rename tables (in case
4104
-     *                                                          there are multiple joins to the same table)
4105
-     * @return void
4106
-     * @throws EE_Error
4107
-     */
4108
-    private function _add_join_to_model(
4109
-        $model_name,
4110
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4111
-        $original_query_param
4112
-    ) {
4113
-        $relation_obj = $this->related_settings_for($model_name);
4114
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4115
-        //check if the relation is HABTM, because then we're essentially doing two joins
4116
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
4117
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4118
-            $join_model_obj = $relation_obj->get_join_model();
4119
-            //replace the model specified with the join model for this relation chain, whi
4120
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4121
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
4122
-            $passed_in_query_info->merge(
4123
-                new EE_Model_Query_Info_Carrier(
4124
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4125
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4126
-                )
4127
-            );
4128
-        }
4129
-        //now just join to the other table pointed to by the relation object, and add its data types
4130
-        $passed_in_query_info->merge(
4131
-            new EE_Model_Query_Info_Carrier(
4132
-                array($model_relation_chain => $model_name),
4133
-                $relation_obj->get_join_statement($model_relation_chain)
4134
-            )
4135
-        );
4136
-    }
4137
-
4138
-
4139
-
4140
-    /**
4141
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4142
-     *
4143
-     * @param array $where_params like EEM_Base::get_all
4144
-     * @return string of SQL
4145
-     * @throws EE_Error
4146
-     */
4147
-    private function _construct_where_clause($where_params)
4148
-    {
4149
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4150
-        if ($SQL) {
4151
-            return " WHERE " . $SQL;
4152
-        }
4153
-        return '';
4154
-    }
4155
-
4156
-
4157
-
4158
-    /**
4159
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4160
-     * and should be passed HAVING parameters, not WHERE parameters
4161
-     *
4162
-     * @param array $having_params
4163
-     * @return string
4164
-     * @throws EE_Error
4165
-     */
4166
-    private function _construct_having_clause($having_params)
4167
-    {
4168
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4169
-        if ($SQL) {
4170
-            return " HAVING " . $SQL;
4171
-        }
4172
-        return '';
4173
-    }
4174
-
4175
-
4176
-    /**
4177
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4178
-     * Event_Meta.meta_value = 'foo'))"
4179
-     *
4180
-     * @param array  $where_params see EEM_Base::get_all for documentation
4181
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4182
-     * @throws EE_Error
4183
-     * @return string of SQL
4184
-     */
4185
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4186
-    {
4187
-        $where_clauses = array();
4188
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4189
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4190
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4191
-                switch ($query_param) {
4192
-                    case 'not':
4193
-                    case 'NOT':
4194
-                        $where_clauses[] = "! ("
4195
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4196
-                                $glue)
4197
-                                           . ")";
4198
-                        break;
4199
-                    case 'and':
4200
-                    case 'AND':
4201
-                        $where_clauses[] = " ("
4202
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4203
-                                ' AND ')
4204
-                                           . ")";
4205
-                        break;
4206
-                    case 'or':
4207
-                    case 'OR':
4208
-                        $where_clauses[] = " ("
4209
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4210
-                                ' OR ')
4211
-                                           . ")";
4212
-                        break;
4213
-                }
4214
-            } else {
4215
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4216
-                //if it's not a normal field, maybe it's a custom selection?
4217
-                if (! $field_obj) {
4218
-                    if ($this->_custom_selections instanceof CustomSelects) {
4219
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4220
-                    } else {
4221
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4222
-                            "event_espresso"), $query_param));
4223
-                    }
4224
-                }
4225
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4226
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4227
-            }
4228
-        }
4229
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4230
-    }
4231
-
4232
-
4233
-
4234
-    /**
4235
-     * Takes the input parameter and extract the table name (alias) and column name
4236
-     *
4237
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4238
-     * @throws EE_Error
4239
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4240
-     */
4241
-    private function _deduce_column_name_from_query_param($query_param)
4242
-    {
4243
-        $field = $this->_deduce_field_from_query_param($query_param);
4244
-        if ($field) {
4245
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4246
-                $query_param);
4247
-            return $table_alias_prefix . $field->get_qualified_column();
4248
-        }
4249
-        if ($this->_custom_selections instanceof CustomSelects
4250
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4251
-        ) {
4252
-            //maybe it's custom selection item?
4253
-            //if so, just use it as the "column name"
4254
-            return $query_param;
4255
-        }
4256
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4257
-            ? implode(',', $this->_custom_selections->columnAliases())
4258
-            : '';
4259
-        throw new EE_Error(
4260
-            sprintf(
4261
-                __(
4262
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4263
-                    "event_espresso"
4264
-                ), $query_param, $custom_select_aliases
4265
-            )
4266
-        );
4267
-    }
4268
-
4269
-
4270
-
4271
-    /**
4272
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4273
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4274
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4275
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4276
-     *
4277
-     * @param string $condition_query_param_key
4278
-     * @return string
4279
-     */
4280
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4281
-    {
4282
-        $pos_of_star = strpos($condition_query_param_key, '*');
4283
-        if ($pos_of_star === false) {
4284
-            return $condition_query_param_key;
4285
-        }
4286
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4287
-        return $condition_query_param_sans_star;
4288
-    }
4289
-
4290
-
4291
-
4292
-    /**
4293
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4294
-     *
4295
-     * @param                            mixed      array | string    $op_and_value
4296
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4297
-     * @throws EE_Error
4298
-     * @return string
4299
-     */
4300
-    private function _construct_op_and_value($op_and_value, $field_obj)
4301
-    {
4302
-        if (is_array($op_and_value)) {
4303
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4304
-            if (! $operator) {
4305
-                $php_array_like_string = array();
4306
-                foreach ($op_and_value as $key => $value) {
4307
-                    $php_array_like_string[] = "$key=>$value";
4308
-                }
4309
-                throw new EE_Error(
4310
-                    sprintf(
4311
-                        __(
4312
-                            "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))",
4313
-                            "event_espresso"
4314
-                        ),
4315
-                        implode(",", $php_array_like_string)
4316
-                    )
4317
-                );
4318
-            }
4319
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4320
-        } else {
4321
-            $operator = '=';
4322
-            $value = $op_and_value;
4323
-        }
4324
-        //check to see if the value is actually another field
4325
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4326
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4327
-        }
4328
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4329
-            //in this case, the value should be an array, or at least a comma-separated list
4330
-            //it will need to handle a little differently
4331
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4332
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4333
-            return $operator . SP . $cleaned_value;
4334
-        }
4335
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4336
-            //the value should be an array with count of two.
4337
-            if (count($value) !== 2) {
4338
-                throw new EE_Error(
4339
-                    sprintf(
4340
-                        __(
4341
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4342
-                            'event_espresso'
4343
-                        ),
4344
-                        "BETWEEN"
4345
-                    )
4346
-                );
4347
-            }
4348
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4349
-            return $operator . SP . $cleaned_value;
4350
-        }
4351
-        if (in_array($operator, $this->valid_null_style_operators())) {
4352
-            if ($value !== null) {
4353
-                throw new EE_Error(
4354
-                    sprintf(
4355
-                        __(
4356
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4357
-                            "event_espresso"
4358
-                        ),
4359
-                        $value,
4360
-                        $operator
4361
-                    )
4362
-                );
4363
-            }
4364
-            return $operator;
4365
-        }
4366
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4367
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4368
-            //remove other junk. So just treat it as a string.
4369
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4370
-        }
4371
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4372
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4373
-        }
4374
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4375
-            throw new EE_Error(
4376
-                sprintf(
4377
-                    __(
4378
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4379
-                        'event_espresso'
4380
-                    ),
4381
-                    $operator,
4382
-                    $operator
4383
-                )
4384
-            );
4385
-        }
4386
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4387
-            throw new EE_Error(
4388
-                sprintf(
4389
-                    __(
4390
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4391
-                        'event_espresso'
4392
-                    ),
4393
-                    $operator,
4394
-                    $operator
4395
-                )
4396
-            );
4397
-        }
4398
-        throw new EE_Error(
4399
-            sprintf(
4400
-                __(
4401
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4402
-                    "event_espresso"
4403
-                ),
4404
-                http_build_query($op_and_value)
4405
-            )
4406
-        );
4407
-    }
4408
-
4409
-
4410
-
4411
-    /**
4412
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4413
-     *
4414
-     * @param array                      $values
4415
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4416
-     *                                              '%s'
4417
-     * @return string
4418
-     * @throws EE_Error
4419
-     */
4420
-    public function _construct_between_value($values, $field_obj)
4421
-    {
4422
-        $cleaned_values = array();
4423
-        foreach ($values as $value) {
4424
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4425
-        }
4426
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4427
-    }
4428
-
4429
-
4430
-
4431
-    /**
4432
-     * Takes an array or a comma-separated list of $values and cleans them
4433
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4434
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4435
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4436
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4437
-     *
4438
-     * @param mixed                      $values    array or comma-separated string
4439
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4440
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4441
-     * @throws EE_Error
4442
-     */
4443
-    public function _construct_in_value($values, $field_obj)
4444
-    {
4445
-        //check if the value is a CSV list
4446
-        if (is_string($values)) {
4447
-            //in which case, turn it into an array
4448
-            $values = explode(",", $values);
4449
-        }
4450
-        $cleaned_values = array();
4451
-        foreach ($values as $value) {
4452
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4453
-        }
4454
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4455
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4456
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4457
-        if (empty($cleaned_values)) {
4458
-            $all_fields = $this->field_settings();
4459
-            $a_field = array_shift($all_fields);
4460
-            $main_table = $this->_get_main_table();
4461
-            $cleaned_values[] = "SELECT "
4462
-                                . $a_field->get_table_column()
4463
-                                . " FROM "
4464
-                                . $main_table->get_table_name()
4465
-                                . " WHERE FALSE";
4466
-        }
4467
-        return "(" . implode(",", $cleaned_values) . ")";
4468
-    }
4469
-
4470
-
4471
-
4472
-    /**
4473
-     * @param mixed                      $value
4474
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4475
-     * @throws EE_Error
4476
-     * @return false|null|string
4477
-     */
4478
-    private function _wpdb_prepare_using_field($value, $field_obj)
4479
-    {
4480
-        /** @type WPDB $wpdb */
4481
-        global $wpdb;
4482
-        if ($field_obj instanceof EE_Model_Field_Base) {
4483
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4484
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4485
-        } //$field_obj should really just be a data type
4486
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4487
-            throw new EE_Error(
4488
-                sprintf(
4489
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4490
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)
4491
-                )
4492
-            );
4493
-        }
4494
-        return $wpdb->prepare($field_obj, $value);
4495
-    }
4496
-
4497
-
4498
-
4499
-    /**
4500
-     * Takes the input parameter and finds the model field that it indicates.
4501
-     *
4502
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4503
-     * @throws EE_Error
4504
-     * @return EE_Model_Field_Base
4505
-     */
4506
-    protected function _deduce_field_from_query_param($query_param_name)
4507
-    {
4508
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4509
-        //which will help us find the database table and column
4510
-        $query_param_parts = explode(".", $query_param_name);
4511
-        if (empty($query_param_parts)) {
4512
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4513
-                'event_espresso'), $query_param_name));
4514
-        }
4515
-        $number_of_parts = count($query_param_parts);
4516
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4517
-        if ($number_of_parts === 1) {
4518
-            $field_name = $last_query_param_part;
4519
-            $model_obj = $this;
4520
-        } else {// $number_of_parts >= 2
4521
-            //the last part is the column name, and there are only 2parts. therefore...
4522
-            $field_name = $last_query_param_part;
4523
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4524
-        }
4525
-        try {
4526
-            return $model_obj->field_settings_for($field_name);
4527
-        } catch (EE_Error $e) {
4528
-            return null;
4529
-        }
4530
-    }
4531
-
4532
-
4533
-
4534
-    /**
4535
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4536
-     * alias and column which corresponds to it
4537
-     *
4538
-     * @param string $field_name
4539
-     * @throws EE_Error
4540
-     * @return string
4541
-     */
4542
-    public function _get_qualified_column_for_field($field_name)
4543
-    {
4544
-        $all_fields = $this->field_settings();
4545
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4546
-        if ($field) {
4547
-            return $field->get_qualified_column();
4548
-        }
4549
-        throw new EE_Error(
4550
-            sprintf(
4551
-                __(
4552
-                    "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.",
4553
-                    'event_espresso'
4554
-                ), $field_name, get_class($this)
4555
-            )
4556
-        );
4557
-    }
4558
-
4559
-
4560
-
4561
-    /**
4562
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4563
-     * Example usage:
4564
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4565
-     *      array(),
4566
-     *      ARRAY_A,
4567
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4568
-     *  );
4569
-     * is equivalent to
4570
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4571
-     * and
4572
-     *  EEM_Event::instance()->get_all_wpdb_results(
4573
-     *      array(
4574
-     *          array(
4575
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4576
-     *          ),
4577
-     *          ARRAY_A,
4578
-     *          implode(
4579
-     *              ', ',
4580
-     *              array_merge(
4581
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4582
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4583
-     *              )
4584
-     *          )
4585
-     *      )
4586
-     *  );
4587
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4588
-     *
4589
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4590
-     *                                            and the one whose fields you are selecting for example: when querying
4591
-     *                                            tickets model and selecting fields from the tickets model you would
4592
-     *                                            leave this parameter empty, because no models are needed to join
4593
-     *                                            between the queried model and the selected one. Likewise when
4594
-     *                                            querying the datetime model and selecting fields from the tickets
4595
-     *                                            model, it would also be left empty, because there is a direct
4596
-     *                                            relation from datetimes to tickets, so no model is needed to join
4597
-     *                                            them together. However, when querying from the event model and
4598
-     *                                            selecting fields from the ticket model, you should provide the string
4599
-     *                                            'Datetime', indicating that the event model must first join to the
4600
-     *                                            datetime model in order to find its relation to ticket model.
4601
-     *                                            Also, when querying from the venue model and selecting fields from
4602
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4603
-     *                                            indicating you need to join the venue model to the event model,
4604
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4605
-     *                                            This string is used to deduce the prefix that gets added onto the
4606
-     *                                            models' tables qualified columns
4607
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4608
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4609
-     *                                            qualified column names
4610
-     * @return array|string
4611
-     */
4612
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4613
-    {
4614
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4615
-        $qualified_columns = array();
4616
-        foreach ($this->field_settings() as $field_name => $field) {
4617
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4618
-        }
4619
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4620
-    }
4621
-
4622
-
4623
-
4624
-    /**
4625
-     * constructs the select use on special limit joins
4626
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4627
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4628
-     * (as that is typically where the limits would be set).
4629
-     *
4630
-     * @param  string       $table_alias The table the select is being built for
4631
-     * @param  mixed|string $limit       The limit for this select
4632
-     * @return string                The final select join element for the query.
4633
-     */
4634
-    public function _construct_limit_join_select($table_alias, $limit)
4635
-    {
4636
-        $SQL = '';
4637
-        foreach ($this->_tables as $table_obj) {
4638
-            if ($table_obj instanceof EE_Primary_Table) {
4639
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4640
-                    ? $table_obj->get_select_join_limit($limit)
4641
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4642
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4643
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4644
-                    ? $table_obj->get_select_join_limit_join($limit)
4645
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4646
-            }
4647
-        }
4648
-        return $SQL;
4649
-    }
4650
-
4651
-
4652
-
4653
-    /**
4654
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4655
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4656
-     *
4657
-     * @return string SQL
4658
-     * @throws EE_Error
4659
-     */
4660
-    public function _construct_internal_join()
4661
-    {
4662
-        $SQL = $this->_get_main_table()->get_table_sql();
4663
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4664
-        return $SQL;
4665
-    }
4666
-
4667
-
4668
-
4669
-    /**
4670
-     * Constructs the SQL for joining all the tables on this model.
4671
-     * Normally $alias should be the primary table's alias, but in cases where
4672
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4673
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4674
-     * alias, this will construct SQL like:
4675
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4676
-     * With $alias being a secondary table's alias, this will construct SQL like:
4677
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4678
-     *
4679
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4680
-     * @return string
4681
-     */
4682
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4683
-    {
4684
-        $SQL = '';
4685
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4686
-        foreach ($this->_tables as $table_obj) {
4687
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4688
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4689
-                    //so we're joining to this table, meaning the table is already in
4690
-                    //the FROM statement, BUT the primary table isn't. So we want
4691
-                    //to add the inverse join sql
4692
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4693
-                } else {
4694
-                    //just add a regular JOIN to this table from the primary table
4695
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4696
-                }
4697
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4698
-        }
4699
-        return $SQL;
4700
-    }
4701
-
4702
-
4703
-
4704
-    /**
4705
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4706
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4707
-     * their data type (eg, '%s', '%d', etc)
4708
-     *
4709
-     * @return array
4710
-     */
4711
-    public function _get_data_types()
4712
-    {
4713
-        $data_types = array();
4714
-        foreach ($this->field_settings() as $field_obj) {
4715
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4716
-            /** @var $field_obj EE_Model_Field_Base */
4717
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4718
-        }
4719
-        return $data_types;
4720
-    }
4721
-
4722
-
4723
-
4724
-    /**
4725
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4726
-     *
4727
-     * @param string $model_name
4728
-     * @throws EE_Error
4729
-     * @return EEM_Base
4730
-     */
4731
-    public function get_related_model_obj($model_name)
4732
-    {
4733
-        $model_classname = "EEM_" . $model_name;
4734
-        if (! class_exists($model_classname)) {
4735
-            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",
4736
-                'event_espresso'), $model_name, $model_classname));
4737
-        }
4738
-        return call_user_func($model_classname . "::instance");
4739
-    }
4740
-
4741
-
4742
-
4743
-    /**
4744
-     * Returns the array of EE_ModelRelations for this model.
4745
-     *
4746
-     * @return EE_Model_Relation_Base[]
4747
-     */
4748
-    public function relation_settings()
4749
-    {
4750
-        return $this->_model_relations;
4751
-    }
4752
-
4753
-
4754
-
4755
-    /**
4756
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4757
-     * because without THOSE models, this model probably doesn't have much purpose.
4758
-     * (Eg, without an event, datetimes have little purpose.)
4759
-     *
4760
-     * @return EE_Belongs_To_Relation[]
4761
-     */
4762
-    public function belongs_to_relations()
4763
-    {
4764
-        $belongs_to_relations = array();
4765
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4766
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4767
-                $belongs_to_relations[$model_name] = $relation_obj;
4768
-            }
4769
-        }
4770
-        return $belongs_to_relations;
4771
-    }
4772
-
4773
-
4774
-
4775
-    /**
4776
-     * Returns the specified EE_Model_Relation, or throws an exception
4777
-     *
4778
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4779
-     * @throws EE_Error
4780
-     * @return EE_Model_Relation_Base
4781
-     */
4782
-    public function related_settings_for($relation_name)
4783
-    {
4784
-        $relatedModels = $this->relation_settings();
4785
-        if (! array_key_exists($relation_name, $relatedModels)) {
4786
-            throw new EE_Error(
4787
-                sprintf(
4788
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4789
-                        'event_espresso'),
4790
-                    $relation_name,
4791
-                    $this->_get_class_name(),
4792
-                    implode(', ', array_keys($relatedModels))
4793
-                )
4794
-            );
4795
-        }
4796
-        return $relatedModels[$relation_name];
4797
-    }
4798
-
4799
-
4800
-
4801
-    /**
4802
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4803
-     * fields
4804
-     *
4805
-     * @param string $fieldName
4806
-     * @param boolean $include_db_only_fields
4807
-     * @throws EE_Error
4808
-     * @return EE_Model_Field_Base
4809
-     */
4810
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4811
-    {
4812
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4813
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4814
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4815
-                get_class($this)));
4816
-        }
4817
-        return $fieldSettings[$fieldName];
4818
-    }
4819
-
4820
-
4821
-
4822
-    /**
4823
-     * Checks if this field exists on this model
4824
-     *
4825
-     * @param string $fieldName a key in the model's _field_settings array
4826
-     * @return boolean
4827
-     */
4828
-    public function has_field($fieldName)
4829
-    {
4830
-        $fieldSettings = $this->field_settings(true);
4831
-        if (isset($fieldSettings[$fieldName])) {
4832
-            return true;
4833
-        }
4834
-        return false;
4835
-    }
4836
-
4837
-
4838
-
4839
-    /**
4840
-     * Returns whether or not this model has a relation to the specified model
4841
-     *
4842
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4843
-     * @return boolean
4844
-     */
4845
-    public function has_relation($relation_name)
4846
-    {
4847
-        $relations = $this->relation_settings();
4848
-        if (isset($relations[$relation_name])) {
4849
-            return true;
4850
-        }
4851
-        return false;
4852
-    }
4853
-
4854
-
4855
-
4856
-    /**
4857
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4858
-     * Eg, on EE_Answer that would be ANS_ID field object
4859
-     *
4860
-     * @param $field_obj
4861
-     * @return boolean
4862
-     */
4863
-    public function is_primary_key_field($field_obj)
4864
-    {
4865
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4866
-    }
4867
-
4868
-
4869
-
4870
-    /**
4871
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4872
-     * Eg, on EE_Answer that would be ANS_ID field object
4873
-     *
4874
-     * @return EE_Model_Field_Base
4875
-     * @throws EE_Error
4876
-     */
4877
-    public function get_primary_key_field()
4878
-    {
4879
-        if ($this->_primary_key_field === null) {
4880
-            foreach ($this->field_settings(true) as $field_obj) {
4881
-                if ($this->is_primary_key_field($field_obj)) {
4882
-                    $this->_primary_key_field = $field_obj;
4883
-                    break;
4884
-                }
4885
-            }
4886
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4887
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4888
-                    get_class($this)));
4889
-            }
4890
-        }
4891
-        return $this->_primary_key_field;
4892
-    }
4893
-
4894
-
4895
-
4896
-    /**
4897
-     * Returns whether or not not there is a primary key on this model.
4898
-     * Internally does some caching.
4899
-     *
4900
-     * @return boolean
4901
-     */
4902
-    public function has_primary_key_field()
4903
-    {
4904
-        if ($this->_has_primary_key_field === null) {
4905
-            try {
4906
-                $this->get_primary_key_field();
4907
-                $this->_has_primary_key_field = true;
4908
-            } catch (EE_Error $e) {
4909
-                $this->_has_primary_key_field = false;
4910
-            }
4911
-        }
4912
-        return $this->_has_primary_key_field;
4913
-    }
4914
-
4915
-
4916
-
4917
-    /**
4918
-     * Finds the first field of type $field_class_name.
4919
-     *
4920
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4921
-     *                                 EE_Foreign_Key_Field, etc
4922
-     * @return EE_Model_Field_Base or null if none is found
4923
-     */
4924
-    public function get_a_field_of_type($field_class_name)
4925
-    {
4926
-        foreach ($this->field_settings() as $field) {
4927
-            if ($field instanceof $field_class_name) {
4928
-                return $field;
4929
-            }
4930
-        }
4931
-        return null;
4932
-    }
4933
-
4934
-
4935
-
4936
-    /**
4937
-     * Gets a foreign key field pointing to model.
4938
-     *
4939
-     * @param string $model_name eg Event, Registration, not EEM_Event
4940
-     * @return EE_Foreign_Key_Field_Base
4941
-     * @throws EE_Error
4942
-     */
4943
-    public function get_foreign_key_to($model_name)
4944
-    {
4945
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4946
-            foreach ($this->field_settings() as $field) {
4947
-                if (
4948
-                    $field instanceof EE_Foreign_Key_Field_Base
4949
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4950
-                ) {
4951
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4952
-                    break;
4953
-                }
4954
-            }
4955
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4956
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4957
-                    'event_espresso'), $model_name, get_class($this)));
4958
-            }
4959
-        }
4960
-        return $this->_cache_foreign_key_to_fields[$model_name];
4961
-    }
4962
-
4963
-
4964
-
4965
-    /**
4966
-     * Gets the table name (including $wpdb->prefix) for the table alias
4967
-     *
4968
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4969
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4970
-     *                            Either one works
4971
-     * @return string
4972
-     */
4973
-    public function get_table_for_alias($table_alias)
4974
-    {
4975
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4976
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4977
-    }
4978
-
4979
-
4980
-
4981
-    /**
4982
-     * Returns a flat array of all field son this model, instead of organizing them
4983
-     * by table_alias as they are in the constructor.
4984
-     *
4985
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4986
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4987
-     */
4988
-    public function field_settings($include_db_only_fields = false)
4989
-    {
4990
-        if ($include_db_only_fields) {
4991
-            if ($this->_cached_fields === null) {
4992
-                $this->_cached_fields = array();
4993
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4994
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4995
-                        $this->_cached_fields[$field_name] = $field_obj;
4996
-                    }
4997
-                }
4998
-            }
4999
-            return $this->_cached_fields;
5000
-        }
5001
-        if ($this->_cached_fields_non_db_only === null) {
5002
-            $this->_cached_fields_non_db_only = array();
5003
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5004
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5005
-                    /** @var $field_obj EE_Model_Field_Base */
5006
-                    if (! $field_obj->is_db_only_field()) {
5007
-                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5008
-                    }
5009
-                }
5010
-            }
5011
-        }
5012
-        return $this->_cached_fields_non_db_only;
5013
-    }
5014
-
5015
-
5016
-
5017
-    /**
5018
-     *        cycle though array of attendees and create objects out of each item
5019
-     *
5020
-     * @access        private
5021
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5022
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5023
-     *                           numerically indexed)
5024
-     * @throws EE_Error
5025
-     */
5026
-    protected function _create_objects($rows = array())
5027
-    {
5028
-        $array_of_objects = array();
5029
-        if (empty($rows)) {
5030
-            return array();
5031
-        }
5032
-        $count_if_model_has_no_primary_key = 0;
5033
-        $has_primary_key = $this->has_primary_key_field();
5034
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5035
-        foreach ((array)$rows as $row) {
5036
-            if (empty($row)) {
5037
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5038
-                return array();
5039
-            }
5040
-            //check if we've already set this object in the results array,
5041
-            //in which case there's no need to process it further (again)
5042
-            if ($has_primary_key) {
5043
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5044
-                    $row,
5045
-                    $primary_key_field->get_qualified_column(),
5046
-                    $primary_key_field->get_table_column()
5047
-                );
5048
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5049
-                    continue;
5050
-                }
5051
-            }
5052
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5053
-            if (! $classInstance) {
5054
-                throw new EE_Error(
5055
-                    sprintf(
5056
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5057
-                        $this->get_this_model_name(),
5058
-                        http_build_query($row)
5059
-                    )
5060
-                );
5061
-            }
5062
-            //set the timezone on the instantiated objects
5063
-            $classInstance->set_timezone($this->_timezone);
5064
-            //make sure if there is any timezone setting present that we set the timezone for the object
5065
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5066
-            $array_of_objects[$key] = $classInstance;
5067
-            //also, for all the relations of type BelongsTo, see if we can cache
5068
-            //those related models
5069
-            //(we could do this for other relations too, but if there are conditions
5070
-            //that filtered out some fo the results, then we'd be caching an incomplete set
5071
-            //so it requires a little more thought than just caching them immediately...)
5072
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5073
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5074
-                    //check if this model's INFO is present. If so, cache it on the model
5075
-                    $other_model = $relation_obj->get_other_model();
5076
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5077
-                    //if we managed to make a model object from the results, cache it on the main model object
5078
-                    if ($other_model_obj_maybe) {
5079
-                        //set timezone on these other model objects if they are present
5080
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5081
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5082
-                    }
5083
-                }
5084
-            }
5085
-            //also, if this was a custom select query, let's see if there are any results for the custom select fields
5086
-            //and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5087
-            //the field in the CustomSelects object
5088
-            if ($this->_custom_selections instanceof CustomSelects) {
5089
-                $classInstance->setCustomSelectsValues(
5090
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5091
-                );
5092
-            }
5093
-        }
5094
-        return $array_of_objects;
5095
-    }
5096
-
5097
-
5098
-    /**
5099
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5100
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5101
-     *
5102
-     * @param array $db_results_row
5103
-     * @return array
5104
-     */
5105
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5106
-    {
5107
-        $results = array();
5108
-        if ($this->_custom_selections instanceof CustomSelects) {
5109
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5110
-                if (isset($db_results_row[$alias])) {
5111
-                    $results[$alias] = $this->convertValueToDataType(
5112
-                        $db_results_row[$alias],
5113
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5114
-                    );
5115
-                }
5116
-            }
5117
-        }
5118
-        return $results;
5119
-    }
5120
-
5121
-
5122
-    /**
5123
-     * This will set the value for the given alias
5124
-     * @param string $value
5125
-     * @param string $datatype (one of %d, %s, %f)
5126
-     * @return int|string|float (int for %d, string for %s, float for %f)
5127
-     */
5128
-    protected function convertValueToDataType($value, $datatype)
5129
-    {
5130
-        switch ($datatype) {
5131
-            case '%f':
5132
-                return (float) $value;
5133
-            case '%d':
5134
-                return (int) $value;
5135
-            default:
5136
-                return (string) $value;
5137
-        }
5138
-    }
5139
-
5140
-
5141
-    /**
5142
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5143
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5144
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5145
-     * object (as set in the model_field!).
5146
-     *
5147
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5148
-     */
5149
-    public function create_default_object()
5150
-    {
5151
-        $this_model_fields_and_values = array();
5152
-        //setup the row using default values;
5153
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5154
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5155
-        }
5156
-        $className = $this->_get_class_name();
5157
-        $classInstance = EE_Registry::instance()
5158
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5159
-        return $classInstance;
5160
-    }
5161
-
5162
-
5163
-
5164
-    /**
5165
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5166
-     *                             or an stdClass where each property is the name of a column,
5167
-     * @return EE_Base_Class
5168
-     * @throws EE_Error
5169
-     */
5170
-    public function instantiate_class_from_array_or_object($cols_n_values)
5171
-    {
5172
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5173
-            $cols_n_values = get_object_vars($cols_n_values);
5174
-        }
5175
-        $primary_key = null;
5176
-        //make sure the array only has keys that are fields/columns on this model
5177
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5178
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5179
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5180
-        }
5181
-        $className = $this->_get_class_name();
5182
-        //check we actually found results that we can use to build our model object
5183
-        //if not, return null
5184
-        if ($this->has_primary_key_field()) {
5185
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5186
-                return null;
5187
-            }
5188
-        } else if ($this->unique_indexes()) {
5189
-            $first_column = reset($this_model_fields_n_values);
5190
-            if (empty($first_column)) {
5191
-                return null;
5192
-            }
5193
-        }
5194
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5195
-        if ($primary_key) {
5196
-            $classInstance = $this->get_from_entity_map($primary_key);
5197
-            if (! $classInstance) {
5198
-                $classInstance = EE_Registry::instance()
5199
-                                            ->load_class($className,
5200
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
5201
-                // add this new object to the entity map
5202
-                $classInstance = $this->add_to_entity_map($classInstance);
5203
-            }
5204
-        } else {
5205
-            $classInstance = EE_Registry::instance()
5206
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5207
-                                            true, false);
5208
-        }
5209
-        return $classInstance;
5210
-    }
5211
-
5212
-
5213
-
5214
-    /**
5215
-     * Gets the model object from the  entity map if it exists
5216
-     *
5217
-     * @param int|string $id the ID of the model object
5218
-     * @return EE_Base_Class
5219
-     */
5220
-    public function get_from_entity_map($id)
5221
-    {
5222
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5223
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5224
-    }
5225
-
5226
-
5227
-
5228
-    /**
5229
-     * add_to_entity_map
5230
-     * Adds the object to the model's entity mappings
5231
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5232
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5233
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5234
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5235
-     *        then this method should be called immediately after the update query
5236
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5237
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5238
-     *
5239
-     * @param    EE_Base_Class $object
5240
-     * @throws EE_Error
5241
-     * @return \EE_Base_Class
5242
-     */
5243
-    public function add_to_entity_map(EE_Base_Class $object)
5244
-    {
5245
-        $className = $this->_get_class_name();
5246
-        if (! $object instanceof $className) {
5247
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5248
-                is_object($object) ? get_class($object) : $object, $className));
5249
-        }
5250
-        /** @var $object EE_Base_Class */
5251
-        if (! $object->ID()) {
5252
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5253
-                "event_espresso"), get_class($this)));
5254
-        }
5255
-        // double check it's not already there
5256
-        $classInstance = $this->get_from_entity_map($object->ID());
5257
-        if ($classInstance) {
5258
-            return $classInstance;
5259
-        }
5260
-        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5261
-        return $object;
5262
-    }
5263
-
5264
-
5265
-
5266
-    /**
5267
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5268
-     * if no identifier is provided, then the entire entity map is emptied
5269
-     *
5270
-     * @param int|string $id the ID of the model object
5271
-     * @return boolean
5272
-     */
5273
-    public function clear_entity_map($id = null)
5274
-    {
5275
-        if (empty($id)) {
5276
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5277
-            return true;
5278
-        }
5279
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5280
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5281
-            return true;
5282
-        }
5283
-        return false;
5284
-    }
5285
-
5286
-
5287
-
5288
-    /**
5289
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5290
-     * Given an array where keys are column (or column alias) names and values,
5291
-     * returns an array of their corresponding field names and database values
5292
-     *
5293
-     * @param array $cols_n_values
5294
-     * @return array
5295
-     */
5296
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5297
-    {
5298
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5299
-    }
5300
-
5301
-
5302
-
5303
-    /**
5304
-     * _deduce_fields_n_values_from_cols_n_values
5305
-     * Given an array where keys are column (or column alias) names and values,
5306
-     * returns an array of their corresponding field names and database values
5307
-     *
5308
-     * @param string $cols_n_values
5309
-     * @return array
5310
-     */
5311
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5312
-    {
5313
-        $this_model_fields_n_values = array();
5314
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5315
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5316
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5317
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5318
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5319
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5320
-                    if (! $field_obj->is_db_only_field()) {
5321
-                        //prepare field as if its coming from db
5322
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5323
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5324
-                    }
5325
-                }
5326
-            } else {
5327
-                //the table's rows existed. Use their values
5328
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5329
-                    if (! $field_obj->is_db_only_field()) {
5330
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5331
-                            $cols_n_values, $field_obj->get_qualified_column(),
5332
-                            $field_obj->get_table_column()
5333
-                        );
5334
-                    }
5335
-                }
5336
-            }
5337
-        }
5338
-        return $this_model_fields_n_values;
5339
-    }
5340
-
5341
-
5342
-
5343
-    /**
5344
-     * @param $cols_n_values
5345
-     * @param $qualified_column
5346
-     * @param $regular_column
5347
-     * @return null
5348
-     */
5349
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5350
-    {
5351
-        $value = null;
5352
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5353
-        //does the field on the model relate to this column retrieved from the db?
5354
-        //or is it a db-only field? (not relating to the model)
5355
-        if (isset($cols_n_values[$qualified_column])) {
5356
-            $value = $cols_n_values[$qualified_column];
5357
-        } elseif (isset($cols_n_values[$regular_column])) {
5358
-            $value = $cols_n_values[$regular_column];
5359
-        }
5360
-        return $value;
5361
-    }
5362
-
5363
-
5364
-
5365
-    /**
5366
-     * refresh_entity_map_from_db
5367
-     * Makes sure the model object in the entity map at $id assumes the values
5368
-     * of the database (opposite of EE_base_Class::save())
5369
-     *
5370
-     * @param int|string $id
5371
-     * @return EE_Base_Class
5372
-     * @throws EE_Error
5373
-     */
5374
-    public function refresh_entity_map_from_db($id)
5375
-    {
5376
-        $obj_in_map = $this->get_from_entity_map($id);
5377
-        if ($obj_in_map) {
5378
-            $wpdb_results = $this->_get_all_wpdb_results(
5379
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5380
-            );
5381
-            if ($wpdb_results && is_array($wpdb_results)) {
5382
-                $one_row = reset($wpdb_results);
5383
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5384
-                    $obj_in_map->set_from_db($field_name, $db_value);
5385
-                }
5386
-                //clear the cache of related model objects
5387
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5388
-                    $obj_in_map->clear_cache($relation_name, null, true);
5389
-                }
5390
-            }
5391
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5392
-            return $obj_in_map;
5393
-        }
5394
-        return $this->get_one_by_ID($id);
5395
-    }
5396
-
5397
-
5398
-
5399
-    /**
5400
-     * refresh_entity_map_with
5401
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5402
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5403
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5404
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5405
-     *
5406
-     * @param int|string    $id
5407
-     * @param EE_Base_Class $replacing_model_obj
5408
-     * @return \EE_Base_Class
5409
-     * @throws EE_Error
5410
-     */
5411
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5412
-    {
5413
-        $obj_in_map = $this->get_from_entity_map($id);
5414
-        if ($obj_in_map) {
5415
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5416
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5417
-                    $obj_in_map->set($field_name, $value);
5418
-                }
5419
-                //make the model object in the entity map's cache match the $replacing_model_obj
5420
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5421
-                    $obj_in_map->clear_cache($relation_name, null, true);
5422
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5423
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5424
-                    }
5425
-                }
5426
-            }
5427
-            return $obj_in_map;
5428
-        }
5429
-        $this->add_to_entity_map($replacing_model_obj);
5430
-        return $replacing_model_obj;
5431
-    }
5432
-
5433
-
5434
-
5435
-    /**
5436
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5437
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5438
-     * require_once($this->_getClassName().".class.php");
5439
-     *
5440
-     * @return string
5441
-     */
5442
-    private function _get_class_name()
5443
-    {
5444
-        return "EE_" . $this->get_this_model_name();
5445
-    }
5446
-
5447
-
5448
-
5449
-    /**
5450
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5451
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5452
-     * it would be 'Events'.
5453
-     *
5454
-     * @param int $quantity
5455
-     * @return string
5456
-     */
5457
-    public function item_name($quantity = 1)
5458
-    {
5459
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5460
-    }
5461
-
5462
-
5463
-
5464
-    /**
5465
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5466
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5467
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5468
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5469
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5470
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5471
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5472
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5473
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5474
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5475
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5476
-     *        return $previousReturnValue.$returnString;
5477
-     * }
5478
-     * require('EEM_Answer.model.php');
5479
-     * $answer=EEM_Answer::instance();
5480
-     * echo $answer->my_callback('monkeys',100);
5481
-     * //will output "you called my_callback! and passed args:monkeys,100"
5482
-     *
5483
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5484
-     * @param array  $args       array of original arguments passed to the function
5485
-     * @throws EE_Error
5486
-     * @return mixed whatever the plugin which calls add_filter decides
5487
-     */
5488
-    public function __call($methodName, $args)
5489
-    {
5490
-        $className = get_class($this);
5491
-        $tagName = "FHEE__{$className}__{$methodName}";
5492
-        if (! has_filter($tagName)) {
5493
-            throw new EE_Error(
5494
-                sprintf(
5495
-                    __('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 );',
5496
-                        'event_espresso'),
5497
-                    $methodName,
5498
-                    $className,
5499
-                    $tagName,
5500
-                    '<br />'
5501
-                )
5502
-            );
5503
-        }
5504
-        return apply_filters($tagName, null, $this, $args);
5505
-    }
5506
-
5507
-
5508
-
5509
-    /**
5510
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5511
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5512
-     *
5513
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5514
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5515
-     *                                                       the object's class name
5516
-     *                                                       or object's ID
5517
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5518
-     *                                                       exists in the database. If it does not, we add it
5519
-     * @throws EE_Error
5520
-     * @return EE_Base_Class
5521
-     */
5522
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5523
-    {
5524
-        $className = $this->_get_class_name();
5525
-        if ($base_class_obj_or_id instanceof $className) {
5526
-            $model_object = $base_class_obj_or_id;
5527
-        } else {
5528
-            $primary_key_field = $this->get_primary_key_field();
5529
-            if (
5530
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5531
-                && (
5532
-                    is_int($base_class_obj_or_id)
5533
-                    || is_string($base_class_obj_or_id)
5534
-                )
5535
-            ) {
5536
-                // assume it's an ID.
5537
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5538
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5539
-            } else if (
5540
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5541
-                && is_string($base_class_obj_or_id)
5542
-            ) {
5543
-                // assume its a string representation of the object
5544
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5545
-            } else {
5546
-                throw new EE_Error(
5547
-                    sprintf(
5548
-                        __(
5549
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5550
-                            'event_espresso'
5551
-                        ),
5552
-                        $base_class_obj_or_id,
5553
-                        $this->_get_class_name(),
5554
-                        print_r($base_class_obj_or_id, true)
5555
-                    )
5556
-                );
5557
-            }
5558
-        }
5559
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5560
-            $model_object->save();
5561
-        }
5562
-        return $model_object;
5563
-    }
5564
-
5565
-
5566
-
5567
-    /**
5568
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5569
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5570
-     * returns it ID.
5571
-     *
5572
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5573
-     * @return int|string depending on the type of this model object's ID
5574
-     * @throws EE_Error
5575
-     */
5576
-    public function ensure_is_ID($base_class_obj_or_id)
5577
-    {
5578
-        $className = $this->_get_class_name();
5579
-        if ($base_class_obj_or_id instanceof $className) {
5580
-            /** @var $base_class_obj_or_id EE_Base_Class */
5581
-            $id = $base_class_obj_or_id->ID();
5582
-        } elseif (is_int($base_class_obj_or_id)) {
5583
-            //assume it's an ID
5584
-            $id = $base_class_obj_or_id;
5585
-        } elseif (is_string($base_class_obj_or_id)) {
5586
-            //assume its a string representation of the object
5587
-            $id = $base_class_obj_or_id;
5588
-        } else {
5589
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5590
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5591
-                print_r($base_class_obj_or_id, true)));
5592
-        }
5593
-        return $id;
5594
-    }
5595
-
5596
-
5597
-
5598
-    /**
5599
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5600
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5601
-     * been sanitized and converted into the appropriate domain.
5602
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5603
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5604
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5605
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5606
-     * $EVT = EEM_Event::instance(); $old_setting =
5607
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5608
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5609
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5610
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5611
-     *
5612
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5613
-     * @return void
5614
-     */
5615
-    public function assume_values_already_prepared_by_model_object(
5616
-        $values_already_prepared = self::not_prepared_by_model_object
5617
-    ) {
5618
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5619
-    }
5620
-
5621
-
5622
-
5623
-    /**
5624
-     * Read comments for assume_values_already_prepared_by_model_object()
5625
-     *
5626
-     * @return int
5627
-     */
5628
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5629
-    {
5630
-        return $this->_values_already_prepared_by_model_object;
5631
-    }
5632
-
5633
-
5634
-
5635
-    /**
5636
-     * Gets all the indexes on this model
5637
-     *
5638
-     * @return EE_Index[]
5639
-     */
5640
-    public function indexes()
5641
-    {
5642
-        return $this->_indexes;
5643
-    }
5644
-
5645
-
5646
-
5647
-    /**
5648
-     * Gets all the Unique Indexes on this model
5649
-     *
5650
-     * @return EE_Unique_Index[]
5651
-     */
5652
-    public function unique_indexes()
5653
-    {
5654
-        $unique_indexes = array();
5655
-        foreach ($this->_indexes as $name => $index) {
5656
-            if ($index instanceof EE_Unique_Index) {
5657
-                $unique_indexes [$name] = $index;
5658
-            }
5659
-        }
5660
-        return $unique_indexes;
5661
-    }
5662
-
5663
-
5664
-
5665
-    /**
5666
-     * Gets all the fields which, when combined, make the primary key.
5667
-     * This is usually just an array with 1 element (the primary key), but in cases
5668
-     * where there is no primary key, it's a combination of fields as defined
5669
-     * on a primary index
5670
-     *
5671
-     * @return EE_Model_Field_Base[] indexed by the field's name
5672
-     * @throws EE_Error
5673
-     */
5674
-    public function get_combined_primary_key_fields()
5675
-    {
5676
-        foreach ($this->indexes() as $index) {
5677
-            if ($index instanceof EE_Primary_Key_Index) {
5678
-                return $index->fields();
5679
-            }
5680
-        }
5681
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5682
-    }
5683
-
5684
-
5685
-
5686
-    /**
5687
-     * Used to build a primary key string (when the model has no primary key),
5688
-     * which can be used a unique string to identify this model object.
5689
-     *
5690
-     * @param array $cols_n_values keys are field names, values are their values
5691
-     * @return string
5692
-     * @throws EE_Error
5693
-     */
5694
-    public function get_index_primary_key_string($cols_n_values)
5695
-    {
5696
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5697
-            $this->get_combined_primary_key_fields());
5698
-        return http_build_query($cols_n_values_for_primary_key_index);
5699
-    }
5700
-
5701
-
5702
-
5703
-    /**
5704
-     * Gets the field values from the primary key string
5705
-     *
5706
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5707
-     * @param string $index_primary_key_string
5708
-     * @return null|array
5709
-     * @throws EE_Error
5710
-     */
5711
-    public function parse_index_primary_key_string($index_primary_key_string)
5712
-    {
5713
-        $key_fields = $this->get_combined_primary_key_fields();
5714
-        //check all of them are in the $id
5715
-        $key_vals_in_combined_pk = array();
5716
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5717
-        foreach ($key_fields as $key_field_name => $field_obj) {
5718
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5719
-                return null;
5720
-            }
5721
-        }
5722
-        return $key_vals_in_combined_pk;
5723
-    }
5724
-
5725
-
5726
-
5727
-    /**
5728
-     * verifies that an array of key-value pairs for model fields has a key
5729
-     * for each field comprising the primary key index
5730
-     *
5731
-     * @param array $key_vals
5732
-     * @return boolean
5733
-     * @throws EE_Error
5734
-     */
5735
-    public function has_all_combined_primary_key_fields($key_vals)
5736
-    {
5737
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5738
-        foreach ($keys_it_should_have as $key) {
5739
-            if (! isset($key_vals[$key])) {
5740
-                return false;
5741
-            }
5742
-        }
5743
-        return true;
5744
-    }
5745
-
5746
-
5747
-
5748
-    /**
5749
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5750
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5751
-     *
5752
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5753
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5754
-     * @throws EE_Error
5755
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5756
-     *                                                              indexed)
5757
-     */
5758
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5759
-    {
5760
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5761
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5762
-        } elseif (is_array($model_object_or_attributes_array)) {
5763
-            $attributes_array = $model_object_or_attributes_array;
5764
-        } else {
5765
-            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",
5766
-                "event_espresso"), $model_object_or_attributes_array));
5767
-        }
5768
-        //even copies obviously won't have the same ID, so remove the primary key
5769
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5770
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5771
-            unset($attributes_array[$this->primary_key_name()]);
5772
-        }
5773
-        if (isset($query_params[0])) {
5774
-            $query_params[0] = array_merge($attributes_array, $query_params);
5775
-        } else {
5776
-            $query_params[0] = $attributes_array;
5777
-        }
5778
-        return $this->get_all($query_params);
5779
-    }
5780
-
5781
-
5782
-
5783
-    /**
5784
-     * Gets the first copy we find. See get_all_copies for more details
5785
-     *
5786
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5787
-     * @param array $query_params
5788
-     * @return EE_Base_Class
5789
-     * @throws EE_Error
5790
-     */
5791
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5792
-    {
5793
-        if (! is_array($query_params)) {
5794
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5795
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5796
-                    gettype($query_params)), '4.6.0');
5797
-            $query_params = array();
5798
-        }
5799
-        $query_params['limit'] = 1;
5800
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5801
-        if (is_array($copies)) {
5802
-            return array_shift($copies);
5803
-        }
5804
-        return null;
5805
-    }
5806
-
5807
-
5808
-
5809
-    /**
5810
-     * Updates the item with the specified id. Ignores default query parameters because
5811
-     * we have specified the ID, and its assumed we KNOW what we're doing
5812
-     *
5813
-     * @param array      $fields_n_values keys are field names, values are their new values
5814
-     * @param int|string $id              the value of the primary key to update
5815
-     * @return int number of rows updated
5816
-     * @throws EE_Error
5817
-     */
5818
-    public function update_by_ID($fields_n_values, $id)
5819
-    {
5820
-        $query_params = array(
5821
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5822
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5823
-        );
5824
-        return $this->update($fields_n_values, $query_params);
5825
-    }
5826
-
5827
-
5828
-
5829
-    /**
5830
-     * Changes an operator which was supplied to the models into one usable in SQL
5831
-     *
5832
-     * @param string $operator_supplied
5833
-     * @return string an operator which can be used in SQL
5834
-     * @throws EE_Error
5835
-     */
5836
-    private function _prepare_operator_for_sql($operator_supplied)
5837
-    {
5838
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5839
-            : null;
5840
-        if ($sql_operator) {
5841
-            return $sql_operator;
5842
-        }
5843
-        throw new EE_Error(
5844
-            sprintf(
5845
-                __(
5846
-                    "The operator '%s' is not in the list of valid operators: %s",
5847
-                    "event_espresso"
5848
-                ), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5849
-            )
5850
-        );
5851
-    }
5852
-
5853
-
5854
-
5855
-    /**
5856
-     * Gets the valid operators
5857
-     * @return array keys are accepted strings, values are the SQL they are converted to
5858
-     */
5859
-    public function valid_operators(){
5860
-        return $this->_valid_operators;
5861
-    }
5862
-
5863
-
5864
-
5865
-    /**
5866
-     * Gets the between-style operators (take 2 arguments).
5867
-     * @return array keys are accepted strings, values are the SQL they are converted to
5868
-     */
5869
-    public function valid_between_style_operators()
5870
-    {
5871
-        return array_intersect(
5872
-            $this->valid_operators(),
5873
-            $this->_between_style_operators
5874
-        );
5875
-    }
5876
-
5877
-    /**
5878
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5879
-     * @return array keys are accepted strings, values are the SQL they are converted to
5880
-     */
5881
-    public function valid_like_style_operators()
5882
-    {
5883
-        return array_intersect(
5884
-            $this->valid_operators(),
5885
-            $this->_like_style_operators
5886
-        );
5887
-    }
5888
-
5889
-    /**
5890
-     * Gets the "in"-style operators
5891
-     * @return array keys are accepted strings, values are the SQL they are converted to
5892
-     */
5893
-    public function valid_in_style_operators()
5894
-    {
5895
-        return array_intersect(
5896
-            $this->valid_operators(),
5897
-            $this->_in_style_operators
5898
-        );
5899
-    }
5900
-
5901
-    /**
5902
-     * Gets the "null"-style operators (accept no arguments)
5903
-     * @return array keys are accepted strings, values are the SQL they are converted to
5904
-     */
5905
-    public function valid_null_style_operators()
5906
-    {
5907
-        return array_intersect(
5908
-            $this->valid_operators(),
5909
-            $this->_null_style_operators
5910
-        );
5911
-    }
5912
-
5913
-    /**
5914
-     * Gets an array where keys are the primary keys and values are their 'names'
5915
-     * (as determined by the model object's name() function, which is often overridden)
5916
-     *
5917
-     * @param array $query_params like get_all's
5918
-     * @return string[]
5919
-     * @throws EE_Error
5920
-     */
5921
-    public function get_all_names($query_params = array())
5922
-    {
5923
-        $objs = $this->get_all($query_params);
5924
-        $names = array();
5925
-        foreach ($objs as $obj) {
5926
-            $names[$obj->ID()] = $obj->name();
5927
-        }
5928
-        return $names;
5929
-    }
5930
-
5931
-
5932
-
5933
-    /**
5934
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5935
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5936
-     * this is duplicated effort and reduces efficiency) you would be better to use
5937
-     * array_keys() on $model_objects.
5938
-     *
5939
-     * @param \EE_Base_Class[] $model_objects
5940
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5941
-     *                                               in the returned array
5942
-     * @return array
5943
-     * @throws EE_Error
5944
-     */
5945
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5946
-    {
5947
-        if (! $this->has_primary_key_field()) {
5948
-            if (WP_DEBUG) {
5949
-                EE_Error::add_error(
5950
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5951
-                    __FILE__,
5952
-                    __FUNCTION__,
5953
-                    __LINE__
5954
-                );
5955
-            }
5956
-        }
5957
-        $IDs = array();
5958
-        foreach ($model_objects as $model_object) {
5959
-            $id = $model_object->ID();
5960
-            if (! $id) {
5961
-                if ($filter_out_empty_ids) {
5962
-                    continue;
5963
-                }
5964
-                if (WP_DEBUG) {
5965
-                    EE_Error::add_error(
5966
-                        __(
5967
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5968
-                            'event_espresso'
5969
-                        ),
5970
-                        __FILE__,
5971
-                        __FUNCTION__,
5972
-                        __LINE__
5973
-                    );
5974
-                }
5975
-            }
5976
-            $IDs[] = $id;
5977
-        }
5978
-        return $IDs;
5979
-    }
5980
-
5981
-
5982
-
5983
-    /**
5984
-     * Returns the string used in capabilities relating to this model. If there
5985
-     * are no capabilities that relate to this model returns false
5986
-     *
5987
-     * @return string|false
5988
-     */
5989
-    public function cap_slug()
5990
-    {
5991
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5992
-    }
5993
-
5994
-
5995
-
5996
-    /**
5997
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5998
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5999
-     * only returns the cap restrictions array in that context (ie, the array
6000
-     * at that key)
6001
-     *
6002
-     * @param string $context
6003
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6004
-     * @throws EE_Error
6005
-     */
6006
-    public function cap_restrictions($context = EEM_Base::caps_read)
6007
-    {
6008
-        EEM_Base::verify_is_valid_cap_context($context);
6009
-        //check if we ought to run the restriction generator first
6010
-        if (
6011
-            isset($this->_cap_restriction_generators[$context])
6012
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6013
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6014
-        ) {
6015
-            $this->_cap_restrictions[$context] = array_merge(
6016
-                $this->_cap_restrictions[$context],
6017
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
6018
-            );
6019
-        }
6020
-        //and make sure we've finalized the construction of each restriction
6021
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6022
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6023
-                $where_conditions_obj->_finalize_construct($this);
6024
-            }
6025
-        }
6026
-        return $this->_cap_restrictions[$context];
6027
-    }
6028
-
6029
-
6030
-
6031
-    /**
6032
-     * Indicating whether or not this model thinks its a wp core model
6033
-     *
6034
-     * @return boolean
6035
-     */
6036
-    public function is_wp_core_model()
6037
-    {
6038
-        return $this->_wp_core_model;
6039
-    }
6040
-
6041
-
6042
-
6043
-    /**
6044
-     * Gets all the caps that are missing which impose a restriction on
6045
-     * queries made in this context
6046
-     *
6047
-     * @param string $context one of EEM_Base::caps_ constants
6048
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6049
-     * @throws EE_Error
6050
-     */
6051
-    public function caps_missing($context = EEM_Base::caps_read)
6052
-    {
6053
-        $missing_caps = array();
6054
-        $cap_restrictions = $this->cap_restrictions($context);
6055
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6056
-            if (! EE_Capabilities::instance()
6057
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6058
-            ) {
6059
-                $missing_caps[$cap] = $restriction_if_no_cap;
6060
-            }
6061
-        }
6062
-        return $missing_caps;
6063
-    }
6064
-
6065
-
6066
-
6067
-    /**
6068
-     * Gets the mapping from capability contexts to action strings used in capability names
6069
-     *
6070
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6071
-     * one of 'read', 'edit', or 'delete'
6072
-     */
6073
-    public function cap_contexts_to_cap_action_map()
6074
-    {
6075
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
6076
-            $this);
6077
-    }
6078
-
6079
-
6080
-
6081
-    /**
6082
-     * Gets the action string for the specified capability context
6083
-     *
6084
-     * @param string $context
6085
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6086
-     * @throws EE_Error
6087
-     */
6088
-    public function cap_action_for_context($context)
6089
-    {
6090
-        $mapping = $this->cap_contexts_to_cap_action_map();
6091
-        if (isset($mapping[$context])) {
6092
-            return $mapping[$context];
6093
-        }
6094
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6095
-            return $action;
6096
-        }
6097
-        throw new EE_Error(
6098
-            sprintf(
6099
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6100
-                $context,
6101
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6102
-            )
6103
-        );
6104
-    }
6105
-
6106
-
6107
-
6108
-    /**
6109
-     * Returns all the capability contexts which are valid when querying models
6110
-     *
6111
-     * @return array
6112
-     */
6113
-    public static function valid_cap_contexts()
6114
-    {
6115
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6116
-            self::caps_read,
6117
-            self::caps_read_admin,
6118
-            self::caps_edit,
6119
-            self::caps_delete,
6120
-        ));
6121
-    }
6122
-
6123
-
6124
-
6125
-    /**
6126
-     * Returns all valid options for 'default_where_conditions'
6127
-     *
6128
-     * @return array
6129
-     */
6130
-    public static function valid_default_where_conditions()
6131
-    {
6132
-        return array(
6133
-            EEM_Base::default_where_conditions_all,
6134
-            EEM_Base::default_where_conditions_this_only,
6135
-            EEM_Base::default_where_conditions_others_only,
6136
-            EEM_Base::default_where_conditions_minimum_all,
6137
-            EEM_Base::default_where_conditions_minimum_others,
6138
-            EEM_Base::default_where_conditions_none
6139
-        );
6140
-    }
6141
-
6142
-    // public static function default_where_conditions_full
6143
-    /**
6144
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6145
-     *
6146
-     * @param string $context
6147
-     * @return bool
6148
-     * @throws EE_Error
6149
-     */
6150
-    static public function verify_is_valid_cap_context($context)
6151
-    {
6152
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6153
-        if (in_array($context, $valid_cap_contexts)) {
6154
-            return true;
6155
-        }
6156
-        throw new EE_Error(
6157
-            sprintf(
6158
-                __(
6159
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6160
-                    'event_espresso'
6161
-                ),
6162
-                $context,
6163
-                'EEM_Base',
6164
-                implode(',', $valid_cap_contexts)
6165
-            )
6166
-        );
6167
-    }
6168
-
6169
-
6170
-
6171
-    /**
6172
-     * Clears all the models field caches. This is only useful when a sub-class
6173
-     * might have added a field or something and these caches might be invalidated
6174
-     */
6175
-    protected function _invalidate_field_caches()
6176
-    {
6177
-        $this->_cache_foreign_key_to_fields = array();
6178
-        $this->_cached_fields = null;
6179
-        $this->_cached_fields_non_db_only = null;
6180
-    }
6181
-
6182
-
6183
-
6184
-    /**
6185
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6186
-     * (eg "and", "or", "not").
6187
-     *
6188
-     * @return array
6189
-     */
6190
-    public function logic_query_param_keys()
6191
-    {
6192
-        return $this->_logic_query_param_keys;
6193
-    }
6194
-
6195
-
6196
-
6197
-    /**
6198
-     * Determines whether or not the where query param array key is for a logic query param.
6199
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6200
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6201
-     *
6202
-     * @param $query_param_key
6203
-     * @return bool
6204
-     */
6205
-    public function is_logic_query_param_key($query_param_key)
6206
-    {
6207
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6208
-            if ($query_param_key === $logic_query_param_key
6209
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6210
-            ) {
6211
-                return true;
6212
-            }
6213
-        }
6214
-        return false;
6215
-    }
3774
+		}
3775
+		return $null_friendly_where_conditions;
3776
+	}
3777
+
3778
+
3779
+
3780
+	/**
3781
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3782
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3783
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3784
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3785
+	 *
3786
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3787
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3788
+	 */
3789
+	private function _get_default_where_conditions($model_relation_path = null)
3790
+	{
3791
+		if ($this->_ignore_where_strategy) {
3792
+			return array();
3793
+		}
3794
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3795
+	}
3796
+
3797
+
3798
+
3799
+	/**
3800
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3801
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3802
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3803
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3804
+	 * Similar to _get_default_where_conditions
3805
+	 *
3806
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3807
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3808
+	 */
3809
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3810
+	{
3811
+		if ($this->_ignore_where_strategy) {
3812
+			return array();
3813
+		}
3814
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3815
+	}
3816
+
3817
+
3818
+
3819
+	/**
3820
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3821
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3822
+	 *
3823
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3824
+	 * @return string
3825
+	 * @throws EE_Error
3826
+	 */
3827
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3828
+	{
3829
+		$selects = $this->_get_columns_to_select_for_this_model();
3830
+		foreach (
3831
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3832
+			$name_of_other_model_included
3833
+		) {
3834
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3835
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3836
+			foreach ($other_model_selects as $key => $value) {
3837
+				$selects[] = $value;
3838
+			}
3839
+		}
3840
+		return implode(", ", $selects);
3841
+	}
3842
+
3843
+
3844
+
3845
+	/**
3846
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3847
+	 * So that's going to be the columns for all the fields on the model
3848
+	 *
3849
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3850
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3851
+	 */
3852
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3853
+	{
3854
+		$fields = $this->field_settings();
3855
+		$selects = array();
3856
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3857
+			$this->get_this_model_name());
3858
+		foreach ($fields as $field_obj) {
3859
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3860
+						 . $field_obj->get_table_alias()
3861
+						 . "."
3862
+						 . $field_obj->get_table_column()
3863
+						 . " AS '"
3864
+						 . $table_alias_with_model_relation_chain_prefix
3865
+						 . $field_obj->get_table_alias()
3866
+						 . "."
3867
+						 . $field_obj->get_table_column()
3868
+						 . "'";
3869
+		}
3870
+		//make sure we are also getting the PKs of each table
3871
+		$tables = $this->get_tables();
3872
+		if (count($tables) > 1) {
3873
+			foreach ($tables as $table_obj) {
3874
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3875
+									   . $table_obj->get_fully_qualified_pk_column();
3876
+				if (! in_array($qualified_pk_column, $selects)) {
3877
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3878
+				}
3879
+			}
3880
+		}
3881
+		return $selects;
3882
+	}
3883
+
3884
+
3885
+
3886
+	/**
3887
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3888
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3889
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3890
+	 * SQL for joining, and the data types
3891
+	 *
3892
+	 * @param null|string                 $original_query_param
3893
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3894
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3895
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3896
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3897
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3898
+	 *                                                          or 'Registration's
3899
+	 * @param string                      $original_query_param what it originally was (eg
3900
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3901
+	 *                                                          matches $query_param
3902
+	 * @throws EE_Error
3903
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3904
+	 */
3905
+	private function _extract_related_model_info_from_query_param(
3906
+		$query_param,
3907
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3908
+		$query_param_type,
3909
+		$original_query_param = null
3910
+	) {
3911
+		if ($original_query_param === null) {
3912
+			$original_query_param = $query_param;
3913
+		}
3914
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3915
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3916
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3917
+		$allow_fields = in_array(
3918
+			$query_param_type,
3919
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3920
+			true
3921
+		);
3922
+		//check to see if we have a field on this model
3923
+		$this_model_fields = $this->field_settings(true);
3924
+		if (array_key_exists($query_param, $this_model_fields)) {
3925
+			if ($allow_fields) {
3926
+				return;
3927
+			}
3928
+			throw new EE_Error(
3929
+				sprintf(
3930
+					__(
3931
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3932
+						"event_espresso"
3933
+					),
3934
+					$query_param, get_class($this), $query_param_type, $original_query_param
3935
+				)
3936
+			);
3937
+		}
3938
+		//check if this is a special logic query param
3939
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3940
+			if ($allow_logic_query_params) {
3941
+				return;
3942
+			}
3943
+			throw new EE_Error(
3944
+				sprintf(
3945
+					__(
3946
+						'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',
3947
+						'event_espresso'
3948
+					),
3949
+					implode('", "', $this->_logic_query_param_keys),
3950
+					$query_param,
3951
+					get_class($this),
3952
+					'<br />',
3953
+					"\t"
3954
+					. ' $passed_in_query_info = <pre>'
3955
+					. print_r($passed_in_query_info, true)
3956
+					. '</pre>'
3957
+					. "\n\t"
3958
+					. ' $query_param_type = '
3959
+					. $query_param_type
3960
+					. "\n\t"
3961
+					. ' $original_query_param = '
3962
+					. $original_query_param
3963
+				)
3964
+			);
3965
+		}
3966
+		//check if it's a custom selection
3967
+		if ($this->_custom_selections instanceof CustomSelects
3968
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
3969
+		) {
3970
+			return;
3971
+		}
3972
+		//check if has a model name at the beginning
3973
+		//and
3974
+		//check if it's a field on a related model
3975
+		if ($this->extractJoinModelFromQueryParams(
3976
+			$passed_in_query_info,
3977
+			$query_param,
3978
+			$original_query_param,
3979
+			$query_param_type
3980
+		)) {
3981
+			return;
3982
+		}
3983
+
3984
+		//ok so $query_param didn't start with a model name
3985
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3986
+		//it's wack, that's what it is
3987
+		throw new EE_Error(
3988
+			sprintf(
3989
+				esc_html__(
3990
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3991
+					"event_espresso"
3992
+				),
3993
+				$query_param,
3994
+				get_class($this),
3995
+				$query_param_type,
3996
+				$original_query_param
3997
+			)
3998
+		);
3999
+	}
4000
+
4001
+
4002
+	/**
4003
+	 * Extracts any possible join model information from the provided possible_join_string.
4004
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4005
+	 * parts that should be added to the query.
4006
+	 *
4007
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4008
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4009
+	 * @param null|string                 $original_query_param
4010
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4011
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4012
+	 * @return bool  returns true if a join was added and false if not.
4013
+	 * @throws EE_Error
4014
+	 */
4015
+	private function extractJoinModelFromQueryParams(
4016
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4017
+		$possible_join_string,
4018
+		$original_query_param,
4019
+		$query_parameter_type
4020
+	) {
4021
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4022
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4023
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4024
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4025
+				if ($possible_join_string === '') {
4026
+					//nothing left to $query_param
4027
+					//we should actually end in a field name, not a model like this!
4028
+					throw new EE_Error(
4029
+						sprintf(
4030
+							esc_html__(
4031
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4032
+								"event_espresso"
4033
+							),
4034
+							$possible_join_string,
4035
+							$query_parameter_type,
4036
+							get_class($this),
4037
+							$valid_related_model_name
4038
+						)
4039
+					);
4040
+				}
4041
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4042
+				$related_model_obj->_extract_related_model_info_from_query_param(
4043
+					$possible_join_string,
4044
+					$query_info_carrier,
4045
+					$query_parameter_type,
4046
+					$original_query_param
4047
+				);
4048
+				return true;
4049
+			}
4050
+			if ($possible_join_string === $valid_related_model_name) {
4051
+				$this->_add_join_to_model(
4052
+					$valid_related_model_name,
4053
+					$query_info_carrier,
4054
+					$original_query_param
4055
+				);
4056
+				return true;
4057
+			}
4058
+		}
4059
+		return false;
4060
+	}
4061
+
4062
+
4063
+	/**
4064
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4065
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4066
+	 * @throws EE_Error
4067
+	 */
4068
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4069
+	{
4070
+		if ($this->_custom_selections instanceof CustomSelects
4071
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4072
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4073
+			)
4074
+		) {
4075
+			$original_selects = $this->_custom_selections->originalSelects();
4076
+			foreach ($original_selects as $alias => $select_configuration) {
4077
+				$this->extractJoinModelFromQueryParams(
4078
+					$query_info_carrier,
4079
+					$select_configuration[0],
4080
+					$select_configuration[0],
4081
+					'custom_selects'
4082
+				);
4083
+			}
4084
+		}
4085
+	}
4086
+
4087
+
4088
+
4089
+	/**
4090
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4091
+	 * and store it on $passed_in_query_info
4092
+	 *
4093
+	 * @param string                      $model_name
4094
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4095
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4096
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4097
+	 *                                                          and are adding a join to 'Payment' with the original
4098
+	 *                                                          query param key
4099
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4100
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4101
+	 *                                                          Payment wants to add default query params so that it
4102
+	 *                                                          will know what models to prepend onto its default query
4103
+	 *                                                          params or in case it wants to rename tables (in case
4104
+	 *                                                          there are multiple joins to the same table)
4105
+	 * @return void
4106
+	 * @throws EE_Error
4107
+	 */
4108
+	private function _add_join_to_model(
4109
+		$model_name,
4110
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4111
+		$original_query_param
4112
+	) {
4113
+		$relation_obj = $this->related_settings_for($model_name);
4114
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4115
+		//check if the relation is HABTM, because then we're essentially doing two joins
4116
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
4117
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4118
+			$join_model_obj = $relation_obj->get_join_model();
4119
+			//replace the model specified with the join model for this relation chain, whi
4120
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4121
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
4122
+			$passed_in_query_info->merge(
4123
+				new EE_Model_Query_Info_Carrier(
4124
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4125
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4126
+				)
4127
+			);
4128
+		}
4129
+		//now just join to the other table pointed to by the relation object, and add its data types
4130
+		$passed_in_query_info->merge(
4131
+			new EE_Model_Query_Info_Carrier(
4132
+				array($model_relation_chain => $model_name),
4133
+				$relation_obj->get_join_statement($model_relation_chain)
4134
+			)
4135
+		);
4136
+	}
4137
+
4138
+
4139
+
4140
+	/**
4141
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4142
+	 *
4143
+	 * @param array $where_params like EEM_Base::get_all
4144
+	 * @return string of SQL
4145
+	 * @throws EE_Error
4146
+	 */
4147
+	private function _construct_where_clause($where_params)
4148
+	{
4149
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4150
+		if ($SQL) {
4151
+			return " WHERE " . $SQL;
4152
+		}
4153
+		return '';
4154
+	}
4155
+
4156
+
4157
+
4158
+	/**
4159
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4160
+	 * and should be passed HAVING parameters, not WHERE parameters
4161
+	 *
4162
+	 * @param array $having_params
4163
+	 * @return string
4164
+	 * @throws EE_Error
4165
+	 */
4166
+	private function _construct_having_clause($having_params)
4167
+	{
4168
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4169
+		if ($SQL) {
4170
+			return " HAVING " . $SQL;
4171
+		}
4172
+		return '';
4173
+	}
4174
+
4175
+
4176
+	/**
4177
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4178
+	 * Event_Meta.meta_value = 'foo'))"
4179
+	 *
4180
+	 * @param array  $where_params see EEM_Base::get_all for documentation
4181
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4182
+	 * @throws EE_Error
4183
+	 * @return string of SQL
4184
+	 */
4185
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4186
+	{
4187
+		$where_clauses = array();
4188
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4189
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4190
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4191
+				switch ($query_param) {
4192
+					case 'not':
4193
+					case 'NOT':
4194
+						$where_clauses[] = "! ("
4195
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4196
+								$glue)
4197
+										   . ")";
4198
+						break;
4199
+					case 'and':
4200
+					case 'AND':
4201
+						$where_clauses[] = " ("
4202
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4203
+								' AND ')
4204
+										   . ")";
4205
+						break;
4206
+					case 'or':
4207
+					case 'OR':
4208
+						$where_clauses[] = " ("
4209
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4210
+								' OR ')
4211
+										   . ")";
4212
+						break;
4213
+				}
4214
+			} else {
4215
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4216
+				//if it's not a normal field, maybe it's a custom selection?
4217
+				if (! $field_obj) {
4218
+					if ($this->_custom_selections instanceof CustomSelects) {
4219
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4220
+					} else {
4221
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4222
+							"event_espresso"), $query_param));
4223
+					}
4224
+				}
4225
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4226
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4227
+			}
4228
+		}
4229
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4230
+	}
4231
+
4232
+
4233
+
4234
+	/**
4235
+	 * Takes the input parameter and extract the table name (alias) and column name
4236
+	 *
4237
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4238
+	 * @throws EE_Error
4239
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4240
+	 */
4241
+	private function _deduce_column_name_from_query_param($query_param)
4242
+	{
4243
+		$field = $this->_deduce_field_from_query_param($query_param);
4244
+		if ($field) {
4245
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4246
+				$query_param);
4247
+			return $table_alias_prefix . $field->get_qualified_column();
4248
+		}
4249
+		if ($this->_custom_selections instanceof CustomSelects
4250
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4251
+		) {
4252
+			//maybe it's custom selection item?
4253
+			//if so, just use it as the "column name"
4254
+			return $query_param;
4255
+		}
4256
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4257
+			? implode(',', $this->_custom_selections->columnAliases())
4258
+			: '';
4259
+		throw new EE_Error(
4260
+			sprintf(
4261
+				__(
4262
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4263
+					"event_espresso"
4264
+				), $query_param, $custom_select_aliases
4265
+			)
4266
+		);
4267
+	}
4268
+
4269
+
4270
+
4271
+	/**
4272
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4273
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4274
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4275
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4276
+	 *
4277
+	 * @param string $condition_query_param_key
4278
+	 * @return string
4279
+	 */
4280
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4281
+	{
4282
+		$pos_of_star = strpos($condition_query_param_key, '*');
4283
+		if ($pos_of_star === false) {
4284
+			return $condition_query_param_key;
4285
+		}
4286
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4287
+		return $condition_query_param_sans_star;
4288
+	}
4289
+
4290
+
4291
+
4292
+	/**
4293
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4294
+	 *
4295
+	 * @param                            mixed      array | string    $op_and_value
4296
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4297
+	 * @throws EE_Error
4298
+	 * @return string
4299
+	 */
4300
+	private function _construct_op_and_value($op_and_value, $field_obj)
4301
+	{
4302
+		if (is_array($op_and_value)) {
4303
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4304
+			if (! $operator) {
4305
+				$php_array_like_string = array();
4306
+				foreach ($op_and_value as $key => $value) {
4307
+					$php_array_like_string[] = "$key=>$value";
4308
+				}
4309
+				throw new EE_Error(
4310
+					sprintf(
4311
+						__(
4312
+							"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))",
4313
+							"event_espresso"
4314
+						),
4315
+						implode(",", $php_array_like_string)
4316
+					)
4317
+				);
4318
+			}
4319
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4320
+		} else {
4321
+			$operator = '=';
4322
+			$value = $op_and_value;
4323
+		}
4324
+		//check to see if the value is actually another field
4325
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4326
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4327
+		}
4328
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4329
+			//in this case, the value should be an array, or at least a comma-separated list
4330
+			//it will need to handle a little differently
4331
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4332
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4333
+			return $operator . SP . $cleaned_value;
4334
+		}
4335
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4336
+			//the value should be an array with count of two.
4337
+			if (count($value) !== 2) {
4338
+				throw new EE_Error(
4339
+					sprintf(
4340
+						__(
4341
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4342
+							'event_espresso'
4343
+						),
4344
+						"BETWEEN"
4345
+					)
4346
+				);
4347
+			}
4348
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4349
+			return $operator . SP . $cleaned_value;
4350
+		}
4351
+		if (in_array($operator, $this->valid_null_style_operators())) {
4352
+			if ($value !== null) {
4353
+				throw new EE_Error(
4354
+					sprintf(
4355
+						__(
4356
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4357
+							"event_espresso"
4358
+						),
4359
+						$value,
4360
+						$operator
4361
+					)
4362
+				);
4363
+			}
4364
+			return $operator;
4365
+		}
4366
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4367
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4368
+			//remove other junk. So just treat it as a string.
4369
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4370
+		}
4371
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4372
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4373
+		}
4374
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4375
+			throw new EE_Error(
4376
+				sprintf(
4377
+					__(
4378
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4379
+						'event_espresso'
4380
+					),
4381
+					$operator,
4382
+					$operator
4383
+				)
4384
+			);
4385
+		}
4386
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4387
+			throw new EE_Error(
4388
+				sprintf(
4389
+					__(
4390
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4391
+						'event_espresso'
4392
+					),
4393
+					$operator,
4394
+					$operator
4395
+				)
4396
+			);
4397
+		}
4398
+		throw new EE_Error(
4399
+			sprintf(
4400
+				__(
4401
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4402
+					"event_espresso"
4403
+				),
4404
+				http_build_query($op_and_value)
4405
+			)
4406
+		);
4407
+	}
4408
+
4409
+
4410
+
4411
+	/**
4412
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4413
+	 *
4414
+	 * @param array                      $values
4415
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4416
+	 *                                              '%s'
4417
+	 * @return string
4418
+	 * @throws EE_Error
4419
+	 */
4420
+	public function _construct_between_value($values, $field_obj)
4421
+	{
4422
+		$cleaned_values = array();
4423
+		foreach ($values as $value) {
4424
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4425
+		}
4426
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4427
+	}
4428
+
4429
+
4430
+
4431
+	/**
4432
+	 * Takes an array or a comma-separated list of $values and cleans them
4433
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4434
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4435
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4436
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4437
+	 *
4438
+	 * @param mixed                      $values    array or comma-separated string
4439
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4440
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4441
+	 * @throws EE_Error
4442
+	 */
4443
+	public function _construct_in_value($values, $field_obj)
4444
+	{
4445
+		//check if the value is a CSV list
4446
+		if (is_string($values)) {
4447
+			//in which case, turn it into an array
4448
+			$values = explode(",", $values);
4449
+		}
4450
+		$cleaned_values = array();
4451
+		foreach ($values as $value) {
4452
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4453
+		}
4454
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4455
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4456
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4457
+		if (empty($cleaned_values)) {
4458
+			$all_fields = $this->field_settings();
4459
+			$a_field = array_shift($all_fields);
4460
+			$main_table = $this->_get_main_table();
4461
+			$cleaned_values[] = "SELECT "
4462
+								. $a_field->get_table_column()
4463
+								. " FROM "
4464
+								. $main_table->get_table_name()
4465
+								. " WHERE FALSE";
4466
+		}
4467
+		return "(" . implode(",", $cleaned_values) . ")";
4468
+	}
4469
+
4470
+
4471
+
4472
+	/**
4473
+	 * @param mixed                      $value
4474
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4475
+	 * @throws EE_Error
4476
+	 * @return false|null|string
4477
+	 */
4478
+	private function _wpdb_prepare_using_field($value, $field_obj)
4479
+	{
4480
+		/** @type WPDB $wpdb */
4481
+		global $wpdb;
4482
+		if ($field_obj instanceof EE_Model_Field_Base) {
4483
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4484
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4485
+		} //$field_obj should really just be a data type
4486
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4487
+			throw new EE_Error(
4488
+				sprintf(
4489
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4490
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)
4491
+				)
4492
+			);
4493
+		}
4494
+		return $wpdb->prepare($field_obj, $value);
4495
+	}
4496
+
4497
+
4498
+
4499
+	/**
4500
+	 * Takes the input parameter and finds the model field that it indicates.
4501
+	 *
4502
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4503
+	 * @throws EE_Error
4504
+	 * @return EE_Model_Field_Base
4505
+	 */
4506
+	protected function _deduce_field_from_query_param($query_param_name)
4507
+	{
4508
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4509
+		//which will help us find the database table and column
4510
+		$query_param_parts = explode(".", $query_param_name);
4511
+		if (empty($query_param_parts)) {
4512
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4513
+				'event_espresso'), $query_param_name));
4514
+		}
4515
+		$number_of_parts = count($query_param_parts);
4516
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4517
+		if ($number_of_parts === 1) {
4518
+			$field_name = $last_query_param_part;
4519
+			$model_obj = $this;
4520
+		} else {// $number_of_parts >= 2
4521
+			//the last part is the column name, and there are only 2parts. therefore...
4522
+			$field_name = $last_query_param_part;
4523
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4524
+		}
4525
+		try {
4526
+			return $model_obj->field_settings_for($field_name);
4527
+		} catch (EE_Error $e) {
4528
+			return null;
4529
+		}
4530
+	}
4531
+
4532
+
4533
+
4534
+	/**
4535
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4536
+	 * alias and column which corresponds to it
4537
+	 *
4538
+	 * @param string $field_name
4539
+	 * @throws EE_Error
4540
+	 * @return string
4541
+	 */
4542
+	public function _get_qualified_column_for_field($field_name)
4543
+	{
4544
+		$all_fields = $this->field_settings();
4545
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4546
+		if ($field) {
4547
+			return $field->get_qualified_column();
4548
+		}
4549
+		throw new EE_Error(
4550
+			sprintf(
4551
+				__(
4552
+					"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.",
4553
+					'event_espresso'
4554
+				), $field_name, get_class($this)
4555
+			)
4556
+		);
4557
+	}
4558
+
4559
+
4560
+
4561
+	/**
4562
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4563
+	 * Example usage:
4564
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4565
+	 *      array(),
4566
+	 *      ARRAY_A,
4567
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4568
+	 *  );
4569
+	 * is equivalent to
4570
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4571
+	 * and
4572
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4573
+	 *      array(
4574
+	 *          array(
4575
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4576
+	 *          ),
4577
+	 *          ARRAY_A,
4578
+	 *          implode(
4579
+	 *              ', ',
4580
+	 *              array_merge(
4581
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4582
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4583
+	 *              )
4584
+	 *          )
4585
+	 *      )
4586
+	 *  );
4587
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4588
+	 *
4589
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4590
+	 *                                            and the one whose fields you are selecting for example: when querying
4591
+	 *                                            tickets model and selecting fields from the tickets model you would
4592
+	 *                                            leave this parameter empty, because no models are needed to join
4593
+	 *                                            between the queried model and the selected one. Likewise when
4594
+	 *                                            querying the datetime model and selecting fields from the tickets
4595
+	 *                                            model, it would also be left empty, because there is a direct
4596
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4597
+	 *                                            them together. However, when querying from the event model and
4598
+	 *                                            selecting fields from the ticket model, you should provide the string
4599
+	 *                                            'Datetime', indicating that the event model must first join to the
4600
+	 *                                            datetime model in order to find its relation to ticket model.
4601
+	 *                                            Also, when querying from the venue model and selecting fields from
4602
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4603
+	 *                                            indicating you need to join the venue model to the event model,
4604
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4605
+	 *                                            This string is used to deduce the prefix that gets added onto the
4606
+	 *                                            models' tables qualified columns
4607
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4608
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4609
+	 *                                            qualified column names
4610
+	 * @return array|string
4611
+	 */
4612
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4613
+	{
4614
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4615
+		$qualified_columns = array();
4616
+		foreach ($this->field_settings() as $field_name => $field) {
4617
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4618
+		}
4619
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4620
+	}
4621
+
4622
+
4623
+
4624
+	/**
4625
+	 * constructs the select use on special limit joins
4626
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4627
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4628
+	 * (as that is typically where the limits would be set).
4629
+	 *
4630
+	 * @param  string       $table_alias The table the select is being built for
4631
+	 * @param  mixed|string $limit       The limit for this select
4632
+	 * @return string                The final select join element for the query.
4633
+	 */
4634
+	public function _construct_limit_join_select($table_alias, $limit)
4635
+	{
4636
+		$SQL = '';
4637
+		foreach ($this->_tables as $table_obj) {
4638
+			if ($table_obj instanceof EE_Primary_Table) {
4639
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4640
+					? $table_obj->get_select_join_limit($limit)
4641
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4642
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4643
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4644
+					? $table_obj->get_select_join_limit_join($limit)
4645
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4646
+			}
4647
+		}
4648
+		return $SQL;
4649
+	}
4650
+
4651
+
4652
+
4653
+	/**
4654
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4655
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4656
+	 *
4657
+	 * @return string SQL
4658
+	 * @throws EE_Error
4659
+	 */
4660
+	public function _construct_internal_join()
4661
+	{
4662
+		$SQL = $this->_get_main_table()->get_table_sql();
4663
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4664
+		return $SQL;
4665
+	}
4666
+
4667
+
4668
+
4669
+	/**
4670
+	 * Constructs the SQL for joining all the tables on this model.
4671
+	 * Normally $alias should be the primary table's alias, but in cases where
4672
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4673
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4674
+	 * alias, this will construct SQL like:
4675
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4676
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4677
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4678
+	 *
4679
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4680
+	 * @return string
4681
+	 */
4682
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4683
+	{
4684
+		$SQL = '';
4685
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4686
+		foreach ($this->_tables as $table_obj) {
4687
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4688
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4689
+					//so we're joining to this table, meaning the table is already in
4690
+					//the FROM statement, BUT the primary table isn't. So we want
4691
+					//to add the inverse join sql
4692
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4693
+				} else {
4694
+					//just add a regular JOIN to this table from the primary table
4695
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4696
+				}
4697
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4698
+		}
4699
+		return $SQL;
4700
+	}
4701
+
4702
+
4703
+
4704
+	/**
4705
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4706
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4707
+	 * their data type (eg, '%s', '%d', etc)
4708
+	 *
4709
+	 * @return array
4710
+	 */
4711
+	public function _get_data_types()
4712
+	{
4713
+		$data_types = array();
4714
+		foreach ($this->field_settings() as $field_obj) {
4715
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4716
+			/** @var $field_obj EE_Model_Field_Base */
4717
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4718
+		}
4719
+		return $data_types;
4720
+	}
4721
+
4722
+
4723
+
4724
+	/**
4725
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4726
+	 *
4727
+	 * @param string $model_name
4728
+	 * @throws EE_Error
4729
+	 * @return EEM_Base
4730
+	 */
4731
+	public function get_related_model_obj($model_name)
4732
+	{
4733
+		$model_classname = "EEM_" . $model_name;
4734
+		if (! class_exists($model_classname)) {
4735
+			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",
4736
+				'event_espresso'), $model_name, $model_classname));
4737
+		}
4738
+		return call_user_func($model_classname . "::instance");
4739
+	}
4740
+
4741
+
4742
+
4743
+	/**
4744
+	 * Returns the array of EE_ModelRelations for this model.
4745
+	 *
4746
+	 * @return EE_Model_Relation_Base[]
4747
+	 */
4748
+	public function relation_settings()
4749
+	{
4750
+		return $this->_model_relations;
4751
+	}
4752
+
4753
+
4754
+
4755
+	/**
4756
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4757
+	 * because without THOSE models, this model probably doesn't have much purpose.
4758
+	 * (Eg, without an event, datetimes have little purpose.)
4759
+	 *
4760
+	 * @return EE_Belongs_To_Relation[]
4761
+	 */
4762
+	public function belongs_to_relations()
4763
+	{
4764
+		$belongs_to_relations = array();
4765
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4766
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4767
+				$belongs_to_relations[$model_name] = $relation_obj;
4768
+			}
4769
+		}
4770
+		return $belongs_to_relations;
4771
+	}
4772
+
4773
+
4774
+
4775
+	/**
4776
+	 * Returns the specified EE_Model_Relation, or throws an exception
4777
+	 *
4778
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4779
+	 * @throws EE_Error
4780
+	 * @return EE_Model_Relation_Base
4781
+	 */
4782
+	public function related_settings_for($relation_name)
4783
+	{
4784
+		$relatedModels = $this->relation_settings();
4785
+		if (! array_key_exists($relation_name, $relatedModels)) {
4786
+			throw new EE_Error(
4787
+				sprintf(
4788
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4789
+						'event_espresso'),
4790
+					$relation_name,
4791
+					$this->_get_class_name(),
4792
+					implode(', ', array_keys($relatedModels))
4793
+				)
4794
+			);
4795
+		}
4796
+		return $relatedModels[$relation_name];
4797
+	}
4798
+
4799
+
4800
+
4801
+	/**
4802
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4803
+	 * fields
4804
+	 *
4805
+	 * @param string $fieldName
4806
+	 * @param boolean $include_db_only_fields
4807
+	 * @throws EE_Error
4808
+	 * @return EE_Model_Field_Base
4809
+	 */
4810
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4811
+	{
4812
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4813
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4814
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4815
+				get_class($this)));
4816
+		}
4817
+		return $fieldSettings[$fieldName];
4818
+	}
4819
+
4820
+
4821
+
4822
+	/**
4823
+	 * Checks if this field exists on this model
4824
+	 *
4825
+	 * @param string $fieldName a key in the model's _field_settings array
4826
+	 * @return boolean
4827
+	 */
4828
+	public function has_field($fieldName)
4829
+	{
4830
+		$fieldSettings = $this->field_settings(true);
4831
+		if (isset($fieldSettings[$fieldName])) {
4832
+			return true;
4833
+		}
4834
+		return false;
4835
+	}
4836
+
4837
+
4838
+
4839
+	/**
4840
+	 * Returns whether or not this model has a relation to the specified model
4841
+	 *
4842
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4843
+	 * @return boolean
4844
+	 */
4845
+	public function has_relation($relation_name)
4846
+	{
4847
+		$relations = $this->relation_settings();
4848
+		if (isset($relations[$relation_name])) {
4849
+			return true;
4850
+		}
4851
+		return false;
4852
+	}
4853
+
4854
+
4855
+
4856
+	/**
4857
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4858
+	 * Eg, on EE_Answer that would be ANS_ID field object
4859
+	 *
4860
+	 * @param $field_obj
4861
+	 * @return boolean
4862
+	 */
4863
+	public function is_primary_key_field($field_obj)
4864
+	{
4865
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4866
+	}
4867
+
4868
+
4869
+
4870
+	/**
4871
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4872
+	 * Eg, on EE_Answer that would be ANS_ID field object
4873
+	 *
4874
+	 * @return EE_Model_Field_Base
4875
+	 * @throws EE_Error
4876
+	 */
4877
+	public function get_primary_key_field()
4878
+	{
4879
+		if ($this->_primary_key_field === null) {
4880
+			foreach ($this->field_settings(true) as $field_obj) {
4881
+				if ($this->is_primary_key_field($field_obj)) {
4882
+					$this->_primary_key_field = $field_obj;
4883
+					break;
4884
+				}
4885
+			}
4886
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4887
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4888
+					get_class($this)));
4889
+			}
4890
+		}
4891
+		return $this->_primary_key_field;
4892
+	}
4893
+
4894
+
4895
+
4896
+	/**
4897
+	 * Returns whether or not not there is a primary key on this model.
4898
+	 * Internally does some caching.
4899
+	 *
4900
+	 * @return boolean
4901
+	 */
4902
+	public function has_primary_key_field()
4903
+	{
4904
+		if ($this->_has_primary_key_field === null) {
4905
+			try {
4906
+				$this->get_primary_key_field();
4907
+				$this->_has_primary_key_field = true;
4908
+			} catch (EE_Error $e) {
4909
+				$this->_has_primary_key_field = false;
4910
+			}
4911
+		}
4912
+		return $this->_has_primary_key_field;
4913
+	}
4914
+
4915
+
4916
+
4917
+	/**
4918
+	 * Finds the first field of type $field_class_name.
4919
+	 *
4920
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4921
+	 *                                 EE_Foreign_Key_Field, etc
4922
+	 * @return EE_Model_Field_Base or null if none is found
4923
+	 */
4924
+	public function get_a_field_of_type($field_class_name)
4925
+	{
4926
+		foreach ($this->field_settings() as $field) {
4927
+			if ($field instanceof $field_class_name) {
4928
+				return $field;
4929
+			}
4930
+		}
4931
+		return null;
4932
+	}
4933
+
4934
+
4935
+
4936
+	/**
4937
+	 * Gets a foreign key field pointing to model.
4938
+	 *
4939
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4940
+	 * @return EE_Foreign_Key_Field_Base
4941
+	 * @throws EE_Error
4942
+	 */
4943
+	public function get_foreign_key_to($model_name)
4944
+	{
4945
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4946
+			foreach ($this->field_settings() as $field) {
4947
+				if (
4948
+					$field instanceof EE_Foreign_Key_Field_Base
4949
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4950
+				) {
4951
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4952
+					break;
4953
+				}
4954
+			}
4955
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4956
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4957
+					'event_espresso'), $model_name, get_class($this)));
4958
+			}
4959
+		}
4960
+		return $this->_cache_foreign_key_to_fields[$model_name];
4961
+	}
4962
+
4963
+
4964
+
4965
+	/**
4966
+	 * Gets the table name (including $wpdb->prefix) for the table alias
4967
+	 *
4968
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4969
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4970
+	 *                            Either one works
4971
+	 * @return string
4972
+	 */
4973
+	public function get_table_for_alias($table_alias)
4974
+	{
4975
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4976
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4977
+	}
4978
+
4979
+
4980
+
4981
+	/**
4982
+	 * Returns a flat array of all field son this model, instead of organizing them
4983
+	 * by table_alias as they are in the constructor.
4984
+	 *
4985
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4986
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4987
+	 */
4988
+	public function field_settings($include_db_only_fields = false)
4989
+	{
4990
+		if ($include_db_only_fields) {
4991
+			if ($this->_cached_fields === null) {
4992
+				$this->_cached_fields = array();
4993
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4994
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4995
+						$this->_cached_fields[$field_name] = $field_obj;
4996
+					}
4997
+				}
4998
+			}
4999
+			return $this->_cached_fields;
5000
+		}
5001
+		if ($this->_cached_fields_non_db_only === null) {
5002
+			$this->_cached_fields_non_db_only = array();
5003
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5004
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5005
+					/** @var $field_obj EE_Model_Field_Base */
5006
+					if (! $field_obj->is_db_only_field()) {
5007
+						$this->_cached_fields_non_db_only[$field_name] = $field_obj;
5008
+					}
5009
+				}
5010
+			}
5011
+		}
5012
+		return $this->_cached_fields_non_db_only;
5013
+	}
5014
+
5015
+
5016
+
5017
+	/**
5018
+	 *        cycle though array of attendees and create objects out of each item
5019
+	 *
5020
+	 * @access        private
5021
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5022
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5023
+	 *                           numerically indexed)
5024
+	 * @throws EE_Error
5025
+	 */
5026
+	protected function _create_objects($rows = array())
5027
+	{
5028
+		$array_of_objects = array();
5029
+		if (empty($rows)) {
5030
+			return array();
5031
+		}
5032
+		$count_if_model_has_no_primary_key = 0;
5033
+		$has_primary_key = $this->has_primary_key_field();
5034
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5035
+		foreach ((array)$rows as $row) {
5036
+			if (empty($row)) {
5037
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5038
+				return array();
5039
+			}
5040
+			//check if we've already set this object in the results array,
5041
+			//in which case there's no need to process it further (again)
5042
+			if ($has_primary_key) {
5043
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5044
+					$row,
5045
+					$primary_key_field->get_qualified_column(),
5046
+					$primary_key_field->get_table_column()
5047
+				);
5048
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5049
+					continue;
5050
+				}
5051
+			}
5052
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5053
+			if (! $classInstance) {
5054
+				throw new EE_Error(
5055
+					sprintf(
5056
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5057
+						$this->get_this_model_name(),
5058
+						http_build_query($row)
5059
+					)
5060
+				);
5061
+			}
5062
+			//set the timezone on the instantiated objects
5063
+			$classInstance->set_timezone($this->_timezone);
5064
+			//make sure if there is any timezone setting present that we set the timezone for the object
5065
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5066
+			$array_of_objects[$key] = $classInstance;
5067
+			//also, for all the relations of type BelongsTo, see if we can cache
5068
+			//those related models
5069
+			//(we could do this for other relations too, but if there are conditions
5070
+			//that filtered out some fo the results, then we'd be caching an incomplete set
5071
+			//so it requires a little more thought than just caching them immediately...)
5072
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5073
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5074
+					//check if this model's INFO is present. If so, cache it on the model
5075
+					$other_model = $relation_obj->get_other_model();
5076
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5077
+					//if we managed to make a model object from the results, cache it on the main model object
5078
+					if ($other_model_obj_maybe) {
5079
+						//set timezone on these other model objects if they are present
5080
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5081
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5082
+					}
5083
+				}
5084
+			}
5085
+			//also, if this was a custom select query, let's see if there are any results for the custom select fields
5086
+			//and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5087
+			//the field in the CustomSelects object
5088
+			if ($this->_custom_selections instanceof CustomSelects) {
5089
+				$classInstance->setCustomSelectsValues(
5090
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5091
+				);
5092
+			}
5093
+		}
5094
+		return $array_of_objects;
5095
+	}
5096
+
5097
+
5098
+	/**
5099
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5100
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5101
+	 *
5102
+	 * @param array $db_results_row
5103
+	 * @return array
5104
+	 */
5105
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5106
+	{
5107
+		$results = array();
5108
+		if ($this->_custom_selections instanceof CustomSelects) {
5109
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5110
+				if (isset($db_results_row[$alias])) {
5111
+					$results[$alias] = $this->convertValueToDataType(
5112
+						$db_results_row[$alias],
5113
+						$this->_custom_selections->getDataTypeForAlias($alias)
5114
+					);
5115
+				}
5116
+			}
5117
+		}
5118
+		return $results;
5119
+	}
5120
+
5121
+
5122
+	/**
5123
+	 * This will set the value for the given alias
5124
+	 * @param string $value
5125
+	 * @param string $datatype (one of %d, %s, %f)
5126
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5127
+	 */
5128
+	protected function convertValueToDataType($value, $datatype)
5129
+	{
5130
+		switch ($datatype) {
5131
+			case '%f':
5132
+				return (float) $value;
5133
+			case '%d':
5134
+				return (int) $value;
5135
+			default:
5136
+				return (string) $value;
5137
+		}
5138
+	}
5139
+
5140
+
5141
+	/**
5142
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5143
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5144
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5145
+	 * object (as set in the model_field!).
5146
+	 *
5147
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5148
+	 */
5149
+	public function create_default_object()
5150
+	{
5151
+		$this_model_fields_and_values = array();
5152
+		//setup the row using default values;
5153
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5154
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5155
+		}
5156
+		$className = $this->_get_class_name();
5157
+		$classInstance = EE_Registry::instance()
5158
+									->load_class($className, array($this_model_fields_and_values), false, false);
5159
+		return $classInstance;
5160
+	}
5161
+
5162
+
5163
+
5164
+	/**
5165
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5166
+	 *                             or an stdClass where each property is the name of a column,
5167
+	 * @return EE_Base_Class
5168
+	 * @throws EE_Error
5169
+	 */
5170
+	public function instantiate_class_from_array_or_object($cols_n_values)
5171
+	{
5172
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5173
+			$cols_n_values = get_object_vars($cols_n_values);
5174
+		}
5175
+		$primary_key = null;
5176
+		//make sure the array only has keys that are fields/columns on this model
5177
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5178
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5179
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5180
+		}
5181
+		$className = $this->_get_class_name();
5182
+		//check we actually found results that we can use to build our model object
5183
+		//if not, return null
5184
+		if ($this->has_primary_key_field()) {
5185
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5186
+				return null;
5187
+			}
5188
+		} else if ($this->unique_indexes()) {
5189
+			$first_column = reset($this_model_fields_n_values);
5190
+			if (empty($first_column)) {
5191
+				return null;
5192
+			}
5193
+		}
5194
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5195
+		if ($primary_key) {
5196
+			$classInstance = $this->get_from_entity_map($primary_key);
5197
+			if (! $classInstance) {
5198
+				$classInstance = EE_Registry::instance()
5199
+											->load_class($className,
5200
+												array($this_model_fields_n_values, $this->_timezone), true, false);
5201
+				// add this new object to the entity map
5202
+				$classInstance = $this->add_to_entity_map($classInstance);
5203
+			}
5204
+		} else {
5205
+			$classInstance = EE_Registry::instance()
5206
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5207
+											true, false);
5208
+		}
5209
+		return $classInstance;
5210
+	}
5211
+
5212
+
5213
+
5214
+	/**
5215
+	 * Gets the model object from the  entity map if it exists
5216
+	 *
5217
+	 * @param int|string $id the ID of the model object
5218
+	 * @return EE_Base_Class
5219
+	 */
5220
+	public function get_from_entity_map($id)
5221
+	{
5222
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5223
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5224
+	}
5225
+
5226
+
5227
+
5228
+	/**
5229
+	 * add_to_entity_map
5230
+	 * Adds the object to the model's entity mappings
5231
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5232
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5233
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5234
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5235
+	 *        then this method should be called immediately after the update query
5236
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5237
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5238
+	 *
5239
+	 * @param    EE_Base_Class $object
5240
+	 * @throws EE_Error
5241
+	 * @return \EE_Base_Class
5242
+	 */
5243
+	public function add_to_entity_map(EE_Base_Class $object)
5244
+	{
5245
+		$className = $this->_get_class_name();
5246
+		if (! $object instanceof $className) {
5247
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5248
+				is_object($object) ? get_class($object) : $object, $className));
5249
+		}
5250
+		/** @var $object EE_Base_Class */
5251
+		if (! $object->ID()) {
5252
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5253
+				"event_espresso"), get_class($this)));
5254
+		}
5255
+		// double check it's not already there
5256
+		$classInstance = $this->get_from_entity_map($object->ID());
5257
+		if ($classInstance) {
5258
+			return $classInstance;
5259
+		}
5260
+		$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5261
+		return $object;
5262
+	}
5263
+
5264
+
5265
+
5266
+	/**
5267
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5268
+	 * if no identifier is provided, then the entire entity map is emptied
5269
+	 *
5270
+	 * @param int|string $id the ID of the model object
5271
+	 * @return boolean
5272
+	 */
5273
+	public function clear_entity_map($id = null)
5274
+	{
5275
+		if (empty($id)) {
5276
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5277
+			return true;
5278
+		}
5279
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5280
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5281
+			return true;
5282
+		}
5283
+		return false;
5284
+	}
5285
+
5286
+
5287
+
5288
+	/**
5289
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5290
+	 * Given an array where keys are column (or column alias) names and values,
5291
+	 * returns an array of their corresponding field names and database values
5292
+	 *
5293
+	 * @param array $cols_n_values
5294
+	 * @return array
5295
+	 */
5296
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5297
+	{
5298
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5299
+	}
5300
+
5301
+
5302
+
5303
+	/**
5304
+	 * _deduce_fields_n_values_from_cols_n_values
5305
+	 * Given an array where keys are column (or column alias) names and values,
5306
+	 * returns an array of their corresponding field names and database values
5307
+	 *
5308
+	 * @param string $cols_n_values
5309
+	 * @return array
5310
+	 */
5311
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5312
+	{
5313
+		$this_model_fields_n_values = array();
5314
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5315
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5316
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5317
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5318
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5319
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5320
+					if (! $field_obj->is_db_only_field()) {
5321
+						//prepare field as if its coming from db
5322
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5323
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5324
+					}
5325
+				}
5326
+			} else {
5327
+				//the table's rows existed. Use their values
5328
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5329
+					if (! $field_obj->is_db_only_field()) {
5330
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5331
+							$cols_n_values, $field_obj->get_qualified_column(),
5332
+							$field_obj->get_table_column()
5333
+						);
5334
+					}
5335
+				}
5336
+			}
5337
+		}
5338
+		return $this_model_fields_n_values;
5339
+	}
5340
+
5341
+
5342
+
5343
+	/**
5344
+	 * @param $cols_n_values
5345
+	 * @param $qualified_column
5346
+	 * @param $regular_column
5347
+	 * @return null
5348
+	 */
5349
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5350
+	{
5351
+		$value = null;
5352
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5353
+		//does the field on the model relate to this column retrieved from the db?
5354
+		//or is it a db-only field? (not relating to the model)
5355
+		if (isset($cols_n_values[$qualified_column])) {
5356
+			$value = $cols_n_values[$qualified_column];
5357
+		} elseif (isset($cols_n_values[$regular_column])) {
5358
+			$value = $cols_n_values[$regular_column];
5359
+		}
5360
+		return $value;
5361
+	}
5362
+
5363
+
5364
+
5365
+	/**
5366
+	 * refresh_entity_map_from_db
5367
+	 * Makes sure the model object in the entity map at $id assumes the values
5368
+	 * of the database (opposite of EE_base_Class::save())
5369
+	 *
5370
+	 * @param int|string $id
5371
+	 * @return EE_Base_Class
5372
+	 * @throws EE_Error
5373
+	 */
5374
+	public function refresh_entity_map_from_db($id)
5375
+	{
5376
+		$obj_in_map = $this->get_from_entity_map($id);
5377
+		if ($obj_in_map) {
5378
+			$wpdb_results = $this->_get_all_wpdb_results(
5379
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5380
+			);
5381
+			if ($wpdb_results && is_array($wpdb_results)) {
5382
+				$one_row = reset($wpdb_results);
5383
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5384
+					$obj_in_map->set_from_db($field_name, $db_value);
5385
+				}
5386
+				//clear the cache of related model objects
5387
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5388
+					$obj_in_map->clear_cache($relation_name, null, true);
5389
+				}
5390
+			}
5391
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5392
+			return $obj_in_map;
5393
+		}
5394
+		return $this->get_one_by_ID($id);
5395
+	}
5396
+
5397
+
5398
+
5399
+	/**
5400
+	 * refresh_entity_map_with
5401
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5402
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5403
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5404
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5405
+	 *
5406
+	 * @param int|string    $id
5407
+	 * @param EE_Base_Class $replacing_model_obj
5408
+	 * @return \EE_Base_Class
5409
+	 * @throws EE_Error
5410
+	 */
5411
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5412
+	{
5413
+		$obj_in_map = $this->get_from_entity_map($id);
5414
+		if ($obj_in_map) {
5415
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5416
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5417
+					$obj_in_map->set($field_name, $value);
5418
+				}
5419
+				//make the model object in the entity map's cache match the $replacing_model_obj
5420
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5421
+					$obj_in_map->clear_cache($relation_name, null, true);
5422
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5423
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5424
+					}
5425
+				}
5426
+			}
5427
+			return $obj_in_map;
5428
+		}
5429
+		$this->add_to_entity_map($replacing_model_obj);
5430
+		return $replacing_model_obj;
5431
+	}
5432
+
5433
+
5434
+
5435
+	/**
5436
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5437
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5438
+	 * require_once($this->_getClassName().".class.php");
5439
+	 *
5440
+	 * @return string
5441
+	 */
5442
+	private function _get_class_name()
5443
+	{
5444
+		return "EE_" . $this->get_this_model_name();
5445
+	}
5446
+
5447
+
5448
+
5449
+	/**
5450
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5451
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5452
+	 * it would be 'Events'.
5453
+	 *
5454
+	 * @param int $quantity
5455
+	 * @return string
5456
+	 */
5457
+	public function item_name($quantity = 1)
5458
+	{
5459
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5460
+	}
5461
+
5462
+
5463
+
5464
+	/**
5465
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5466
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5467
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5468
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5469
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5470
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5471
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5472
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5473
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5474
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5475
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5476
+	 *        return $previousReturnValue.$returnString;
5477
+	 * }
5478
+	 * require('EEM_Answer.model.php');
5479
+	 * $answer=EEM_Answer::instance();
5480
+	 * echo $answer->my_callback('monkeys',100);
5481
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5482
+	 *
5483
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5484
+	 * @param array  $args       array of original arguments passed to the function
5485
+	 * @throws EE_Error
5486
+	 * @return mixed whatever the plugin which calls add_filter decides
5487
+	 */
5488
+	public function __call($methodName, $args)
5489
+	{
5490
+		$className = get_class($this);
5491
+		$tagName = "FHEE__{$className}__{$methodName}";
5492
+		if (! has_filter($tagName)) {
5493
+			throw new EE_Error(
5494
+				sprintf(
5495
+					__('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 );',
5496
+						'event_espresso'),
5497
+					$methodName,
5498
+					$className,
5499
+					$tagName,
5500
+					'<br />'
5501
+				)
5502
+			);
5503
+		}
5504
+		return apply_filters($tagName, null, $this, $args);
5505
+	}
5506
+
5507
+
5508
+
5509
+	/**
5510
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5511
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5512
+	 *
5513
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5514
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5515
+	 *                                                       the object's class name
5516
+	 *                                                       or object's ID
5517
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5518
+	 *                                                       exists in the database. If it does not, we add it
5519
+	 * @throws EE_Error
5520
+	 * @return EE_Base_Class
5521
+	 */
5522
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5523
+	{
5524
+		$className = $this->_get_class_name();
5525
+		if ($base_class_obj_or_id instanceof $className) {
5526
+			$model_object = $base_class_obj_or_id;
5527
+		} else {
5528
+			$primary_key_field = $this->get_primary_key_field();
5529
+			if (
5530
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5531
+				&& (
5532
+					is_int($base_class_obj_or_id)
5533
+					|| is_string($base_class_obj_or_id)
5534
+				)
5535
+			) {
5536
+				// assume it's an ID.
5537
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5538
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5539
+			} else if (
5540
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5541
+				&& is_string($base_class_obj_or_id)
5542
+			) {
5543
+				// assume its a string representation of the object
5544
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5545
+			} else {
5546
+				throw new EE_Error(
5547
+					sprintf(
5548
+						__(
5549
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5550
+							'event_espresso'
5551
+						),
5552
+						$base_class_obj_or_id,
5553
+						$this->_get_class_name(),
5554
+						print_r($base_class_obj_or_id, true)
5555
+					)
5556
+				);
5557
+			}
5558
+		}
5559
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5560
+			$model_object->save();
5561
+		}
5562
+		return $model_object;
5563
+	}
5564
+
5565
+
5566
+
5567
+	/**
5568
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5569
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5570
+	 * returns it ID.
5571
+	 *
5572
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5573
+	 * @return int|string depending on the type of this model object's ID
5574
+	 * @throws EE_Error
5575
+	 */
5576
+	public function ensure_is_ID($base_class_obj_or_id)
5577
+	{
5578
+		$className = $this->_get_class_name();
5579
+		if ($base_class_obj_or_id instanceof $className) {
5580
+			/** @var $base_class_obj_or_id EE_Base_Class */
5581
+			$id = $base_class_obj_or_id->ID();
5582
+		} elseif (is_int($base_class_obj_or_id)) {
5583
+			//assume it's an ID
5584
+			$id = $base_class_obj_or_id;
5585
+		} elseif (is_string($base_class_obj_or_id)) {
5586
+			//assume its a string representation of the object
5587
+			$id = $base_class_obj_or_id;
5588
+		} else {
5589
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5590
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5591
+				print_r($base_class_obj_or_id, true)));
5592
+		}
5593
+		return $id;
5594
+	}
5595
+
5596
+
5597
+
5598
+	/**
5599
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5600
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5601
+	 * been sanitized and converted into the appropriate domain.
5602
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5603
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5604
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5605
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5606
+	 * $EVT = EEM_Event::instance(); $old_setting =
5607
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5608
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5609
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5610
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5611
+	 *
5612
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5613
+	 * @return void
5614
+	 */
5615
+	public function assume_values_already_prepared_by_model_object(
5616
+		$values_already_prepared = self::not_prepared_by_model_object
5617
+	) {
5618
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5619
+	}
5620
+
5621
+
5622
+
5623
+	/**
5624
+	 * Read comments for assume_values_already_prepared_by_model_object()
5625
+	 *
5626
+	 * @return int
5627
+	 */
5628
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5629
+	{
5630
+		return $this->_values_already_prepared_by_model_object;
5631
+	}
5632
+
5633
+
5634
+
5635
+	/**
5636
+	 * Gets all the indexes on this model
5637
+	 *
5638
+	 * @return EE_Index[]
5639
+	 */
5640
+	public function indexes()
5641
+	{
5642
+		return $this->_indexes;
5643
+	}
5644
+
5645
+
5646
+
5647
+	/**
5648
+	 * Gets all the Unique Indexes on this model
5649
+	 *
5650
+	 * @return EE_Unique_Index[]
5651
+	 */
5652
+	public function unique_indexes()
5653
+	{
5654
+		$unique_indexes = array();
5655
+		foreach ($this->_indexes as $name => $index) {
5656
+			if ($index instanceof EE_Unique_Index) {
5657
+				$unique_indexes [$name] = $index;
5658
+			}
5659
+		}
5660
+		return $unique_indexes;
5661
+	}
5662
+
5663
+
5664
+
5665
+	/**
5666
+	 * Gets all the fields which, when combined, make the primary key.
5667
+	 * This is usually just an array with 1 element (the primary key), but in cases
5668
+	 * where there is no primary key, it's a combination of fields as defined
5669
+	 * on a primary index
5670
+	 *
5671
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5672
+	 * @throws EE_Error
5673
+	 */
5674
+	public function get_combined_primary_key_fields()
5675
+	{
5676
+		foreach ($this->indexes() as $index) {
5677
+			if ($index instanceof EE_Primary_Key_Index) {
5678
+				return $index->fields();
5679
+			}
5680
+		}
5681
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5682
+	}
5683
+
5684
+
5685
+
5686
+	/**
5687
+	 * Used to build a primary key string (when the model has no primary key),
5688
+	 * which can be used a unique string to identify this model object.
5689
+	 *
5690
+	 * @param array $cols_n_values keys are field names, values are their values
5691
+	 * @return string
5692
+	 * @throws EE_Error
5693
+	 */
5694
+	public function get_index_primary_key_string($cols_n_values)
5695
+	{
5696
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5697
+			$this->get_combined_primary_key_fields());
5698
+		return http_build_query($cols_n_values_for_primary_key_index);
5699
+	}
5700
+
5701
+
5702
+
5703
+	/**
5704
+	 * Gets the field values from the primary key string
5705
+	 *
5706
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5707
+	 * @param string $index_primary_key_string
5708
+	 * @return null|array
5709
+	 * @throws EE_Error
5710
+	 */
5711
+	public function parse_index_primary_key_string($index_primary_key_string)
5712
+	{
5713
+		$key_fields = $this->get_combined_primary_key_fields();
5714
+		//check all of them are in the $id
5715
+		$key_vals_in_combined_pk = array();
5716
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5717
+		foreach ($key_fields as $key_field_name => $field_obj) {
5718
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5719
+				return null;
5720
+			}
5721
+		}
5722
+		return $key_vals_in_combined_pk;
5723
+	}
5724
+
5725
+
5726
+
5727
+	/**
5728
+	 * verifies that an array of key-value pairs for model fields has a key
5729
+	 * for each field comprising the primary key index
5730
+	 *
5731
+	 * @param array $key_vals
5732
+	 * @return boolean
5733
+	 * @throws EE_Error
5734
+	 */
5735
+	public function has_all_combined_primary_key_fields($key_vals)
5736
+	{
5737
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5738
+		foreach ($keys_it_should_have as $key) {
5739
+			if (! isset($key_vals[$key])) {
5740
+				return false;
5741
+			}
5742
+		}
5743
+		return true;
5744
+	}
5745
+
5746
+
5747
+
5748
+	/**
5749
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5750
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5751
+	 *
5752
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5753
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5754
+	 * @throws EE_Error
5755
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5756
+	 *                                                              indexed)
5757
+	 */
5758
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5759
+	{
5760
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5761
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5762
+		} elseif (is_array($model_object_or_attributes_array)) {
5763
+			$attributes_array = $model_object_or_attributes_array;
5764
+		} else {
5765
+			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",
5766
+				"event_espresso"), $model_object_or_attributes_array));
5767
+		}
5768
+		//even copies obviously won't have the same ID, so remove the primary key
5769
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5770
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5771
+			unset($attributes_array[$this->primary_key_name()]);
5772
+		}
5773
+		if (isset($query_params[0])) {
5774
+			$query_params[0] = array_merge($attributes_array, $query_params);
5775
+		} else {
5776
+			$query_params[0] = $attributes_array;
5777
+		}
5778
+		return $this->get_all($query_params);
5779
+	}
5780
+
5781
+
5782
+
5783
+	/**
5784
+	 * Gets the first copy we find. See get_all_copies for more details
5785
+	 *
5786
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5787
+	 * @param array $query_params
5788
+	 * @return EE_Base_Class
5789
+	 * @throws EE_Error
5790
+	 */
5791
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5792
+	{
5793
+		if (! is_array($query_params)) {
5794
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5795
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5796
+					gettype($query_params)), '4.6.0');
5797
+			$query_params = array();
5798
+		}
5799
+		$query_params['limit'] = 1;
5800
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5801
+		if (is_array($copies)) {
5802
+			return array_shift($copies);
5803
+		}
5804
+		return null;
5805
+	}
5806
+
5807
+
5808
+
5809
+	/**
5810
+	 * Updates the item with the specified id. Ignores default query parameters because
5811
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5812
+	 *
5813
+	 * @param array      $fields_n_values keys are field names, values are their new values
5814
+	 * @param int|string $id              the value of the primary key to update
5815
+	 * @return int number of rows updated
5816
+	 * @throws EE_Error
5817
+	 */
5818
+	public function update_by_ID($fields_n_values, $id)
5819
+	{
5820
+		$query_params = array(
5821
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5822
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5823
+		);
5824
+		return $this->update($fields_n_values, $query_params);
5825
+	}
5826
+
5827
+
5828
+
5829
+	/**
5830
+	 * Changes an operator which was supplied to the models into one usable in SQL
5831
+	 *
5832
+	 * @param string $operator_supplied
5833
+	 * @return string an operator which can be used in SQL
5834
+	 * @throws EE_Error
5835
+	 */
5836
+	private function _prepare_operator_for_sql($operator_supplied)
5837
+	{
5838
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5839
+			: null;
5840
+		if ($sql_operator) {
5841
+			return $sql_operator;
5842
+		}
5843
+		throw new EE_Error(
5844
+			sprintf(
5845
+				__(
5846
+					"The operator '%s' is not in the list of valid operators: %s",
5847
+					"event_espresso"
5848
+				), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5849
+			)
5850
+		);
5851
+	}
5852
+
5853
+
5854
+
5855
+	/**
5856
+	 * Gets the valid operators
5857
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5858
+	 */
5859
+	public function valid_operators(){
5860
+		return $this->_valid_operators;
5861
+	}
5862
+
5863
+
5864
+
5865
+	/**
5866
+	 * Gets the between-style operators (take 2 arguments).
5867
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5868
+	 */
5869
+	public function valid_between_style_operators()
5870
+	{
5871
+		return array_intersect(
5872
+			$this->valid_operators(),
5873
+			$this->_between_style_operators
5874
+		);
5875
+	}
5876
+
5877
+	/**
5878
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5879
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5880
+	 */
5881
+	public function valid_like_style_operators()
5882
+	{
5883
+		return array_intersect(
5884
+			$this->valid_operators(),
5885
+			$this->_like_style_operators
5886
+		);
5887
+	}
5888
+
5889
+	/**
5890
+	 * Gets the "in"-style operators
5891
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5892
+	 */
5893
+	public function valid_in_style_operators()
5894
+	{
5895
+		return array_intersect(
5896
+			$this->valid_operators(),
5897
+			$this->_in_style_operators
5898
+		);
5899
+	}
5900
+
5901
+	/**
5902
+	 * Gets the "null"-style operators (accept no arguments)
5903
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5904
+	 */
5905
+	public function valid_null_style_operators()
5906
+	{
5907
+		return array_intersect(
5908
+			$this->valid_operators(),
5909
+			$this->_null_style_operators
5910
+		);
5911
+	}
5912
+
5913
+	/**
5914
+	 * Gets an array where keys are the primary keys and values are their 'names'
5915
+	 * (as determined by the model object's name() function, which is often overridden)
5916
+	 *
5917
+	 * @param array $query_params like get_all's
5918
+	 * @return string[]
5919
+	 * @throws EE_Error
5920
+	 */
5921
+	public function get_all_names($query_params = array())
5922
+	{
5923
+		$objs = $this->get_all($query_params);
5924
+		$names = array();
5925
+		foreach ($objs as $obj) {
5926
+			$names[$obj->ID()] = $obj->name();
5927
+		}
5928
+		return $names;
5929
+	}
5930
+
5931
+
5932
+
5933
+	/**
5934
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5935
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5936
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5937
+	 * array_keys() on $model_objects.
5938
+	 *
5939
+	 * @param \EE_Base_Class[] $model_objects
5940
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5941
+	 *                                               in the returned array
5942
+	 * @return array
5943
+	 * @throws EE_Error
5944
+	 */
5945
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5946
+	{
5947
+		if (! $this->has_primary_key_field()) {
5948
+			if (WP_DEBUG) {
5949
+				EE_Error::add_error(
5950
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5951
+					__FILE__,
5952
+					__FUNCTION__,
5953
+					__LINE__
5954
+				);
5955
+			}
5956
+		}
5957
+		$IDs = array();
5958
+		foreach ($model_objects as $model_object) {
5959
+			$id = $model_object->ID();
5960
+			if (! $id) {
5961
+				if ($filter_out_empty_ids) {
5962
+					continue;
5963
+				}
5964
+				if (WP_DEBUG) {
5965
+					EE_Error::add_error(
5966
+						__(
5967
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5968
+							'event_espresso'
5969
+						),
5970
+						__FILE__,
5971
+						__FUNCTION__,
5972
+						__LINE__
5973
+					);
5974
+				}
5975
+			}
5976
+			$IDs[] = $id;
5977
+		}
5978
+		return $IDs;
5979
+	}
5980
+
5981
+
5982
+
5983
+	/**
5984
+	 * Returns the string used in capabilities relating to this model. If there
5985
+	 * are no capabilities that relate to this model returns false
5986
+	 *
5987
+	 * @return string|false
5988
+	 */
5989
+	public function cap_slug()
5990
+	{
5991
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5992
+	}
5993
+
5994
+
5995
+
5996
+	/**
5997
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5998
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5999
+	 * only returns the cap restrictions array in that context (ie, the array
6000
+	 * at that key)
6001
+	 *
6002
+	 * @param string $context
6003
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6004
+	 * @throws EE_Error
6005
+	 */
6006
+	public function cap_restrictions($context = EEM_Base::caps_read)
6007
+	{
6008
+		EEM_Base::verify_is_valid_cap_context($context);
6009
+		//check if we ought to run the restriction generator first
6010
+		if (
6011
+			isset($this->_cap_restriction_generators[$context])
6012
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6013
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6014
+		) {
6015
+			$this->_cap_restrictions[$context] = array_merge(
6016
+				$this->_cap_restrictions[$context],
6017
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
6018
+			);
6019
+		}
6020
+		//and make sure we've finalized the construction of each restriction
6021
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6022
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6023
+				$where_conditions_obj->_finalize_construct($this);
6024
+			}
6025
+		}
6026
+		return $this->_cap_restrictions[$context];
6027
+	}
6028
+
6029
+
6030
+
6031
+	/**
6032
+	 * Indicating whether or not this model thinks its a wp core model
6033
+	 *
6034
+	 * @return boolean
6035
+	 */
6036
+	public function is_wp_core_model()
6037
+	{
6038
+		return $this->_wp_core_model;
6039
+	}
6040
+
6041
+
6042
+
6043
+	/**
6044
+	 * Gets all the caps that are missing which impose a restriction on
6045
+	 * queries made in this context
6046
+	 *
6047
+	 * @param string $context one of EEM_Base::caps_ constants
6048
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6049
+	 * @throws EE_Error
6050
+	 */
6051
+	public function caps_missing($context = EEM_Base::caps_read)
6052
+	{
6053
+		$missing_caps = array();
6054
+		$cap_restrictions = $this->cap_restrictions($context);
6055
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6056
+			if (! EE_Capabilities::instance()
6057
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6058
+			) {
6059
+				$missing_caps[$cap] = $restriction_if_no_cap;
6060
+			}
6061
+		}
6062
+		return $missing_caps;
6063
+	}
6064
+
6065
+
6066
+
6067
+	/**
6068
+	 * Gets the mapping from capability contexts to action strings used in capability names
6069
+	 *
6070
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6071
+	 * one of 'read', 'edit', or 'delete'
6072
+	 */
6073
+	public function cap_contexts_to_cap_action_map()
6074
+	{
6075
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
6076
+			$this);
6077
+	}
6078
+
6079
+
6080
+
6081
+	/**
6082
+	 * Gets the action string for the specified capability context
6083
+	 *
6084
+	 * @param string $context
6085
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6086
+	 * @throws EE_Error
6087
+	 */
6088
+	public function cap_action_for_context($context)
6089
+	{
6090
+		$mapping = $this->cap_contexts_to_cap_action_map();
6091
+		if (isset($mapping[$context])) {
6092
+			return $mapping[$context];
6093
+		}
6094
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6095
+			return $action;
6096
+		}
6097
+		throw new EE_Error(
6098
+			sprintf(
6099
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6100
+				$context,
6101
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6102
+			)
6103
+		);
6104
+	}
6105
+
6106
+
6107
+
6108
+	/**
6109
+	 * Returns all the capability contexts which are valid when querying models
6110
+	 *
6111
+	 * @return array
6112
+	 */
6113
+	public static function valid_cap_contexts()
6114
+	{
6115
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6116
+			self::caps_read,
6117
+			self::caps_read_admin,
6118
+			self::caps_edit,
6119
+			self::caps_delete,
6120
+		));
6121
+	}
6122
+
6123
+
6124
+
6125
+	/**
6126
+	 * Returns all valid options for 'default_where_conditions'
6127
+	 *
6128
+	 * @return array
6129
+	 */
6130
+	public static function valid_default_where_conditions()
6131
+	{
6132
+		return array(
6133
+			EEM_Base::default_where_conditions_all,
6134
+			EEM_Base::default_where_conditions_this_only,
6135
+			EEM_Base::default_where_conditions_others_only,
6136
+			EEM_Base::default_where_conditions_minimum_all,
6137
+			EEM_Base::default_where_conditions_minimum_others,
6138
+			EEM_Base::default_where_conditions_none
6139
+		);
6140
+	}
6141
+
6142
+	// public static function default_where_conditions_full
6143
+	/**
6144
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6145
+	 *
6146
+	 * @param string $context
6147
+	 * @return bool
6148
+	 * @throws EE_Error
6149
+	 */
6150
+	static public function verify_is_valid_cap_context($context)
6151
+	{
6152
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6153
+		if (in_array($context, $valid_cap_contexts)) {
6154
+			return true;
6155
+		}
6156
+		throw new EE_Error(
6157
+			sprintf(
6158
+				__(
6159
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6160
+					'event_espresso'
6161
+				),
6162
+				$context,
6163
+				'EEM_Base',
6164
+				implode(',', $valid_cap_contexts)
6165
+			)
6166
+		);
6167
+	}
6168
+
6169
+
6170
+
6171
+	/**
6172
+	 * Clears all the models field caches. This is only useful when a sub-class
6173
+	 * might have added a field or something and these caches might be invalidated
6174
+	 */
6175
+	protected function _invalidate_field_caches()
6176
+	{
6177
+		$this->_cache_foreign_key_to_fields = array();
6178
+		$this->_cached_fields = null;
6179
+		$this->_cached_fields_non_db_only = null;
6180
+	}
6181
+
6182
+
6183
+
6184
+	/**
6185
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6186
+	 * (eg "and", "or", "not").
6187
+	 *
6188
+	 * @return array
6189
+	 */
6190
+	public function logic_query_param_keys()
6191
+	{
6192
+		return $this->_logic_query_param_keys;
6193
+	}
6194
+
6195
+
6196
+
6197
+	/**
6198
+	 * Determines whether or not the where query param array key is for a logic query param.
6199
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6200
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6201
+	 *
6202
+	 * @param $query_param_key
6203
+	 * @return bool
6204
+	 */
6205
+	public function is_logic_query_param_key($query_param_key)
6206
+	{
6207
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6208
+			if ($query_param_key === $logic_query_param_key
6209
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6210
+			) {
6211
+				return true;
6212
+			}
6213
+		}
6214
+		return false;
6215
+	}
6216 6216
 
6217 6217
 
6218 6218
 
Please login to merge, or discard this patch.