Completed
Branch BUG-10144-query-quotes (e5d611)
by
unknown
37:22 queued 18:36
created
core/data_migration_scripts/EE_DMS_Core_4_1_0.dms.php 1 patch
Spacing   +206 added lines, -206 removed lines patch added patch discarded remove patch
@@ -11,15 +11,15 @@  discard block
 block discarded – undo
11 11
 //(all other times it gets resurrected from a wordpress option)
12 12
 $stages = glob(EE_CORE.'data_migration_scripts/4_1_0_stages/*');
13 13
 $class_to_filepath = array();
14
-if ( ! empty( $stages ) ) {
15
-	foreach($stages as $filepath){
14
+if ( ! empty($stages)) {
15
+	foreach ($stages as $filepath) {
16 16
 		$matches = array();
17
-		preg_match('~4_1_0_stages/(.*).dmsstage.php~',$filepath,$matches);
17
+		preg_match('~4_1_0_stages/(.*).dmsstage.php~', $filepath, $matches);
18 18
 		$class_to_filepath[$matches[1]] = $filepath;
19 19
 	}
20 20
 }
21 21
 //give addons a chance to autoload their stages too
22
-$class_to_filepath = apply_filters('FHEE__EE_DMS_4_1_0__autoloaded_stages',$class_to_filepath);
22
+$class_to_filepath = apply_filters('FHEE__EE_DMS_4_1_0__autoloaded_stages', $class_to_filepath);
23 23
 EEH_Autoloader::register_autoloader($class_to_filepath);
24 24
 
25 25
 /**
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
  * --a function named update_espresso_config() which saves the EE_Config object to the database
38 38
  * --...and all its subclasses... really, you're best off copying the whole thing when 4.1 is released into this file and wrapping its declaration in if( ! class_exists()){...}
39 39
  */
40
-class EE_DMS_Core_4_1_0 extends EE_Data_Migration_Script_Base{
40
+class EE_DMS_Core_4_1_0 extends EE_Data_Migration_Script_Base {
41 41
 
42 42
 
43 43
 
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
 	 * @param TableManager  $table_manager
48 48
 	 * @param TableAnalysis $table_analysis
49 49
 	 */
50
-	public function __construct( TableManager $table_manager = null, TableAnalysis $table_analysis = null ) {
50
+	public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null) {
51 51
 		$this->_pretty_name = __("Data Migration to Event Espresso 4.1.0P", "event_espresso");
52 52
 		$this->_priority = 10;
53 53
 		$this->_migration_stages = array(
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
 			new EE_DMS_4_1_0_answers(),
70 70
 			new EE_DMS_4_1_0_checkins(),
71 71
 		);
72
-		parent::__construct( $table_manager, $table_analysis );
72
+		parent::__construct($table_manager, $table_analysis);
73 73
 	}
74 74
 	/**
75 75
 	 * Checks if this 3.1 Check-in table exists. If it doesn't we can't migrate Check-ins
@@ -77,27 +77,27 @@  discard block
 block discarded – undo
77 77
 	 * @global wpdb $wpdb
78 78
 	 * @return boolean
79 79
 	 */
80
-	private function _checkin_table_exists(){
80
+	private function _checkin_table_exists() {
81 81
 		global $wpdb;
82 82
 		$results = $wpdb->get_results("SHOW TABLES LIKE '".$wpdb->prefix."events_attendee_checkin"."'");
83
-		if($results){
83
+		if ($results) {
84 84
 			return true;
85
-		}else{
85
+		} else {
86 86
 			return false;
87 87
 		}
88 88
 	}
89 89
 
90 90
 	public function can_migrate_from_version($version_array) {
91 91
 		$version_string = $version_array['Core'];
92
-		if ( version_compare( $version_string, '4.0.0', '<=' ) && version_compare( $version_string, '3.1.26', '>=' ) ) {
92
+		if (version_compare($version_string, '4.0.0', '<=') && version_compare($version_string, '3.1.26', '>=')) {
93 93
 //			echo "$version_string can be migrated fro";
94 94
 			return true;
95
-		}elseif( ! $version_string ){
95
+		}elseif ( ! $version_string) {
96 96
 //			echo "no version string provided: $version_string";
97 97
 			//no version string provided... this must be pre 4.1
98 98
 			//because since 4.1 we're
99
-			return false;//changed mind. dont want people thinking they should migrate yet because they cant
100
-		}else{
99
+			return false; //changed mind. dont want people thinking they should migrate yet because they cant
100
+		} else {
101 101
 //			echo "$version_string doesnt apply";
102 102
 			return false;
103 103
 		}
@@ -107,15 +107,15 @@  discard block
 block discarded – undo
107 107
 	}
108 108
 	public function schema_changes_before_migration() {
109 109
 		//relies on 4.1's EEH_Activation::create_table
110
-		require_once( EE_HELPERS . 'EEH_Activation.helper.php' );
110
+		require_once(EE_HELPERS.'EEH_Activation.helper.php');
111 111
 
112
-		$table_name='esp_answer';
113
-		$sql=" ANS_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
112
+		$table_name = 'esp_answer';
113
+		$sql = " ANS_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
114 114
 					REG_ID INT UNSIGNED NOT NULL,
115 115
 					QST_ID INT UNSIGNED NOT NULL,
116 116
 					ANS_value TEXT NOT NULL,
117 117
 					PRIMARY KEY  (ANS_ID)";
118
-		$this->_table_is_new_in_this_version($table_name,$sql, 'ENGINE=InnoDB');
118
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
119 119
 
120 120
 		$table_name = 'esp_attendee_meta';
121 121
 		$sql = "ATTM_ID INT(10) UNSIGNED NOT	NULL AUTO_INCREMENT,
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 					  CNT_is_EU TINYINT(1) DEFAULT '0',
156 156
 					  CNT_active TINYINT(1) DEFAULT '0',
157 157
 					  PRIMARY KEY  (CNT_ISO)";
158
-		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB' );
158
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
159 159
 
160 160
 
161 161
 
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 
177 177
 
178 178
 
179
-		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB' );
179
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
180 180
 		$table_name = 'esp_event_meta';
181 181
 		$sql = "
182 182
 			EVTM_ID INT NOT NULL AUTO_INCREMENT,
@@ -193,41 +193,41 @@  discard block
 block discarded – undo
193 193
 			EVT_external_URL VARCHAR(200) NULL,
194 194
 			EVT_donations TINYINT(1) NULL,
195 195
 			PRIMARY KEY  (EVTM_ID)";
196
-		$this->_table_is_new_in_this_version($table_name,$sql, 'ENGINE=InnoDB');
196
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
197 197
 
198 198
 
199 199
 
200
-		$table_name='esp_event_question_group';
201
-		$sql="EQG_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
200
+		$table_name = 'esp_event_question_group';
201
+		$sql = "EQG_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
202 202
 					EVT_ID BIGINT(20) UNSIGNED NOT NULL,
203 203
 					QSG_ID INT UNSIGNED NOT NULL,
204 204
 					EQG_primary TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
205 205
 					PRIMARY KEY  (EQG_ID)";
206
-		$this->_table_is_new_in_this_version($table_name,$sql, 'ENGINE=InnoDB');
206
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
207 207
 
208 208
 
209 209
 
210
-		$table_name='esp_event_venue';
211
-		$sql="EVV_ID INT(11) NOT NULL AUTO_INCREMENT,
210
+		$table_name = 'esp_event_venue';
211
+		$sql = "EVV_ID INT(11) NOT NULL AUTO_INCREMENT,
212 212
 				EVT_ID BIGINT(20) UNSIGNED NOT NULL,
213 213
 				VNU_ID BIGINT(20) UNSIGNED NOT NULL,
214 214
 				EVV_primary TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
215 215
 				PRIMARY KEY  (EVV_ID)";
216
-		$this->_table_is_new_in_this_version($table_name,$sql, 'ENGINE=InnoDB');
216
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
217 217
 
218 218
 
219 219
 
220
-		$table_name='esp_extra_meta';
221
-		$sql="EXM_ID INT(11) NOT NULL AUTO_INCREMENT,
220
+		$table_name = 'esp_extra_meta';
221
+		$sql = "EXM_ID INT(11) NOT NULL AUTO_INCREMENT,
222 222
 				OBJ_ID INT(11) DEFAULT NULL,
223 223
 				EXM_type VARCHAR(45) DEFAULT NULL,
224 224
 				EXM_key VARCHAR(45) DEFAULT NULL,
225 225
 				EXM_value TEXT,
226 226
 				PRIMARY KEY  (EXM_ID)";
227
-		$this->_table_is_new_in_this_version($table_name,$sql, 'ENGINE=InnoDB');
227
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
228 228
 
229
-		$table_name='esp_line_item';
230
-		$sql="LIN_ID INT(11) NOT NULL AUTO_INCREMENT,
229
+		$table_name = 'esp_line_item';
230
+		$sql = "LIN_ID INT(11) NOT NULL AUTO_INCREMENT,
231 231
 				LIN_code VARCHAR(245) NOT NULL DEFAULT '',
232 232
 				TXN_ID INT(11) DEFAULT NULL,
233 233
 				LIN_name VARCHAR(245) NOT NULL DEFAULT '',
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
 				OBJ_ID INT(11) DEFAULT NULL,
244 244
 				OBJ_type VARCHAR(45)DEFAULT NULL,
245 245
 				PRIMARY KEY  (LIN_ID)";
246
-		$this->_table_is_new_in_this_version($table_name,$sql, 'ENGINE=InnoDB' );
246
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
247 247
 
248 248
 		$table_name = 'esp_message_template';
249 249
 		$sql = "MTP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
@@ -270,7 +270,7 @@  discard block
 block discarded – undo
270 270
 					PRIMARY KEY  (GRP_ID),
271 271
 					KEY EVT_ID (EVT_ID),
272 272
 					KEY MTP_user_id (MTP_user_id)";
273
-		$this->_table_is_new_in_this_version( $table_name, $sql, 'ENGINE=InnoDB');
273
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
274 274
 
275 275
 
276 276
 
@@ -378,8 +378,8 @@  discard block
 block discarded – undo
378 378
 
379 379
 
380 380
 
381
-		$table_name='esp_question';
382
-		$sql='QST_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
381
+		$table_name = 'esp_question';
382
+		$sql = 'QST_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
383 383
 					QST_display_text TEXT NOT NULL,
384 384
 					QST_admin_label VARCHAR(255) NOT NULL,
385 385
 					QST_system VARCHAR(25) DEFAULT NULL,
@@ -391,12 +391,12 @@  discard block
 block discarded – undo
391 391
 					QST_wp_user BIGINT UNSIGNED NULL,
392 392
 					QST_deleted TINYINT UNSIGNED NOT NULL DEFAULT 0,
393 393
 					PRIMARY KEY  (QST_ID)';
394
-		$this->_table_is_new_in_this_version($table_name,$sql, 'ENGINE=InnoDB');
394
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
395 395
 
396
-		$this->_get_table_manager()->dropIndex( 'esp_question_group', 'QSG_identifier_UNIQUE' );
396
+		$this->_get_table_manager()->dropIndex('esp_question_group', 'QSG_identifier_UNIQUE');
397 397
 
398 398
 		$table_name = 'esp_question_group';
399
-		$sql='QSG_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
399
+		$sql = 'QSG_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
400 400
 					QSG_name VARCHAR(255) NOT NULL,
401 401
 					QSG_identifier VARCHAR(100) NOT NULL,
402 402
 					QSG_desc TEXT NULL,
@@ -407,27 +407,27 @@  discard block
 block discarded – undo
407 407
 					QSG_deleted TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
408 408
 					PRIMARY KEY  (QSG_ID),
409 409
 					UNIQUE KEY QSG_identifier_UNIQUE (QSG_identifier ASC)';
410
-		$this->_table_is_new_in_this_version($table_name,$sql, 'ENGINE=InnoDB');
410
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
411 411
 
412 412
 
413 413
 
414
-		$table_name='esp_question_group_question';
415
-		$sql="QGQ_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
414
+		$table_name = 'esp_question_group_question';
415
+		$sql = "QGQ_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
416 416
 					QSG_ID INT UNSIGNED NOT NULL,
417 417
 					QST_ID INT UNSIGNED NOT NULL,
418 418
 					PRIMARY KEY  (QGQ_ID) ";
419
-		$this->_table_is_new_in_this_version($table_name,$sql, 'ENGINE=InnoDB');
419
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
420 420
 
421 421
 
422 422
 
423
-		$table_name='esp_question_option';
424
-		$sql="QSO_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
423
+		$table_name = 'esp_question_option';
424
+		$sql = "QSO_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
425 425
 					QSO_value VARCHAR(255) NOT NULL,
426 426
 					QSO_desc TEXT NOT NULL,
427 427
 					QST_ID INT UNSIGNED NOT NULL,
428 428
 					QSO_deleted TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
429 429
 					PRIMARY KEY  (QSO_ID)";
430
-		$this->_table_is_new_in_this_version($table_name,$sql, 'ENGINE=InnoDB');
430
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
431 431
 
432 432
 
433 433
 
@@ -460,8 +460,8 @@  discard block
 block discarded – undo
460 460
 
461 461
 
462 462
 
463
-		$table_name='esp_checkin';
464
-		$sql="CHK_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
463
+		$table_name = 'esp_checkin';
464
+		$sql = "CHK_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
465 465
 					REG_ID INT(10) UNSIGNED NOT NULL,
466 466
 					DTT_ID INT(10) UNSIGNED NOT NULL,
467 467
 					CHK_in TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
@@ -568,12 +568,12 @@  discard block
 block discarded – undo
568 568
 
569 569
 		global $wpdb;
570 570
 		$state_table = $wpdb->prefix."esp_state";
571
-		if ( $this->_get_table_analysis()->tableExists( $state_table ) ) {
571
+		if ($this->_get_table_analysis()->tableExists($state_table)) {
572 572
 
573
-			$SQL = "SELECT COUNT('STA_ID') FROM " . $state_table;
573
+			$SQL = "SELECT COUNT('STA_ID') FROM ".$state_table;
574 574
 			$states = $wpdb->get_var($SQL);
575
-			if ( ! $states ) {
576
-				$SQL = "INSERT INTO " . $state_table . "
575
+			if ( ! $states) {
576
+				$SQL = "INSERT INTO ".$state_table."
577 577
 				(STA_ID, CNT_ISO, STA_abbrev, STA_name, STA_active) VALUES
578 578
 				(1, 'US', 'AK', 'Alaska', 1),
579 579
 				(2, 'US', 'AL', 'Alabama', 1),
@@ -660,12 +660,12 @@  discard block
 block discarded – undo
660 660
 
661 661
 		global $wpdb;
662 662
 		$country_table = $wpdb->prefix."esp_country";
663
-		if ( $this->_get_table_analysis()->tableExists( $country_table ) ) {
663
+		if ($this->_get_table_analysis()->tableExists($country_table)) {
664 664
 
665
-			$SQL = "SELECT COUNT('CNT_ISO') FROM " . $country_table;
665
+			$SQL = "SELECT COUNT('CNT_ISO') FROM ".$country_table;
666 666
 			$countries = $wpdb->get_var($SQL);
667
-			if ( ! $countries ) {
668
-				$SQL = "INSERT INTO " . $country_table . "
667
+			if ( ! $countries) {
668
+				$SQL = "INSERT INTO ".$country_table."
669 669
 				(CNT_ISO, CNT_ISO3, RGN_ID, CNT_name, CNT_cur_code, CNT_cur_single, CNT_cur_plural, CNT_cur_sign, CNT_cur_sign_b4, CNT_cur_dec_plc, CNT_tel_code, CNT_is_EU, CNT_active) VALUES
670 670
 				('AD', 'AND', 0, 'Andorra', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+376', 0, 0),
671 671
 				('AE', 'ARE', 0, 'United Arab Emirates', 'AED', 'Dirham', 'Dirhams', 'د.إ', 1, 2, '+971', 0, 0),
@@ -912,20 +912,20 @@  discard block
 block discarded – undo
912 912
 		global $wpdb;
913 913
 		$price_type_table = $wpdb->prefix."esp_price_type";
914 914
 
915
-		if ( $this->_get_table_analysis()->tableExists( $price_type_table ) ) {
915
+		if ($this->_get_table_analysis()->tableExists($price_type_table)) {
916 916
 
917
-			$SQL = 'SELECT COUNT(PRT_ID) FROM ' . $price_type_table;
918
-			$price_types_exist = $wpdb->get_var( $SQL );
917
+			$SQL = 'SELECT COUNT(PRT_ID) FROM '.$price_type_table;
918
+			$price_types_exist = $wpdb->get_var($SQL);
919 919
 
920
-			if ( ! $price_types_exist ) {
920
+			if ( ! $price_types_exist) {
921 921
 				$SQL = "INSERT INTO $price_type_table ( PRT_ID, PRT_name, PBT_ID, PRT_is_percent, PRT_order, PRT_deleted ) VALUES
922
-							(1, '" . __('Base Price', 'event_espresso') . "', 1,  0, 0, 0),
923
-							(2, '" . __('Percent Discount', 'event_espresso') . "', 2,  1, 20, 0),
924
-							(3, '" . __('Fixed Discount', 'event_espresso') . "', 2,  0, 30, 0),
925
-							(4, '" . __('Percent Surcharge', 'event_espresso') . "', 3,  1, 40, 0),
926
-							(5, '" . __('Fixed Surcharge', 'event_espresso') . "', 3,  0, 50, 0);";
927
-				$SQL = apply_filters( 'FHEE__EE_DMS_4_1_0__insert_default_price_types__SQL', $SQL );
928
-				$wpdb->query( $SQL );
922
+							(1, '".__('Base Price', 'event_espresso')."', 1,  0, 0, 0),
923
+							(2, '" . __('Percent Discount', 'event_espresso')."', 2,  1, 20, 0),
924
+							(3, '" . __('Fixed Discount', 'event_espresso')."', 2,  0, 30, 0),
925
+							(4, '" . __('Percent Surcharge', 'event_espresso')."', 3,  1, 40, 0),
926
+							(5, '" . __('Fixed Surcharge', 'event_espresso')."', 3,  0, 50, 0);";
927
+				$SQL = apply_filters('FHEE__EE_DMS_4_1_0__insert_default_price_types__SQL', $SQL);
928
+				$wpdb->query($SQL);
929 929
 			}
930 930
 		}
931 931
 	}
@@ -945,16 +945,16 @@  discard block
 block discarded – undo
945 945
 		global $wpdb;
946 946
 		$price_table = $wpdb->prefix."esp_price";
947 947
 
948
-		if ( $this->_get_table_analysis()->tableExists(  $price_table ) ) {
948
+		if ($this->_get_table_analysis()->tableExists($price_table)) {
949 949
 
950
-			$SQL = 'SELECT COUNT(PRC_ID) FROM ' .$price_table;
951
-			$prices_exist = $wpdb->get_var( $SQL );
950
+			$SQL = 'SELECT COUNT(PRC_ID) FROM '.$price_table;
951
+			$prices_exist = $wpdb->get_var($SQL);
952 952
 
953
-			if ( ! $prices_exist ) {
953
+			if ( ! $prices_exist) {
954 954
 				$SQL = "INSERT INTO $price_table
955 955
 							(PRC_ID, PRT_ID, PRC_amount, PRC_name, PRC_desc,  PRC_is_default, PRC_overrides, PRC_order, PRC_deleted, PRC_parent ) VALUES
956 956
 							(1, 1, '0.00', 'Free Admission', '', 1, NULL, 0, 0, 0);";
957
-				$SQL = apply_filters( 'FHEE__EE_DMS_4_1_0__insert_default_prices__SQL', $SQL );
957
+				$SQL = apply_filters('FHEE__EE_DMS_4_1_0__insert_default_prices__SQL', $SQL);
958 958
 				$wpdb->query($SQL);
959 959
 			}
960 960
 		}
@@ -971,34 +971,34 @@  discard block
 block discarded – undo
971 971
 
972 972
 		global $wpdb;
973 973
 		$ticket_table = $wpdb->prefix."esp_ticket";
974
-		if ( $this->_get_table_analysis()->tableExists( $ticket_table ) ) {
974
+		if ($this->_get_table_analysis()->tableExists($ticket_table)) {
975 975
 
976
-			$SQL = 'SELECT COUNT(TKT_ID) FROM ' . $ticket_table;
976
+			$SQL = 'SELECT COUNT(TKT_ID) FROM '.$ticket_table;
977 977
 			$tickets_exist = $wpdb->get_var($SQL);
978 978
 
979
-			if ( ! $tickets_exist ) {
979
+			if ( ! $tickets_exist) {
980 980
 				$SQL = "INSERT INTO $ticket_table
981 981
 					( TKT_ID, TTM_ID, TKT_name, TKT_description, TKT_qty, TKT_sold, TKT_uses, TKT_min, TKT_max, TKT_price, TKT_start_date, TKT_end_date, TKT_taxable, TKT_order, TKT_row, TKT_is_default, TKT_parent, TKT_deleted ) VALUES
982
-					( 1, 0, '" . __("Free Ticket", "event_espresso") . "', '', 100, 0, -1, 0, -1, 0.00, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0, 0, 1, 1, 0, 0);";
983
-				$SQL = apply_filters( 'FHEE__EE_DMS_4_1_0__insert_default_tickets__SQL', $SQL );
982
+					( 1, 0, '".__("Free Ticket", "event_espresso")."', '', 100, 0, -1, 0, -1, 0.00, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0, 0, 1, 1, 0, 0);";
983
+				$SQL = apply_filters('FHEE__EE_DMS_4_1_0__insert_default_tickets__SQL', $SQL);
984 984
 				$wpdb->query($SQL);
985 985
 			}
986 986
 		}
987 987
 		$ticket_price_table = $wpdb->prefix."esp_ticket_price";
988 988
 
989
-		if ( $this->_get_table_analysis()->tableExists( $ticket_price_table ) ) {
989
+		if ($this->_get_table_analysis()->tableExists($ticket_price_table)) {
990 990
 
991
-			$SQL = 'SELECT COUNT(TKP_ID) FROM ' . $ticket_price_table;
991
+			$SQL = 'SELECT COUNT(TKP_ID) FROM '.$ticket_price_table;
992 992
 			$ticket_prc_exist = $wpdb->get_var($SQL);
993 993
 
994
-			if ( ! $ticket_prc_exist ) {
994
+			if ( ! $ticket_prc_exist) {
995 995
 
996 996
 				$SQL = "INSERT INTO $ticket_price_table
997 997
 				( TKP_ID, TKT_ID, PRC_ID ) VALUES
998 998
 				( 1, 1, 1 )
999 999
 				";
1000 1000
 
1001
-				$SQL = apply_filters( 'FHEE__EE_DMS_4_1_0__insert_default_tickets__SQL__ticket_price', $SQL );
1001
+				$SQL = apply_filters('FHEE__EE_DMS_4_1_0__insert_default_tickets__SQL__ticket_price', $SQL);
1002 1002
 				$wpdb->query($SQL);
1003 1003
 			}
1004 1004
 		}
@@ -1011,20 +1011,20 @@  discard block
 block discarded – undo
1011 1011
 	 * @param string $country_name
1012 1012
 	 * @return array where keys are columns, values are column values
1013 1013
 	 */
1014
-	public function get_or_create_country($country_name){
1015
-		if( ! $country_name ){
1014
+	public function get_or_create_country($country_name) {
1015
+		if ( ! $country_name) {
1016 1016
 			throw new EE_Error(__("Could not get a country because country name is blank", "event_espresso"));
1017 1017
 		}
1018 1018
 		global $wpdb;
1019 1019
 		$country_table = $wpdb->prefix."esp_country";
1020
-		if(is_int($country_name)){
1020
+		if (is_int($country_name)) {
1021 1021
 			$country_name = $this->get_iso_from_3_1_country_id($country_name);
1022 1022
 		}
1023 1023
 		$country = $wpdb->get_row($wpdb->prepare("SELECT * FROM $country_table WHERE
1024 1024
 			CNT_ISO LIKE %s OR
1025 1025
 			CNT_ISO3 LIKE %s OR
1026
-			CNT_name LIKE %s LIMIT 1",$country_name,$country_name,$country_name),ARRAY_A);
1027
-		if( ! $country ){
1026
+			CNT_name LIKE %s LIMIT 1", $country_name, $country_name, $country_name), ARRAY_A);
1027
+		if ( ! $country) {
1028 1028
 			//insert a new one then
1029 1029
 			$cols_n_values = array(
1030 1030
 				'CNT_ISO'=> $this->_find_available_country_iso(2),
@@ -1044,26 +1044,26 @@  discard block
 block discarded – undo
1044 1044
 				'CNT_active'=>true
1045 1045
 			);
1046 1046
 			$data_types = array(
1047
-				'%s',//CNT_ISO
1048
-				'%s',//CNT_ISO3
1049
-				'%d',//RGN_ID
1050
-				'%s',//CNT_name
1051
-				'%s',//CNT_cur_code
1052
-				'%s',//CNT_cur_single
1053
-				'%s',//CNT_cur_plural
1054
-				'%s',//CNT_cur_sign
1055
-				'%d',//CNT_cur_sign_b4
1056
-				'%d',//CNT_cur_dec_plc
1057
-				'%s',//CNT_cur_dec_mrk
1058
-				'%s',//CNT_cur_thsnds
1059
-				'%s',//CNT_tel_code
1060
-				'%d',//CNT_is_EU
1061
-				'%d',//CNT_active
1047
+				'%s', //CNT_ISO
1048
+				'%s', //CNT_ISO3
1049
+				'%d', //RGN_ID
1050
+				'%s', //CNT_name
1051
+				'%s', //CNT_cur_code
1052
+				'%s', //CNT_cur_single
1053
+				'%s', //CNT_cur_plural
1054
+				'%s', //CNT_cur_sign
1055
+				'%d', //CNT_cur_sign_b4
1056
+				'%d', //CNT_cur_dec_plc
1057
+				'%s', //CNT_cur_dec_mrk
1058
+				'%s', //CNT_cur_thsnds
1059
+				'%s', //CNT_tel_code
1060
+				'%d', //CNT_is_EU
1061
+				'%d', //CNT_active
1062 1062
 			);
1063 1063
 			$success = $wpdb->insert($country_table,
1064 1064
 					$cols_n_values,
1065 1065
 					$data_types);
1066
-			if( ! $success){
1066
+			if ( ! $success) {
1067 1067
 				throw new EE_Error($this->_create_error_message_for_db_insertion('N/A', array('country_id'=>$country_name), $country_table, $cols_n_values, $data_types));
1068 1068
 			}
1069 1069
 			$country = $cols_n_values;
@@ -1075,18 +1075,18 @@  discard block
 block discarded – undo
1075 1075
 	 * @global type $wpdb
1076 1076
 	 * @return string
1077 1077
 	 */
1078
-	private function _find_available_country_iso($num_letters = 2){
1078
+	private function _find_available_country_iso($num_letters = 2) {
1079 1079
 		global $wpdb;
1080 1080
 		$country_table = $wpdb->prefix."esp_country";
1081 1081
 		$attempts = 0;
1082
-		do{
1082
+		do {
1083 1083
 			$current_iso = strtoupper(wp_generate_password($num_letters, false));
1084
-			$country_with_that_iso = $wpdb->get_var($wpdb->prepare("SELECT count(CNT_ISO) FROM ".$country_table." WHERE CNT_ISO=%s",$current_iso));
1084
+			$country_with_that_iso = $wpdb->get_var($wpdb->prepare("SELECT count(CNT_ISO) FROM ".$country_table." WHERE CNT_ISO=%s", $current_iso));
1085 1085
 			$attempts++;
1086 1086
 		//keep going until we find an available country code, or we arbitrarily
1087 1087
 		//decide we've tried this enough. Somehow they have way too many countries
1088 1088
 		//(probably because they're mis-using the EE3 country_id like a custom question)
1089
-		}while( intval($country_with_that_iso) && $attempts < 200 );
1089
+		}while (intval($country_with_that_iso) && $attempts < 200);
1090 1090
 		return $current_iso;
1091 1091
 	}
1092 1092
 
@@ -1097,14 +1097,14 @@  discard block
 block discarded – undo
1097 1097
 	 * @param string $state_name
1098 1098
 	 * @return array where keys are columns, values are column values
1099 1099
 	 */
1100
-	public function get_or_create_state($state_name,$country_name = ''){
1101
-		if( ! $state_name ){
1100
+	public function get_or_create_state($state_name, $country_name = '') {
1101
+		if ( ! $state_name) {
1102 1102
 			throw new EE_Error(__("Could not get-or-create state because no state name was provided", "event_espresso"));
1103 1103
 		}
1104
-		try{
1104
+		try {
1105 1105
 			$country = $this->get_or_create_country($country_name);
1106 1106
 			$country_iso = $country['CNT_ISO'];
1107
-		}catch(EE_Error $e){
1107
+		} catch (EE_Error $e) {
1108 1108
 			$country_iso = $this->get_default_country_iso();
1109 1109
 		}
1110 1110
 		global $wpdb;
@@ -1112,24 +1112,24 @@  discard block
 block discarded – undo
1112 1112
 		$state = $wpdb->get_row($wpdb->prepare("SELECT * FROM $state_table WHERE
1113 1113
 			(STA_abbrev LIKE %s OR
1114 1114
 			STA_name LIKE %s) AND
1115
-			CNT_ISO LIKE %s LIMIT 1",$state_name,$state_name,$country_iso),ARRAY_A);
1116
-		if ( ! $state){
1115
+			CNT_ISO LIKE %s LIMIT 1", $state_name, $state_name, $country_iso), ARRAY_A);
1116
+		if ( ! $state) {
1117 1117
 			//insert a new one then
1118 1118
 			$cols_n_values = array(
1119 1119
 				'CNT_ISO'=>$country_iso,
1120
-				'STA_abbrev'=>substr($state_name,0,6),
1120
+				'STA_abbrev'=>substr($state_name, 0, 6),
1121 1121
 				'STA_name'=>$state_name,
1122 1122
 				'STA_active'=>true
1123 1123
 			);
1124 1124
 			$data_types = array(
1125
-				'%s',//CNT_ISO
1126
-				'%s',//STA_abbrev
1127
-				'%s',//STA_name
1128
-				'%d',//STA_active
1125
+				'%s', //CNT_ISO
1126
+				'%s', //STA_abbrev
1127
+				'%s', //STA_name
1128
+				'%d', //STA_active
1129 1129
 			);
1130
-			$success = $wpdb->insert($state_table,$cols_n_values,$data_types);
1131
-			if ( ! $success ){
1132
-				throw new EE_Error($this->_create_error_message_for_db_insertion('N/A', array('state'=>$state_name,'country_id'=>$country_name), $state_table, $cols_n_values, $data_types));
1130
+			$success = $wpdb->insert($state_table, $cols_n_values, $data_types);
1131
+			if ( ! $success) {
1132
+				throw new EE_Error($this->_create_error_message_for_db_insertion('N/A', array('state'=>$state_name, 'country_id'=>$country_name), $state_table, $cols_n_values, $data_types));
1133 1133
 			}
1134 1134
 			$state = $cols_n_values;
1135 1135
 			$state['STA_ID'] = $wpdb->insert_id;
@@ -1142,21 +1142,21 @@  discard block
 block discarded – undo
1142 1142
 	 * @param type $timeString
1143 1143
 	 * @return string in the php DATETIME format: "G:i" (24-hour format hour with leading zeros, a colon, and minutes with leading zeros)
1144 1144
 	 */
1145
-	public function convertTimeFromAMPM($timeString){
1145
+	public function convertTimeFromAMPM($timeString) {
1146 1146
 		$matches = array();
1147
-		preg_match("~(\\d*):(\\d*)~",$timeString,$matches);
1148
-		if( ! $matches || count($matches)<3){
1147
+		preg_match("~(\\d*):(\\d*)~", $timeString, $matches);
1148
+		if ( ! $matches || count($matches) < 3) {
1149 1149
 			$hour = '00';
1150 1150
 			$minutes = '00';
1151
-		}else{
1151
+		} else {
1152 1152
 			$hour = intval($matches[1]);
1153 1153
 			$minutes = $matches[2];
1154 1154
 		}
1155
-		if(strpos($timeString, 'PM') || strpos($timeString, 'pm')){
1155
+		if (strpos($timeString, 'PM') || strpos($timeString, 'pm')) {
1156 1156
 			$hour = intval($hour) + 12;
1157 1157
 		}
1158
-		$hour = str_pad( "$hour", 2, '0',STR_PAD_LEFT);
1159
-		$minutes = str_pad( "$minutes", 2, '0',STR_PAD_LEFT);
1158
+		$hour = str_pad("$hour", 2, '0', STR_PAD_LEFT);
1159
+		$minutes = str_pad("$minutes", 2, '0', STR_PAD_LEFT);
1160 1160
 		return "$hour:$minutes";
1161 1161
 	}
1162 1162
 
@@ -1165,7 +1165,7 @@  discard block
 block discarded – undo
1165 1165
 	 * @param int $country_id
1166 1166
 	 * @return string the country's ISO3 code
1167 1167
 	 */
1168
-	public function get_iso_from_3_1_country_id($country_id){
1168
+	public function get_iso_from_3_1_country_id($country_id) {
1169 1169
 		$old_countries = array(
1170 1170
 			array(64, 'United States', 'US', 'USA', 1),
1171 1171
 			array(15, 'Australia', 'AU', 'AUS', 1),
@@ -1391,9 +1391,9 @@  discard block
 block discarded – undo
1391 1391
 			array(226, 'Zimbabwe', 'ZW', 'ZWE', 1));
1392 1392
 
1393 1393
 		$country_iso = 'US';
1394
-		foreach($old_countries as $country_array){
1394
+		foreach ($old_countries as $country_array) {
1395 1395
 			//note: index 0 is the 3.1 country ID
1396
-			if($country_array[0] == $country_id){
1396
+			if ($country_array[0] == $country_id) {
1397 1397
 				//note: index 2 is the ISO
1398 1398
 				$country_iso = $country_array[2];
1399 1399
 				break;
@@ -1406,8 +1406,8 @@  discard block
 block discarded – undo
1406 1406
 	 * Gets the ISO3 for the
1407 1407
 	 * @return string
1408 1408
 	 */
1409
-	public function get_default_country_iso(){
1410
-		$old_org_options= get_option('events_organization_settings');
1409
+	public function get_default_country_iso() {
1410
+		$old_org_options = get_option('events_organization_settings');
1411 1411
 		$iso = $this->get_iso_from_3_1_country_id($old_org_options['organization_country']);
1412 1412
 		return $iso;
1413 1413
 	}
@@ -1419,13 +1419,13 @@  discard block
 block discarded – undo
1419 1419
 	 * the event's DEFAULT payment status, or the attendee's payment status) required pre-approval.
1420 1420
 	 * @return string STS_ID for use in 4.1
1421 1421
 	 */
1422
-	public function convert_3_1_payment_status_to_4_1_STS_ID($payment_status, $this_thing_required_pre_approval = false){
1422
+	public function convert_3_1_payment_status_to_4_1_STS_ID($payment_status, $this_thing_required_pre_approval = false) {
1423 1423
 
1424 1424
 		//EE team can read the related discussion: https://app.asana.com/0/2400967562914/9418495544455
1425
-		if($this_thing_required_pre_approval){
1425
+		if ($this_thing_required_pre_approval) {
1426 1426
 				return 'RNA';
1427
-		}else{
1428
-				$mapping = $default_reg_stati_conversions=array(
1427
+		} else {
1428
+				$mapping = $default_reg_stati_conversions = array(
1429 1429
 			'Completed'=>'RAP',
1430 1430
 			''=>'RPP',
1431 1431
 			'Incomplete'=>'RPP',
@@ -1455,22 +1455,22 @@  discard block
 block discarded – undo
1455 1455
 	 * @param  EE_Data_Migration_Script_Stage $migration_stage the stage which called this, where errors should be added
1456 1456
 	 * @return boolean whether or not we had to do the big job of creating an image attachment
1457 1457
 	 */
1458
-	public function convert_image_url_to_attachment_and_attach_to_post($guid,$new_cpt_id,  EE_Data_Migration_Script_Stage $migration_stage){
1458
+	public function convert_image_url_to_attachment_and_attach_to_post($guid, $new_cpt_id, EE_Data_Migration_Script_Stage $migration_stage) {
1459 1459
 		$created_attachment_post = false;
1460 1460
 		$guid = $this->_get_original_guid($guid);
1461
-		if($guid){
1461
+		if ($guid) {
1462 1462
 			//check for an existing attachment post with this guid
1463 1463
 			$attachment_post_id = $this->_get_image_attachment_id_by_GUID($guid);
1464
-			if( ! $attachment_post_id){
1464
+			if ( ! $attachment_post_id) {
1465 1465
 				//post thumbnail with that GUID doesn't exist, we should create one
1466 1466
 				$attachment_post_id = $this->_create_image_attachment_from_GUID($guid, $migration_stage);
1467 1467
 				$created_attachment_post = true;
1468 1468
 			}
1469 1469
 			//double-check we actually have an attachment post
1470
-			if( $attachment_post_id){
1471
-				update_post_meta($new_cpt_id,'_thumbnail_id',$attachment_post_id);
1472
-			}else{
1473
-				$migration_stage->add_error(sprintf(__("Could not update event image %s for CPT with ID %d, but attachments post ID is %d", "event_espresso"),$guid,$new_cpt_id,$attachment_post_id));
1470
+			if ($attachment_post_id) {
1471
+				update_post_meta($new_cpt_id, '_thumbnail_id', $attachment_post_id);
1472
+			} else {
1473
+				$migration_stage->add_error(sprintf(__("Could not update event image %s for CPT with ID %d, but attachments post ID is %d", "event_espresso"), $guid, $new_cpt_id, $attachment_post_id));
1474 1474
 			}
1475 1475
 		}
1476 1476
 		return $created_attachment_post;
@@ -1484,13 +1484,13 @@  discard block
 block discarded – undo
1484 1484
 	 * @param string $guid_in_old_event
1485 1485
 	 * @return string either the original guid, or $guid_in_old_event if we couldn't figure out what the original was
1486 1486
 	 */
1487
-	private function _get_original_guid($guid_in_old_event){
1488
-		$original_guid = preg_replace('~-\d*x\d*\.~','.',$guid_in_old_event,1);
1487
+	private function _get_original_guid($guid_in_old_event) {
1488
+		$original_guid = preg_replace('~-\d*x\d*\.~', '.', $guid_in_old_event, 1);
1489 1489
 		//do a head request to verify the file exists
1490 1490
 		$head_response = wp_remote_head($original_guid);
1491
-		if( ! $head_response instanceof WP_Error && $head_response['response']['message'] == 'OK'){
1491
+		if ( ! $head_response instanceof WP_Error && $head_response['response']['message'] == 'OK') {
1492 1492
 			return $original_guid;
1493
-		}else{
1493
+		} else {
1494 1494
 			return $guid_in_old_event;
1495 1495
 		}
1496 1496
 	}
@@ -1502,32 +1502,32 @@  discard block
 block discarded – undo
1502 1502
 	 * @param EE_Data_Migration_Script_Stage $migration_stage
1503 1503
 	 * @return int
1504 1504
 	 */
1505
-	private function _create_image_attachment_from_GUID($guid, EE_Data_Migration_Script_Stage $migration_stage){
1506
-		if ( ! $guid){
1505
+	private function _create_image_attachment_from_GUID($guid, EE_Data_Migration_Script_Stage $migration_stage) {
1506
+		if ( ! $guid) {
1507 1507
 			$migration_stage->add_error(sprintf(__("Cannot create image attachment for a blank GUID!", "event_espresso")));
1508 1508
 			return 0;
1509 1509
 		}
1510
-		$wp_filetype = wp_check_filetype(basename($guid), null );
1510
+		$wp_filetype = wp_check_filetype(basename($guid), null);
1511 1511
 		$wp_upload_dir = wp_upload_dir();
1512 1512
 		//if the file is located remotely, download it to our uploads DIR, because wp_genereate_attachmnet_metadata needs the file to be local
1513
-		if(strpos($guid,$wp_upload_dir['url']) === FALSE){
1513
+		if (strpos($guid, $wp_upload_dir['url']) === FALSE) {
1514 1514
 			//image is located remotely. download it and place it in the uploads directory
1515
-			if( ! is_readable($guid)){
1516
-				$migration_stage->add_error(sprintf(__("Could not create image attachment from non-existent file: %s", "event_espresso"),$guid));
1515
+			if ( ! is_readable($guid)) {
1516
+				$migration_stage->add_error(sprintf(__("Could not create image attachment from non-existent file: %s", "event_espresso"), $guid));
1517 1517
 				return 0;
1518 1518
 			}
1519
-			$contents= file_get_contents($guid);
1520
-			if($contents === FALSE){
1521
-				$migration_stage->add_error(sprintf(__("Could not read image at %s, and therefore couldnt create an attachment post for it.", "event_espresso"),$guid));
1519
+			$contents = file_get_contents($guid);
1520
+			if ($contents === FALSE) {
1521
+				$migration_stage->add_error(sprintf(__("Could not read image at %s, and therefore couldnt create an attachment post for it.", "event_espresso"), $guid));
1522 1522
 				return false;
1523 1523
 			}
1524
-			$local_filepath  = $wp_upload_dir['path'].DS.basename($guid);
1524
+			$local_filepath = $wp_upload_dir['path'].DS.basename($guid);
1525 1525
 			$savefile = fopen($local_filepath, 'w');
1526 1526
 			fwrite($savefile, $contents);
1527 1527
 			fclose($savefile);
1528
-			$guid = str_replace($wp_upload_dir['path'],$wp_upload_dir['url'],$local_filepath);
1529
-		}else{
1530
-			$local_filepath = str_replace($wp_upload_dir['url'],$wp_upload_dir['path'],$guid);
1528
+			$guid = str_replace($wp_upload_dir['path'], $wp_upload_dir['url'], $local_filepath);
1529
+		} else {
1530
+			$local_filepath = str_replace($wp_upload_dir['url'], $wp_upload_dir['path'], $guid);
1531 1531
 		}
1532 1532
 
1533 1533
 		$attachment = array(
@@ -1537,24 +1537,24 @@  discard block
 block discarded – undo
1537 1537
 		   'post_content' => '',
1538 1538
 		   'post_status' => 'inherit'
1539 1539
 		);
1540
-		$attach_id = wp_insert_attachment( $attachment, $guid );
1541
-		if( ! $attach_id ){
1542
-			$migration_stage->add_error(sprintf(__("Could not create image attachment post from image '%s'. Attachment data was %s.", "event_espresso"),$guid,$this->_json_encode($attachment)));
1540
+		$attach_id = wp_insert_attachment($attachment, $guid);
1541
+		if ( ! $attach_id) {
1542
+			$migration_stage->add_error(sprintf(__("Could not create image attachment post from image '%s'. Attachment data was %s.", "event_espresso"), $guid, $this->_json_encode($attachment)));
1543 1543
 			return $attach_id;
1544 1544
 		}
1545 1545
 
1546 1546
 		// you must first include the image.php file
1547 1547
 		// for the function wp_generate_attachment_metadata() to work
1548
-		require_once(ABSPATH . 'wp-admin/includes/image.php');
1548
+		require_once(ABSPATH.'wp-admin/includes/image.php');
1549 1549
 
1550
-		$attach_data = wp_generate_attachment_metadata( $attach_id, $local_filepath );
1551
-		if( ! $attach_data){
1552
-			$migration_stage->add_error(sprintf(__("Coudl not genereate attachment metadata for attachment post %d with filepath %s and GUID %s. Please check the file was downloaded properly.", "event_espresso"),$attach_id,$local_filepath,$guid));
1550
+		$attach_data = wp_generate_attachment_metadata($attach_id, $local_filepath);
1551
+		if ( ! $attach_data) {
1552
+			$migration_stage->add_error(sprintf(__("Coudl not genereate attachment metadata for attachment post %d with filepath %s and GUID %s. Please check the file was downloaded properly.", "event_espresso"), $attach_id, $local_filepath, $guid));
1553 1553
 			return $attach_id;
1554 1554
 		}
1555
-		$metadata_save_result = wp_update_attachment_metadata( $attach_id, $attach_data );
1556
-		if( ! $metadata_save_result ){
1557
-			$migration_stage->add_error(sprintf(__("Could not update attachment metadata for attachment %d with data %s", "event_espresso"),$attach_id,$this->_json_encode($attach_data)));
1555
+		$metadata_save_result = wp_update_attachment_metadata($attach_id, $attach_data);
1556
+		if ( ! $metadata_save_result) {
1557
+			$migration_stage->add_error(sprintf(__("Could not update attachment metadata for attachment %d with data %s", "event_espresso"), $attach_id, $this->_json_encode($attach_data)));
1558 1558
 		}
1559 1559
 		return $attach_id;
1560 1560
 	}
@@ -1566,9 +1566,9 @@  discard block
 block discarded – undo
1566 1566
 	 * @param string $guid
1567 1567
 	 * @return int
1568 1568
 	 */
1569
-	private function _get_image_attachment_id_by_GUID($guid){
1569
+	private function _get_image_attachment_id_by_GUID($guid) {
1570 1570
 		global $wpdb;
1571
-		$attachment_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid=%s LIMIT 1",$guid));
1571
+		$attachment_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid=%s LIMIT 1", $guid));
1572 1572
 		return $attachment_id;
1573 1573
 	}
1574 1574
 	/**
@@ -1580,20 +1580,20 @@  discard block
 block discarded – undo
1580 1580
 	 * @param string $timezone
1581 1581
 	 * @return string
1582 1582
 	 */
1583
-	public function convert_date_string_to_utc(EE_Data_Migration_Script_Stage $stage, $row_of_data, $DATETIME_string,$timezone = null){
1583
+	public function convert_date_string_to_utc(EE_Data_Migration_Script_Stage $stage, $row_of_data, $DATETIME_string, $timezone = null) {
1584 1584
 		$original_tz = $timezone;
1585
-		if( ! $timezone){
1585
+		if ( ! $timezone) {
1586 1586
 			$timezone = $this->_get_wp_timezone();
1587 1587
 		}
1588
-		if( ! $timezone){
1589
-			$stage->add_error(sprintf(__("Could not find timezone given %s for %s", "event_espresso"),$original_tz,$row_of_data));
1588
+		if ( ! $timezone) {
1589
+			$stage->add_error(sprintf(__("Could not find timezone given %s for %s", "event_espresso"), $original_tz, $row_of_data));
1590 1590
 			$timezone = 'UTC';
1591 1591
 		}
1592
-		try{
1593
-			$date_obj = new DateTime( $DATETIME_string, new DateTimeZone( $timezone ) );
1592
+		try {
1593
+			$date_obj = new DateTime($DATETIME_string, new DateTimeZone($timezone));
1594 1594
 			$date_obj->setTimezone(new DateTimeZone('UTC'));
1595
-		}catch(Exception $e){
1596
-			$stage->add_error(sprintf(__("Could not convert time string '%s' using timezone '%s' into a proper DATETIME. Using current time instead.", "event_espresso"),$DATETIME_string,$timezone));
1595
+		} catch (Exception $e) {
1596
+			$stage->add_error(sprintf(__("Could not convert time string '%s' using timezone '%s' into a proper DATETIME. Using current time instead.", "event_espresso"), $DATETIME_string, $timezone));
1597 1597
 			$date_obj = new DateTime();
1598 1598
 		}
1599 1599
 
@@ -1604,14 +1604,14 @@  discard block
 block discarded – undo
1604 1604
 	 * Gets the DEFAULT timezone string from wordpress (even if they set a gmt offset)
1605 1605
 	 * @return string
1606 1606
 	 */
1607
-	private function _get_wp_timezone(){
1608
-		$timezone = empty( $timezone ) ? get_option('timezone_string') : $timezone;
1607
+	private function _get_wp_timezone() {
1608
+		$timezone = empty($timezone) ? get_option('timezone_string') : $timezone;
1609 1609
 
1610 1610
 		//if timezone is STILL empty then let's get the GMT offset and then set the timezone_string using our converter
1611
-		if ( empty( $timezone ) ) {
1611
+		if (empty($timezone)) {
1612 1612
 			//let's get a the WordPress UTC offset
1613 1613
 			$offset = get_option('gmt_offset');
1614
-			$timezone = $this->timezone_convert_to_string_from_offset( $offset );
1614
+			$timezone = $this->timezone_convert_to_string_from_offset($offset);
1615 1615
 		}
1616 1616
 		return $timezone;
1617 1617
 	}
@@ -1620,11 +1620,11 @@  discard block
 block discarded – undo
1620 1620
 	 * @param int $offset
1621 1621
 	 * @return boolean
1622 1622
 	 */
1623
-	private function timezone_convert_to_string_from_offset($offset){
1623
+	private function timezone_convert_to_string_from_offset($offset) {
1624 1624
 		//shamelessly taken from bottom comment at http://ca1.php.net/manual/en/function.timezone-name-from-abbr.php because timezone_name_from_abbr() did NOT work as expected - its not reliable
1625 1625
 		$offset *= 3600; // convert hour offset to seconds
1626 1626
         $abbrarray = timezone_abbreviations_list();
1627
-        foreach ($abbrarray as $abbr){
1627
+        foreach ($abbrarray as $abbr) {
1628 1628
                 foreach ($abbr as $city)
1629 1629
                 {
1630 1630
                         if ($city['offset'] == $offset)
@@ -1638,32 +1638,32 @@  discard block
 block discarded – undo
1638 1638
         return FALSE;
1639 1639
 	}
1640 1640
 
1641
-	public function migration_page_hooks(){
1642
-		add_filter('FHEE__ee_migration_page__header',array($this,'_migrate_page_hook_simplify_version_strings'),10,3);
1643
-		add_filter('FHEE__ee_migration_page__p_after_header',array($this,'_migration_page_hook_simplify_next_db_state'),10,2);
1644
-		add_filter('FHEE__ee_migration_page__option_1_main',array($this,'_migrate_page_hook_simplify_version_strings'),10,3);
1645
-		add_filter('FHEE__ee_migration_page__option_1_button_text',array($this,'_migrate_page_hook_simplify_version_strings'),10,3);
1646
-		add_action('AHEE__ee_migration_page__option_1_extra_details',array($this,'_migration_page_hook_option_1_extra_details'),10,3);
1647
-		add_filter('FHEE__ee_migration_page__option_2_main',array($this,'_migrate_page_hook_simplify_version_strings'),10,4);
1648
-		add_filter('FHEE__ee_migration_page__option_2_button_text',array($this,'_migration_page_hook_simplify_next_db_state'),10,2);
1649
-		add_filter('FHEE__ee_migration_page__option_2_details',array($this,'_migration_page_hook_simplify_next_db_state'),10,2);
1650
-		add_action('AHEE__ee_migration_page__after_migration_options_table',array($this,'_migration_page_hook_after_migration_options_table'));
1651
-		add_filter('FHEE__ee_migration_page__done_migration_header',array($this,'_migration_page_hook_simplify_next_db_state'),10,2);
1652
-		add_filter('FHEE__ee_migration_page__p_after_done_migration_header',array($this,'_migration_page_hook_simplify_next_db_state'),10,2);
1641
+	public function migration_page_hooks() {
1642
+		add_filter('FHEE__ee_migration_page__header', array($this, '_migrate_page_hook_simplify_version_strings'), 10, 3);
1643
+		add_filter('FHEE__ee_migration_page__p_after_header', array($this, '_migration_page_hook_simplify_next_db_state'), 10, 2);
1644
+		add_filter('FHEE__ee_migration_page__option_1_main', array($this, '_migrate_page_hook_simplify_version_strings'), 10, 3);
1645
+		add_filter('FHEE__ee_migration_page__option_1_button_text', array($this, '_migrate_page_hook_simplify_version_strings'), 10, 3);
1646
+		add_action('AHEE__ee_migration_page__option_1_extra_details', array($this, '_migration_page_hook_option_1_extra_details'), 10, 3);
1647
+		add_filter('FHEE__ee_migration_page__option_2_main', array($this, '_migrate_page_hook_simplify_version_strings'), 10, 4);
1648
+		add_filter('FHEE__ee_migration_page__option_2_button_text', array($this, '_migration_page_hook_simplify_next_db_state'), 10, 2);
1649
+		add_filter('FHEE__ee_migration_page__option_2_details', array($this, '_migration_page_hook_simplify_next_db_state'), 10, 2);
1650
+		add_action('AHEE__ee_migration_page__after_migration_options_table', array($this, '_migration_page_hook_after_migration_options_table'));
1651
+		add_filter('FHEE__ee_migration_page__done_migration_header', array($this, '_migration_page_hook_simplify_next_db_state'), 10, 2);
1652
+		add_filter('FHEE__ee_migration_page__p_after_done_migration_header', array($this, '_migration_page_hook_simplify_next_db_state'), 10, 2);
1653 1653
 	}
1654 1654
 
1655
-	public function _migrate_page_hook_simplify_version_strings($old_content,$current_db_state,$next_db_state,$ultimate_db_state = NULL){
1656
-		return str_replace(array($current_db_state,$next_db_state,$ultimate_db_state),array(__('EE3','event_espresso'),__('EE4','event_espresso'),  __("EE4", 'event_espresso')),$old_content);
1655
+	public function _migrate_page_hook_simplify_version_strings($old_content, $current_db_state, $next_db_state, $ultimate_db_state = NULL) {
1656
+		return str_replace(array($current_db_state, $next_db_state, $ultimate_db_state), array(__('EE3', 'event_espresso'), __('EE4', 'event_espresso'), __("EE4", 'event_espresso')), $old_content);
1657 1657
 	}
1658
-	public function _migration_page_hook_simplify_next_db_state($old_content,$next_db_state){
1659
-		return str_replace($next_db_state,  __("EE4", 'event_espresso'),$old_content);
1658
+	public function _migration_page_hook_simplify_next_db_state($old_content, $next_db_state) {
1659
+		return str_replace($next_db_state, __("EE4", 'event_espresso'), $old_content);
1660 1660
 	}
1661
-	public function _migration_page_hook_option_1_extra_details(){
1662
-		?><p><?php	printf(__("Note: many of your EE3 shortcodes will be changed to EE4 shortcodes during this migration (among many other things). Should you revert to EE3, then you should restore to your backup or manually change the EE4 shortcodes back to their EE3 equivalents", "event_espresso"));?></p><?php
1661
+	public function _migration_page_hook_option_1_extra_details() {
1662
+		?><p><?php	printf(__("Note: many of your EE3 shortcodes will be changed to EE4 shortcodes during this migration (among many other things). Should you revert to EE3, then you should restore to your backup or manually change the EE4 shortcodes back to their EE3 equivalents", "event_espresso")); ?></p><?php
1663 1663
 	}
1664
-	public function _migration_page_hook_after_migration_options_table(){
1664
+	public function _migration_page_hook_after_migration_options_table() {
1665 1665
 		?><p class="ee-attention">
1666
-				<strong><span class="reminder-spn"><?php _e("Important note to those using Event Espresso 3 addons: ", "event_espresso");?></span></strong><br/><?php _e("Unless an addon's description on our website explicitly states that it is compatible with EE4, you should consider it incompatible and know that it WILL NOT WORK correctly with this new version of Event Espresso 4 (EE4). As well, any data for incompatible addons will NOT BE MIGRATED until an updated EE4 compatible version of the addon is available. If you want, or need to keep using your EE3 addons, you should simply continue using EE3 until EE4 compatible versions of your addons become available. To continue using EE3 for now, just deactivate EE4 and reactivate EE3.", "event_espresso");	?>
1666
+				<strong><span class="reminder-spn"><?php _e("Important note to those using Event Espresso 3 addons: ", "event_espresso"); ?></span></strong><br/><?php _e("Unless an addon's description on our website explicitly states that it is compatible with EE4, you should consider it incompatible and know that it WILL NOT WORK correctly with this new version of Event Espresso 4 (EE4). As well, any data for incompatible addons will NOT BE MIGRATED until an updated EE4 compatible version of the addon is available. If you want, or need to keep using your EE3 addons, you should simply continue using EE3 until EE4 compatible versions of your addons become available. To continue using EE3 for now, just deactivate EE4 and reactivate EE3.", "event_espresso"); ?>
1667 1667
 			</p><?php
1668 1668
 	}
1669 1669
 }
Please login to merge, or discard this patch.
admin_pages/general_settings/General_Settings_Admin_Page.core.php 2 patches
Indentation   +107 added lines, -107 removed lines patch added patch discarded remove patch
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 					'order' => 50
157 157
 					),
158 158
 				'metaboxes' => array_merge( $this->_default_espresso_metaboxes, array( '_publish_post_box' ) ),
159
-               			'help_tabs' => array(
159
+			   			'help_tabs' => array(
160 160
 					'general_settings_critical_pages_help_tab' => array(
161 161
 						'title' => __('Critical Pages', 'event_espresso'),
162 162
 						'filename' => 'general_settings_critical_pages'
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 					'label' => __('Your Organization', 'event_espresso'),
171 171
 					'order' => 20
172 172
 				),
173
-                			'help_tabs' => array(
173
+							'help_tabs' => array(
174 174
 					'general_settings_your_organization_help_tab' => array(
175 175
 						'title' => __('Your Organization', 'event_espresso'),
176 176
 						'filename' => 'general_settings_your_organization'
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
 					'order' => 60
187 187
 					),
188 188
 				'metaboxes' => array_merge( $this->_default_espresso_metaboxes, array( '_publish_post_box' ) ),
189
-                			'help_tabs' => array(
189
+							'help_tabs' => array(
190 190
 					'general_settings_admin_options_help_tab' => array(
191 191
 						'title' => __('Admin Options', 'event_espresso'),
192 192
 						'filename' => 'general_settings_admin_options'
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 					'label' => __('Countries', 'event_espresso'),
201 201
 					'order' => 70
202 202
 					),
203
-                'help_tabs' => array(
203
+				'help_tabs' => array(
204 204
 					'general_settings_countries_help_tab' => array(
205 205
 						'title' => __('Countries', 'event_espresso'),
206 206
 						'filename' => 'general_settings_countries'
@@ -261,49 +261,49 @@  discard block
 block discarded – undo
261 261
 
262 262
 
263 263
 	/*************		Espresso Pages 		*************/
264
-    /**
265
-     * _espresso_page_settings
266
-     *
267
-     * @throws \EE_Error
268
-     */
264
+	/**
265
+	 * _espresso_page_settings
266
+	 *
267
+	 * @throws \EE_Error
268
+	 */
269 269
 	protected function _espresso_page_settings() {
270
-        // Check to make sure all of the main pages are setup properly,
271
-        // if not create the default pages and display an admin notice
272
-        EEH_Activation::verify_default_pages_exist();
273
-        $this->_transient_garbage_collection();
274
-        $this->_template_args['values'] = $this->_yes_no_values;
275
-        $this->_template_args['reg_page_id'] = isset(EE_Registry::instance()->CFG->core->reg_page_id)
276
-            ? EE_Registry::instance()->CFG->core->reg_page_id
277
-            : null;
278
-        $this->_template_args['reg_page_obj'] = isset(EE_Registry::instance()->CFG->core->reg_page_id)
279
-            ? get_page(EE_Registry::instance()->CFG->core->reg_page_id)
280
-            : false;
281
-        $this->_template_args['txn_page_id'] = isset(EE_Registry::instance()->CFG->core->txn_page_id)
282
-            ? EE_Registry::instance()->CFG->core->txn_page_id
283
-            : null;
284
-        $this->_template_args['txn_page_obj'] = isset(EE_Registry::instance()->CFG->core->txn_page_id)
285
-            ? get_page(EE_Registry::instance()->CFG->core->txn_page_id)
286
-            : false;
287
-        $this->_template_args['thank_you_page_id'] = isset(EE_Registry::instance()->CFG->core->thank_you_page_id)
288
-            ? EE_Registry::instance()->CFG->core->thank_you_page_id
289
-            : null;
290
-        $this->_template_args['thank_you_page_obj'] = isset(EE_Registry::instance()->CFG->core->thank_you_page_id)
291
-            ? get_page(EE_Registry::instance()->CFG->core->thank_you_page_id)
292
-            : false;
293
-        $this->_template_args['cancel_page_id'] = isset(EE_Registry::instance()->CFG->core->cancel_page_id)
294
-            ? EE_Registry::instance()->CFG->core->cancel_page_id
295
-            : null;
296
-        $this->_template_args['cancel_page_obj'] = isset(EE_Registry::instance()->CFG->core->cancel_page_id)
297
-            ? get_page(EE_Registry::instance()->CFG->core->cancel_page_id)
298
-            : false;
299
-        $this->_set_add_edit_form_tags('update_espresso_page_settings');
300
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
301
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
302
-            GEN_SET_TEMPLATE_PATH . 'espresso_page_settings.template.php',
303
-            $this->_template_args,
304
-            true
305
-        );
306
-        $this->display_admin_page_with_sidebar();
270
+		// Check to make sure all of the main pages are setup properly,
271
+		// if not create the default pages and display an admin notice
272
+		EEH_Activation::verify_default_pages_exist();
273
+		$this->_transient_garbage_collection();
274
+		$this->_template_args['values'] = $this->_yes_no_values;
275
+		$this->_template_args['reg_page_id'] = isset(EE_Registry::instance()->CFG->core->reg_page_id)
276
+			? EE_Registry::instance()->CFG->core->reg_page_id
277
+			: null;
278
+		$this->_template_args['reg_page_obj'] = isset(EE_Registry::instance()->CFG->core->reg_page_id)
279
+			? get_page(EE_Registry::instance()->CFG->core->reg_page_id)
280
+			: false;
281
+		$this->_template_args['txn_page_id'] = isset(EE_Registry::instance()->CFG->core->txn_page_id)
282
+			? EE_Registry::instance()->CFG->core->txn_page_id
283
+			: null;
284
+		$this->_template_args['txn_page_obj'] = isset(EE_Registry::instance()->CFG->core->txn_page_id)
285
+			? get_page(EE_Registry::instance()->CFG->core->txn_page_id)
286
+			: false;
287
+		$this->_template_args['thank_you_page_id'] = isset(EE_Registry::instance()->CFG->core->thank_you_page_id)
288
+			? EE_Registry::instance()->CFG->core->thank_you_page_id
289
+			: null;
290
+		$this->_template_args['thank_you_page_obj'] = isset(EE_Registry::instance()->CFG->core->thank_you_page_id)
291
+			? get_page(EE_Registry::instance()->CFG->core->thank_you_page_id)
292
+			: false;
293
+		$this->_template_args['cancel_page_id'] = isset(EE_Registry::instance()->CFG->core->cancel_page_id)
294
+			? EE_Registry::instance()->CFG->core->cancel_page_id
295
+			: null;
296
+		$this->_template_args['cancel_page_obj'] = isset(EE_Registry::instance()->CFG->core->cancel_page_id)
297
+			? get_page(EE_Registry::instance()->CFG->core->cancel_page_id)
298
+			: false;
299
+		$this->_set_add_edit_form_tags('update_espresso_page_settings');
300
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
301
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
302
+			GEN_SET_TEMPLATE_PATH . 'espresso_page_settings.template.php',
303
+			$this->_template_args,
304
+			true
305
+		);
306
+		$this->display_admin_page_with_sidebar();
307 307
 
308 308
 	}
309 309
 
@@ -469,68 +469,68 @@  discard block
 block discarded – undo
469 469
 
470 470
 
471 471
 
472
-    /*************        Admin Options        *************/
473
-
474
-
475
-
476
-    /**
477
-     * _admin_option_settings
478
-     *
479
-     * @throws \EE_Error
480
-     * @throws \LogicException
481
-     */
482
-    protected function _admin_option_settings() {
483
-        $this->_template_args['admin_page_content'] = '';
484
-        try {
485
-            $admin_options_settings_form = new AdminOptionsSettings(EE_Registry::instance());
486
-            // still need this for the old school form in Extend_General_Settings_Admin_Page
487
-            $this->_template_args['values'] = $this->_yes_no_values;
488
-            // also need to account for the do_action that was in the old template
489
-            $admin_options_settings_form->setTemplateArgs($this->_template_args);
490
-            $this->_template_args['admin_page_content'] = $admin_options_settings_form->display();
491
-        } catch (Exception $e) {
492
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
493
-        }
494
-        $this->_set_add_edit_form_tags('update_admin_option_settings');
495
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
496
-        $this->display_admin_page_with_sidebar();
497
-    }
498
-
499
-
500
-
501
-    /**
502
-     * _update_admin_option_settings
503
-     *
504
-     * @throws \EE_Error
505
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
506
-     * @throws \EventEspresso\core\exceptions\InvalidFormSubmissionException
507
-     * @throws \InvalidArgumentException
508
-     * @throws \LogicException
509
-     */
510
-    protected function _update_admin_option_settings() {
511
-        try {
512
-            $admin_options_settings_form = new AdminOptionsSettings(EE_Registry::instance());
513
-            $admin_options_settings_form->process($this->_req_data[$admin_options_settings_form->slug()]);
514
-            EE_Registry::instance()->CFG->admin = apply_filters(
515
-                'FHEE__General_Settings_Admin_Page___update_admin_option_settings__CFG_admin',
516
-                EE_Registry::instance()->CFG->admin
517
-            );
518
-        } catch (Exception $e) {
519
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
520
-        }
472
+	/*************        Admin Options        *************/
473
+
474
+
475
+
476
+	/**
477
+	 * _admin_option_settings
478
+	 *
479
+	 * @throws \EE_Error
480
+	 * @throws \LogicException
481
+	 */
482
+	protected function _admin_option_settings() {
483
+		$this->_template_args['admin_page_content'] = '';
484
+		try {
485
+			$admin_options_settings_form = new AdminOptionsSettings(EE_Registry::instance());
486
+			// still need this for the old school form in Extend_General_Settings_Admin_Page
487
+			$this->_template_args['values'] = $this->_yes_no_values;
488
+			// also need to account for the do_action that was in the old template
489
+			$admin_options_settings_form->setTemplateArgs($this->_template_args);
490
+			$this->_template_args['admin_page_content'] = $admin_options_settings_form->display();
491
+		} catch (Exception $e) {
492
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
493
+		}
494
+		$this->_set_add_edit_form_tags('update_admin_option_settings');
495
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
496
+		$this->display_admin_page_with_sidebar();
497
+	}
498
+
499
+
500
+
501
+	/**
502
+	 * _update_admin_option_settings
503
+	 *
504
+	 * @throws \EE_Error
505
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
506
+	 * @throws \EventEspresso\core\exceptions\InvalidFormSubmissionException
507
+	 * @throws \InvalidArgumentException
508
+	 * @throws \LogicException
509
+	 */
510
+	protected function _update_admin_option_settings() {
511
+		try {
512
+			$admin_options_settings_form = new AdminOptionsSettings(EE_Registry::instance());
513
+			$admin_options_settings_form->process($this->_req_data[$admin_options_settings_form->slug()]);
514
+			EE_Registry::instance()->CFG->admin = apply_filters(
515
+				'FHEE__General_Settings_Admin_Page___update_admin_option_settings__CFG_admin',
516
+				EE_Registry::instance()->CFG->admin
517
+			);
518
+		} catch (Exception $e) {
519
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
520
+		}
521 521
 		$this->_redirect_after_action(
522
-            apply_filters(
523
-                'FHEE__General_Settings_Admin_Page___update_admin_option_settings__success',
524
-                $this->_update_espresso_configuration(
525
-                    'Admin Options',
526
-                    EE_Registry::instance()->CFG->admin,
527
-                    __FILE__, __FUNCTION__, __LINE__
528
-                )
529
-            ),
530
-            'Admin Options',
531
-            'updated',
532
-            array( 'action' => 'admin_option_settings' )
533
-        );
522
+			apply_filters(
523
+				'FHEE__General_Settings_Admin_Page___update_admin_option_settings__success',
524
+				$this->_update_espresso_configuration(
525
+					'Admin Options',
526
+					EE_Registry::instance()->CFG->admin,
527
+					__FILE__, __FUNCTION__, __LINE__
528
+				)
529
+			),
530
+			'Admin Options',
531
+			'updated',
532
+			array( 'action' => 'admin_option_settings' )
533
+		);
534 534
 
535 535
 	}
536 536
 
Please login to merge, or discard this patch.
Spacing   +249 added lines, -250 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 use EventEspresso\admin_pages\general_settings\AdminOptionsSettings;
3 3
 
4
-if (!defined('EVENT_ESPRESSO_VERSION') )
4
+if ( ! defined('EVENT_ESPRESSO_VERSION'))
5 5
 	exit('NO direct script access allowed');
6 6
 
7 7
 /**
@@ -42,8 +42,8 @@  discard block
 block discarded – undo
42 42
 
43 43
 
44 44
 
45
-	public function __construct( $routing = TRUE ) {
46
-		parent::__construct( $routing );
45
+	public function __construct($routing = TRUE) {
46
+		parent::__construct($routing);
47 47
 	}
48 48
 
49 49
 
@@ -59,10 +59,10 @@  discard block
 block discarded – undo
59 59
 
60 60
 
61 61
 	protected function _ajax_hooks() {
62
-		add_action('wp_ajax_espresso_display_country_settings', array( $this, 'display_country_settings'));
63
-		add_action('wp_ajax_espresso_display_country_states', array( $this, 'display_country_states'));
64
-		add_action('wp_ajax_espresso_delete_state', array( $this, 'delete_state'), 10, 3 );
65
-		add_action('wp_ajax_espresso_add_new_state', array( $this, 'add_new_state'));
62
+		add_action('wp_ajax_espresso_display_country_settings', array($this, 'display_country_settings'));
63
+		add_action('wp_ajax_espresso_display_country_states', array($this, 'display_country_states'));
64
+		add_action('wp_ajax_espresso_delete_state', array($this, 'delete_state'), 10, 3);
65
+		add_action('wp_ajax_espresso_add_new_state', array($this, 'add_new_state'));
66 66
 	}
67 67
 
68 68
 
@@ -155,14 +155,14 @@  discard block
 block discarded – undo
155 155
 					'label' => __('Critical Pages', 'event_espresso'),
156 156
 					'order' => 50
157 157
 					),
158
-				'metaboxes' => array_merge( $this->_default_espresso_metaboxes, array( '_publish_post_box' ) ),
158
+				'metaboxes' => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
159 159
                			'help_tabs' => array(
160 160
 					'general_settings_critical_pages_help_tab' => array(
161 161
 						'title' => __('Critical Pages', 'event_espresso'),
162 162
 						'filename' => 'general_settings_critical_pages'
163 163
 						)
164 164
 					),
165
-				'help_tour' => array( 'Critical_Pages_Help_Tour' ),
165
+				'help_tour' => array('Critical_Pages_Help_Tour'),
166 166
 				'require_nonce' => FALSE
167 167
 				),
168 168
 			'default' => array(
@@ -176,8 +176,8 @@  discard block
 block discarded – undo
176 176
 						'filename' => 'general_settings_your_organization'
177 177
 						)
178 178
 					),
179
-				'help_tour' => array( 'Your_Organization_Help_Tour' ),
180
-				'metaboxes' => array_merge( $this->_default_espresso_metaboxes, array( '_publish_post_box' ) ),
179
+				'help_tour' => array('Your_Organization_Help_Tour'),
180
+				'metaboxes' => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
181 181
 				'require_nonce' => FALSE
182 182
 				),
183 183
 			'admin_option_settings' => array(
@@ -185,14 +185,14 @@  discard block
 block discarded – undo
185 185
 					'label' => __('Admin Options', 'event_espresso'),
186 186
 					'order' => 60
187 187
 					),
188
-				'metaboxes' => array_merge( $this->_default_espresso_metaboxes, array( '_publish_post_box' ) ),
188
+				'metaboxes' => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
189 189
                 			'help_tabs' => array(
190 190
 					'general_settings_admin_options_help_tab' => array(
191 191
 						'title' => __('Admin Options', 'event_espresso'),
192 192
 						'filename' => 'general_settings_admin_options'
193 193
 						)
194 194
 					),
195
-				'help_tour' => array( 'Admin_Options_Help_Tour' ),
195
+				'help_tour' => array('Admin_Options_Help_Tour'),
196 196
 				'require_nonce' => FALSE
197 197
 				),
198 198
 			'country_settings' => array(
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
 						'filename' => 'general_settings_countries'
207 207
 						)
208 208
 					),
209
-				'help_tour' => array( 'Countries_Help_Tour' ),
209
+				'help_tour' => array('Countries_Help_Tour'),
210 210
 				'require_nonce' => FALSE
211 211
 				)
212 212
 			);
@@ -224,11 +224,11 @@  discard block
 block discarded – undo
224 224
 	}
225 225
 
226 226
 	public function admin_init() {
227
-		EE_Registry::$i18n_js_strings[ 'invalid_server_response' ] = __( 'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.', 'event_espresso' );
228
-		EE_Registry::$i18n_js_strings[ 'error_occurred' ] = __( 'An error occurred! Please refresh the page and try again.', 'event_espresso' );
229
-		EE_Registry::$i18n_js_strings[ 'confirm_delete_state' ] = __( 'Are you sure you want to delete this State / Province?', 'event_espresso' );
230
-		$protocol = isset( $_SERVER[ 'HTTPS' ] ) ? 'https://' : 'http://';
231
-		EE_Registry::$i18n_js_strings[ 'ajax_url' ] = admin_url( 'admin-ajax.php?page=espresso_general_settings', $protocol );
227
+		EE_Registry::$i18n_js_strings['invalid_server_response'] = __('An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.', 'event_espresso');
228
+		EE_Registry::$i18n_js_strings['error_occurred'] = __('An error occurred! Please refresh the page and try again.', 'event_espresso');
229
+		EE_Registry::$i18n_js_strings['confirm_delete_state'] = __('Are you sure you want to delete this State / Province?', 'event_espresso');
230
+		$protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
231
+		EE_Registry::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php?page=espresso_general_settings', $protocol);
232 232
 	}
233 233
 
234 234
 	public function admin_notices() {}
@@ -241,21 +241,21 @@  discard block
 block discarded – undo
241 241
 		//scripts
242 242
 		wp_enqueue_script('media-upload');
243 243
 		wp_enqueue_script('thickbox');
244
-		wp_register_script( 'organization_settings', GEN_SET_ASSETS_URL . 'your_organization_settings.js', array( 'jquery','media-upload','thickbox' ), EVENT_ESPRESSO_VERSION, TRUE );
245
-		wp_register_style( 'organization-css', GEN_SET_ASSETS_URL . 'organization.css', array(), EVENT_ESPRESSO_VERSION );
246
-		wp_enqueue_script( 'organization_settings' );
247
-		wp_enqueue_style( 'organization-css' );
248
-		$confirm_image_delete = array( 'text' => __('Do you really want to delete this image? Please remember to save your settings to complete the removal.', 'event_espresso'));
249
-		wp_localize_script( 'organization_settings', 'confirm_image_delete', $confirm_image_delete );
244
+		wp_register_script('organization_settings', GEN_SET_ASSETS_URL.'your_organization_settings.js', array('jquery', 'media-upload', 'thickbox'), EVENT_ESPRESSO_VERSION, TRUE);
245
+		wp_register_style('organization-css', GEN_SET_ASSETS_URL.'organization.css', array(), EVENT_ESPRESSO_VERSION);
246
+		wp_enqueue_script('organization_settings');
247
+		wp_enqueue_style('organization-css');
248
+		$confirm_image_delete = array('text' => __('Do you really want to delete this image? Please remember to save your settings to complete the removal.', 'event_espresso'));
249
+		wp_localize_script('organization_settings', 'confirm_image_delete', $confirm_image_delete);
250 250
 
251 251
 	}
252 252
 
253 253
 	public function load_scripts_styles_country_settings() {
254 254
 		//scripts
255
-		wp_register_script( 'gen_settings_countries', GEN_SET_ASSETS_URL . 'gen_settings_countries.js', array( 'ee_admin_js' ), EVENT_ESPRESSO_VERSION, TRUE );
256
-		wp_register_style( 'organization-css', GEN_SET_ASSETS_URL . 'organization.css', array(), EVENT_ESPRESSO_VERSION );
257
-		wp_enqueue_script( 'gen_settings_countries' );
258
-		wp_enqueue_style( 'organization-css' );
255
+		wp_register_script('gen_settings_countries', GEN_SET_ASSETS_URL.'gen_settings_countries.js', array('ee_admin_js'), EVENT_ESPRESSO_VERSION, TRUE);
256
+		wp_register_style('organization-css', GEN_SET_ASSETS_URL.'organization.css', array(), EVENT_ESPRESSO_VERSION);
257
+		wp_enqueue_script('gen_settings_countries');
258
+		wp_enqueue_style('organization-css');
259 259
 
260 260
 	}
261 261
 
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
         $this->_set_add_edit_form_tags('update_espresso_page_settings');
300 300
         $this->_set_publish_post_box_vars(null, false, false, null, false);
301 301
         $this->_template_args['admin_page_content'] = EEH_Template::display_template(
302
-            GEN_SET_TEMPLATE_PATH . 'espresso_page_settings.template.php',
302
+            GEN_SET_TEMPLATE_PATH.'espresso_page_settings.template.php',
303 303
             $this->_template_args,
304 304
             true
305 305
         );
@@ -309,10 +309,10 @@  discard block
 block discarded – undo
309 309
 
310 310
 	protected function _update_espresso_page_settings() {
311 311
 		// capture incoming request data
312
-		$reg_page_id = isset( $this->_req_data['reg_page_id'] ) ? absint( $this->_req_data['reg_page_id'] ) : EE_Registry::instance()->CFG->core->reg_page_id;
313
-		$txn_page_id = isset( $this->_req_data['txn_page_id'] ) ? absint( $this->_req_data['txn_page_id'] ) : EE_Registry::instance()->CFG->core->txn_page_id;
314
-		$thank_you_page_id = isset( $this->_req_data['thank_you_page_id'] ) ? absint( $this->_req_data['thank_you_page_id'] ) : EE_Registry::instance()->CFG->core->thank_you_page_id;
315
-		$cancel_page_id = isset( $this->_req_data['cancel_page_id'] ) ? absint( $this->_req_data['cancel_page_id'] ) : EE_Registry::instance()->CFG->core->cancel_page_id;
312
+		$reg_page_id = isset($this->_req_data['reg_page_id']) ? absint($this->_req_data['reg_page_id']) : EE_Registry::instance()->CFG->core->reg_page_id;
313
+		$txn_page_id = isset($this->_req_data['txn_page_id']) ? absint($this->_req_data['txn_page_id']) : EE_Registry::instance()->CFG->core->txn_page_id;
314
+		$thank_you_page_id = isset($this->_req_data['thank_you_page_id']) ? absint($this->_req_data['thank_you_page_id']) : EE_Registry::instance()->CFG->core->thank_you_page_id;
315
+		$cancel_page_id = isset($this->_req_data['cancel_page_id']) ? absint($this->_req_data['cancel_page_id']) : EE_Registry::instance()->CFG->core->cancel_page_id;
316 316
 		// pack critical_pages into an array
317 317
 		$critical_pages = array(
318 318
 			'reg_page_id' 				=> $reg_page_id,
@@ -320,17 +320,17 @@  discard block
 block discarded – undo
320 320
 			'thank_you_page_id' 	=> $thank_you_page_id,
321 321
 			'cancel_page_id' 		=> $cancel_page_id
322 322
 		);
323
-		foreach ( $critical_pages as $critical_page_name => $critical_page_id ) {
323
+		foreach ($critical_pages as $critical_page_name => $critical_page_id) {
324 324
 			// has the page changed ?
325
-			if ( EE_Registry::instance()->CFG->core->{$critical_page_name} !== $critical_page_id ) {
325
+			if (EE_Registry::instance()->CFG->core->{$critical_page_name} !== $critical_page_id) {
326 326
 				// grab post object for old page
327
-				$post = get_post( EE_Registry::instance()->CFG->core->{$critical_page_name} );
327
+				$post = get_post(EE_Registry::instance()->CFG->core->{$critical_page_name} );
328 328
 				// update post shortcodes for old page
329
-				EventEspresso\core\admin\PostShortcodeTracking::parse_post_content_on_save( $critical_page_id, $post );
329
+				EventEspresso\core\admin\PostShortcodeTracking::parse_post_content_on_save($critical_page_id, $post);
330 330
 				// grab post object for new page
331
-				$post = get_post( $critical_page_id );
331
+				$post = get_post($critical_page_id);
332 332
 				// update post shortcodes for new page
333
-				EventEspresso\core\admin\PostShortcodeTracking::parse_post_content_on_save( $critical_page_id, $post );
333
+				EventEspresso\core\admin\PostShortcodeTracking::parse_post_content_on_save($critical_page_id, $post);
334 334
 			}
335 335
 		}
336 336
 		// set page IDs
@@ -339,14 +339,14 @@  discard block
 block discarded – undo
339 339
 		EE_Registry::instance()->CFG->core->thank_you_page_id = $thank_you_page_id;
340 340
 		EE_Registry::instance()->CFG->core->cancel_page_id = $cancel_page_id;
341 341
 
342
-		EE_Registry::instance()->CFG->core = apply_filters( 'FHEE__General_Settings_Admin_Page___update_espresso_page_settings__CFG_core', EE_Registry::instance()->CFG->core, $this->_req_data );
342
+		EE_Registry::instance()->CFG->core = apply_filters('FHEE__General_Settings_Admin_Page___update_espresso_page_settings__CFG_core', EE_Registry::instance()->CFG->core, $this->_req_data);
343 343
 
344 344
 		$what = __('Critical Pages & Shortcodes', 'event_espresso');
345
-		$success = $this->_update_espresso_configuration( $what, EE_Registry::instance()->CFG->core, __FILE__, __FUNCTION__, __LINE__ );
345
+		$success = $this->_update_espresso_configuration($what, EE_Registry::instance()->CFG->core, __FILE__, __FUNCTION__, __LINE__);
346 346
 		$query_args = array(
347 347
 			'action' => 'critical_pages'
348 348
 			);
349
-		$this->_redirect_after_action( FALSE, '', '', $query_args, TRUE );
349
+		$this->_redirect_after_action(FALSE, '', '', $query_args, TRUE);
350 350
 
351 351
 	}
352 352
 
@@ -361,34 +361,34 @@  discard block
 block discarded – undo
361 361
 
362 362
 	protected function _your_organization_settings() {
363 363
 
364
-		$this->_template_args['site_license_key'] = isset( EE_Registry::instance()->NET_CFG->core->site_license_key ) ? EE_Registry::instance()->NET_CFG->core->get_pretty( 'site_license_key' ) : '';
365
-		$this->_template_args['organization_name'] = isset( EE_Registry::instance()->CFG->organization->name ) ? EE_Registry::instance()->CFG->organization->get_pretty( 'name' ) : '';
366
-		$this->_template_args['organization_address_1'] = isset( EE_Registry::instance()->CFG->organization->address_1 ) ? EE_Registry::instance()->CFG->organization->get_pretty( 'address_1' ) : '';
367
-		$this->_template_args['organization_address_2'] = isset( EE_Registry::instance()->CFG->organization->address_2 ) ? EE_Registry::instance()->CFG->organization->get_pretty( 'address_2' ) : '';
368
-		$this->_template_args['organization_city'] = isset( EE_Registry::instance()->CFG->organization->city ) ? EE_Registry::instance()->CFG->organization->get_pretty( 'city' ) : '';
369
-		$this->_template_args['organization_zip'] = isset( EE_Registry::instance()->CFG->organization->zip ) ? EE_Registry::instance()->CFG->organization->get_pretty( 'zip' ) : '';
370
-		$this->_template_args['organization_email'] = isset( EE_Registry::instance()->CFG->organization->email ) ? EE_Registry::instance()->CFG->organization->get_pretty( 'email' ) : '';
371
-		$this->_template_args['organization_phone'] = isset( EE_Registry::instance()->CFG->organization->phone ) ? EE_Registry::instance()->CFG->organization->get_pretty( 'phone' ) : '';
372
-		$this->_template_args['organization_vat'] = isset( EE_Registry::instance()->CFG->organization->vat ) ? EE_Registry::instance()->CFG->organization->get_pretty( 'vat' ) : '';
373
-		$this->_template_args['currency_sign'] = isset( EE_Registry::instance()->CFG->currency->sign ) ? EE_Registry::instance()->CFG->currency->get_pretty( 'sign' ) : '$';
374
-		$this->_template_args['organization_logo_url'] = isset( EE_Registry::instance()->CFG->organization->logo_url ) ? EE_Registry::instance()->CFG->organization->get_pretty( 'logo_url' ) : FALSE;
375
-		$this->_template_args['organization_facebook'] = isset( EE_Registry::instance()->CFG->organization->facebook ) ? EE_Registry::instance()->CFG->organization->get_pretty( 'facebook' ) : '';
376
-		$this->_template_args['organization_twitter'] = isset( EE_Registry::instance()->CFG->organization->twitter ) ? EE_Registry::instance()->CFG->organization->get_pretty( 'twitter' ) : '';
377
-		$this->_template_args['organization_linkedin'] = isset( EE_Registry::instance()->CFG->organization->linkedin ) ? EE_Registry::instance()->CFG->organization->get_pretty( 'linkedin' ) : '';
378
-		$this->_template_args['organization_pinterest'] = isset( EE_Registry::instance()->CFG->organization->pinterest ) ? EE_Registry::instance()->CFG->organization->get_pretty( 'pinterest' ) : '';
379
-		$this->_template_args['organization_google'] = isset( EE_Registry::instance()->CFG->organization->google ) ? EE_Registry::instance()->CFG->organization->get_pretty( 'google' ) : '';
380
-		$this->_template_args['organization_instagram'] = isset( EE_Registry::instance()->CFG->organization->instagram ) ? EE_Registry::instance()->CFG->organization->get_pretty( 'instagram' ) : '';
364
+		$this->_template_args['site_license_key'] = isset(EE_Registry::instance()->NET_CFG->core->site_license_key) ? EE_Registry::instance()->NET_CFG->core->get_pretty('site_license_key') : '';
365
+		$this->_template_args['organization_name'] = isset(EE_Registry::instance()->CFG->organization->name) ? EE_Registry::instance()->CFG->organization->get_pretty('name') : '';
366
+		$this->_template_args['organization_address_1'] = isset(EE_Registry::instance()->CFG->organization->address_1) ? EE_Registry::instance()->CFG->organization->get_pretty('address_1') : '';
367
+		$this->_template_args['organization_address_2'] = isset(EE_Registry::instance()->CFG->organization->address_2) ? EE_Registry::instance()->CFG->organization->get_pretty('address_2') : '';
368
+		$this->_template_args['organization_city'] = isset(EE_Registry::instance()->CFG->organization->city) ? EE_Registry::instance()->CFG->organization->get_pretty('city') : '';
369
+		$this->_template_args['organization_zip'] = isset(EE_Registry::instance()->CFG->organization->zip) ? EE_Registry::instance()->CFG->organization->get_pretty('zip') : '';
370
+		$this->_template_args['organization_email'] = isset(EE_Registry::instance()->CFG->organization->email) ? EE_Registry::instance()->CFG->organization->get_pretty('email') : '';
371
+		$this->_template_args['organization_phone'] = isset(EE_Registry::instance()->CFG->organization->phone) ? EE_Registry::instance()->CFG->organization->get_pretty('phone') : '';
372
+		$this->_template_args['organization_vat'] = isset(EE_Registry::instance()->CFG->organization->vat) ? EE_Registry::instance()->CFG->organization->get_pretty('vat') : '';
373
+		$this->_template_args['currency_sign'] = isset(EE_Registry::instance()->CFG->currency->sign) ? EE_Registry::instance()->CFG->currency->get_pretty('sign') : '$';
374
+		$this->_template_args['organization_logo_url'] = isset(EE_Registry::instance()->CFG->organization->logo_url) ? EE_Registry::instance()->CFG->organization->get_pretty('logo_url') : FALSE;
375
+		$this->_template_args['organization_facebook'] = isset(EE_Registry::instance()->CFG->organization->facebook) ? EE_Registry::instance()->CFG->organization->get_pretty('facebook') : '';
376
+		$this->_template_args['organization_twitter'] = isset(EE_Registry::instance()->CFG->organization->twitter) ? EE_Registry::instance()->CFG->organization->get_pretty('twitter') : '';
377
+		$this->_template_args['organization_linkedin'] = isset(EE_Registry::instance()->CFG->organization->linkedin) ? EE_Registry::instance()->CFG->organization->get_pretty('linkedin') : '';
378
+		$this->_template_args['organization_pinterest'] = isset(EE_Registry::instance()->CFG->organization->pinterest) ? EE_Registry::instance()->CFG->organization->get_pretty('pinterest') : '';
379
+		$this->_template_args['organization_google'] = isset(EE_Registry::instance()->CFG->organization->google) ? EE_Registry::instance()->CFG->organization->get_pretty('google') : '';
380
+		$this->_template_args['organization_instagram'] = isset(EE_Registry::instance()->CFG->organization->instagram) ? EE_Registry::instance()->CFG->organization->get_pretty('instagram') : '';
381 381
 		//UXIP settings
382
-		$this->_template_args['ee_ueip_optin'] = isset( EE_Registry::instance()->CFG->core->ee_ueip_optin ) ? EE_Registry::instance()->CFG->core->get_pretty( 'ee_ueip_optin' ) : TRUE;
382
+		$this->_template_args['ee_ueip_optin'] = isset(EE_Registry::instance()->CFG->core->ee_ueip_optin) ? EE_Registry::instance()->CFG->core->get_pretty('ee_ueip_optin') : TRUE;
383 383
 
384
-		$STA_ID = isset( EE_Registry::instance()->CFG->organization->STA_ID ) ? EE_Registry::instance()->CFG->organization->STA_ID : 4;
384
+		$STA_ID = isset(EE_Registry::instance()->CFG->organization->STA_ID) ? EE_Registry::instance()->CFG->organization->STA_ID : 4;
385 385
 		$this->_template_args['states'] = new EE_Question_Form_Input(
386
-				EE_Question::new_instance ( array(
386
+				EE_Question::new_instance(array(
387 387
 					'QST_ID'=> 0,
388 388
 					'QST_display_text'=> __('State/Province', 'event_espresso'),
389 389
 					'QST_system'=>'admin-state'
390 390
 				)),
391
-				EE_Answer::new_instance ( array(
391
+				EE_Answer::new_instance(array(
392 392
 					'ANS_ID' => 0,
393 393
 					'ANS_value' => $STA_ID
394 394
 				)),
@@ -400,14 +400,14 @@  discard block
 block discarded – undo
400 400
 				)
401 401
 			);
402 402
 
403
-		$CNT_ISO = isset( EE_Registry::instance()->CFG->organization->CNT_ISO ) ? EE_Registry::instance()->CFG->organization->CNT_ISO : 'US';
403
+		$CNT_ISO = isset(EE_Registry::instance()->CFG->organization->CNT_ISO) ? EE_Registry::instance()->CFG->organization->CNT_ISO : 'US';
404 404
 		$this->_template_args['countries'] = new EE_Question_Form_Input(
405
-				EE_Question::new_instance ( array(
405
+				EE_Question::new_instance(array(
406 406
 					'QST_ID'=> 0,
407 407
 					'QST_display_text'=> __('Country', 'event_espresso'),
408 408
 					'QST_system'=>'admin-country'
409 409
 				)),
410
-				EE_Answer::new_instance ( array(
410
+				EE_Answer::new_instance(array(
411 411
 					'ANS_ID' => 0,
412 412
 					'ANS_value' => $CNT_ISO
413 413
 				)),
@@ -419,51 +419,51 @@  discard block
 block discarded – undo
419 419
 				)
420 420
 			);
421 421
 
422
-		add_filter( 'FHEE__EEH_Form_Fields__label_html', array( $this, 'country_form_field_label_wrap' ), 10, 2 );
423
-		add_filter( 'FHEE__EEH_Form_Fields__input_html', array( $this, 'country_form_field_input__wrap' ), 10, 2 );
422
+		add_filter('FHEE__EEH_Form_Fields__label_html', array($this, 'country_form_field_label_wrap'), 10, 2);
423
+		add_filter('FHEE__EEH_Form_Fields__input_html', array($this, 'country_form_field_input__wrap'), 10, 2);
424 424
 
425 425
 		//PUE verification stuff
426
-		$ver_option_key = 'puvererr_' . basename( EE_PLUGIN_BASENAME );
427
-		$verify_fail = get_option( $ver_option_key );
428
-		$this->_template_args['site_license_key_verified'] = $verify_fail || !empty( $verify_fail ) || ( empty( $this->_template_args['site_license_key'] ) && empty( $verify_fail ) )? '<span class="dashicons dashicons-admin-network ee-icon-color-ee-red ee-icon-size-20"></span>' : '<span class="dashicons dashicons-admin-network ee-icon-color-ee-green ee-icon-size-20"></span>';
426
+		$ver_option_key = 'puvererr_'.basename(EE_PLUGIN_BASENAME);
427
+		$verify_fail = get_option($ver_option_key);
428
+		$this->_template_args['site_license_key_verified'] = $verify_fail || ! empty($verify_fail) || (empty($this->_template_args['site_license_key']) && empty($verify_fail)) ? '<span class="dashicons dashicons-admin-network ee-icon-color-ee-red ee-icon-size-20"></span>' : '<span class="dashicons dashicons-admin-network ee-icon-color-ee-green ee-icon-size-20"></span>';
429 429
 
430
-		$this->_set_add_edit_form_tags( 'update_your_organization_settings' );
431
-		$this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
432
-		$this->_template_args['admin_page_content'] = EEH_Template::display_template( GEN_SET_TEMPLATE_PATH . 'your_organization_settings.template.php', $this->_template_args, TRUE );
430
+		$this->_set_add_edit_form_tags('update_your_organization_settings');
431
+		$this->_set_publish_post_box_vars(NULL, FALSE, FALSE, NULL, FALSE);
432
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(GEN_SET_TEMPLATE_PATH.'your_organization_settings.template.php', $this->_template_args, TRUE);
433 433
 
434 434
 		$this->display_admin_page_with_sidebar();
435 435
 	}
436 436
 
437 437
 	protected function _update_your_organization_settings() {
438
-		if ( is_main_site() )
439
-			EE_Registry::instance()->NET_CFG->core->site_license_key = isset( $this->_req_data['site_license_key'] ) ? sanitize_text_field( $this->_req_data['site_license_key'] ) : EE_Registry::instance()->NET_CFG->core->site_license_key;
440
-		EE_Registry::instance()->CFG->organization->name = isset( $this->_req_data['organization_name'] ) ? sanitize_text_field( $this->_req_data['organization_name'] ) : EE_Registry::instance()->CFG->organization->name;
441
-		EE_Registry::instance()->CFG->organization->address_1 = isset( $this->_req_data['organization_address_1'] ) ? sanitize_text_field( $this->_req_data['organization_address_1'] ) : EE_Registry::instance()->CFG->organization->address_1;
442
-		EE_Registry::instance()->CFG->organization->address_2 = isset( $this->_req_data['organization_address_2'] ) ? sanitize_text_field( $this->_req_data['organization_address_2'] ) : EE_Registry::instance()->CFG->organization->address_2;
443
-		EE_Registry::instance()->CFG->organization->city = isset( $this->_req_data['organization_city'] ) ? sanitize_text_field( $this->_req_data['organization_city'] ) : EE_Registry::instance()->CFG->organization->city;
444
-		EE_Registry::instance()->CFG->organization->STA_ID = isset( $this->_req_data['organization_state'] ) ? absint( $this->_req_data['organization_state'] ) : EE_Registry::instance()->CFG->organization->STA_ID;
445
-		EE_Registry::instance()->CFG->organization->CNT_ISO = isset( $this->_req_data['organization_country'] ) ? sanitize_text_field( $this->_req_data['organization_country'] ) : EE_Registry::instance()->CFG->organization->CNT_ISO;
446
-		EE_Registry::instance()->CFG->organization->zip = isset( $this->_req_data['organization_zip'] ) ? sanitize_text_field( $this->_req_data['organization_zip'] ) : EE_Registry::instance()->CFG->organization->zip;
447
-		EE_Registry::instance()->CFG->organization->email = isset( $this->_req_data['organization_email'] ) ? sanitize_email( $this->_req_data['organization_email'] ) : EE_Registry::instance()->CFG->organization->email;
448
-		EE_Registry::instance()->CFG->organization->vat = isset( $this->_req_data['organization_vat'] ) ? sanitize_text_field( $this->_req_data['organization_vat'] ) : EE_Registry::instance()->CFG->organization->vat;
449
-		EE_Registry::instance()->CFG->organization->phone = isset( $this->_req_data['organization_phone'] ) ? sanitize_text_field( $this->_req_data['organization_phone'] ) : EE_Registry::instance()->CFG->organization->phone;
450
-		EE_Registry::instance()->CFG->organization->logo_url = isset( $this->_req_data['organization_logo_url'] ) ? esc_url_raw( $this->_req_data['organization_logo_url'] ) : EE_Registry::instance()->CFG->organization->logo_url;
451
-		EE_Registry::instance()->CFG->organization->facebook = isset( $this->_req_data['organization_facebook'] ) ? esc_url_raw( $this->_req_data['organization_facebook'] ) : EE_Registry::instance()->CFG->organization->facebook;
452
-		EE_Registry::instance()->CFG->organization->twitter = isset( $this->_req_data['organization_twitter'] ) ? esc_url_raw( $this->_req_data['organization_twitter'] ) : EE_Registry::instance()->CFG->organization->twitter;
453
-		EE_Registry::instance()->CFG->organization->linkedin = isset( $this->_req_data['organization_linkedin'] ) ? esc_url_raw( $this->_req_data['organization_linkedin'] ) : EE_Registry::instance()->CFG->organization->linkedin;
454
-		EE_Registry::instance()->CFG->organization->pinterest = isset( $this->_req_data['organization_pinterest'] ) ? esc_url_raw( $this->_req_data['organization_pinterest'] ) : EE_Registry::instance()->CFG->organization->pinterest;
455
-		EE_Registry::instance()->CFG->organization->google = isset( $this->_req_data['organization_google'] ) ? esc_url_raw( $this->_req_data['organization_google'] ) : EE_Registry::instance()->CFG->organization->google;
456
-		EE_Registry::instance()->CFG->organization->instagram = isset( $this->_req_data['organization_instagram'] ) ? esc_url_raw( $this->_req_data['organization_instagram'] ) : EE_Registry::instance()->CFG->organization->instagram;
457
-		EE_Registry::instance()->CFG->core->ee_ueip_optin = isset( $this->_req_data['ueip_optin'] ) && !empty( $this->_req_data['ueip_optin'] ) ? $this->_req_data['ueip_optin'] : EE_Registry::instance()->CFG->core->ee_ueip_optin;
458
-
459
-		EE_Registry::instance()->CFG->currency = new EE_Currency_Config( EE_Registry::instance()->CFG->organization->CNT_ISO );
460
-
461
-		EE_Registry::instance()->CFG = apply_filters( 'FHEE__General_Settings_Admin_Page___update_your_organization_settings__CFG', EE_Registry::instance()->CFG );
438
+		if (is_main_site())
439
+			EE_Registry::instance()->NET_CFG->core->site_license_key = isset($this->_req_data['site_license_key']) ? sanitize_text_field($this->_req_data['site_license_key']) : EE_Registry::instance()->NET_CFG->core->site_license_key;
440
+		EE_Registry::instance()->CFG->organization->name = isset($this->_req_data['organization_name']) ? sanitize_text_field($this->_req_data['organization_name']) : EE_Registry::instance()->CFG->organization->name;
441
+		EE_Registry::instance()->CFG->organization->address_1 = isset($this->_req_data['organization_address_1']) ? sanitize_text_field($this->_req_data['organization_address_1']) : EE_Registry::instance()->CFG->organization->address_1;
442
+		EE_Registry::instance()->CFG->organization->address_2 = isset($this->_req_data['organization_address_2']) ? sanitize_text_field($this->_req_data['organization_address_2']) : EE_Registry::instance()->CFG->organization->address_2;
443
+		EE_Registry::instance()->CFG->organization->city = isset($this->_req_data['organization_city']) ? sanitize_text_field($this->_req_data['organization_city']) : EE_Registry::instance()->CFG->organization->city;
444
+		EE_Registry::instance()->CFG->organization->STA_ID = isset($this->_req_data['organization_state']) ? absint($this->_req_data['organization_state']) : EE_Registry::instance()->CFG->organization->STA_ID;
445
+		EE_Registry::instance()->CFG->organization->CNT_ISO = isset($this->_req_data['organization_country']) ? sanitize_text_field($this->_req_data['organization_country']) : EE_Registry::instance()->CFG->organization->CNT_ISO;
446
+		EE_Registry::instance()->CFG->organization->zip = isset($this->_req_data['organization_zip']) ? sanitize_text_field($this->_req_data['organization_zip']) : EE_Registry::instance()->CFG->organization->zip;
447
+		EE_Registry::instance()->CFG->organization->email = isset($this->_req_data['organization_email']) ? sanitize_email($this->_req_data['organization_email']) : EE_Registry::instance()->CFG->organization->email;
448
+		EE_Registry::instance()->CFG->organization->vat = isset($this->_req_data['organization_vat']) ? sanitize_text_field($this->_req_data['organization_vat']) : EE_Registry::instance()->CFG->organization->vat;
449
+		EE_Registry::instance()->CFG->organization->phone = isset($this->_req_data['organization_phone']) ? sanitize_text_field($this->_req_data['organization_phone']) : EE_Registry::instance()->CFG->organization->phone;
450
+		EE_Registry::instance()->CFG->organization->logo_url = isset($this->_req_data['organization_logo_url']) ? esc_url_raw($this->_req_data['organization_logo_url']) : EE_Registry::instance()->CFG->organization->logo_url;
451
+		EE_Registry::instance()->CFG->organization->facebook = isset($this->_req_data['organization_facebook']) ? esc_url_raw($this->_req_data['organization_facebook']) : EE_Registry::instance()->CFG->organization->facebook;
452
+		EE_Registry::instance()->CFG->organization->twitter = isset($this->_req_data['organization_twitter']) ? esc_url_raw($this->_req_data['organization_twitter']) : EE_Registry::instance()->CFG->organization->twitter;
453
+		EE_Registry::instance()->CFG->organization->linkedin = isset($this->_req_data['organization_linkedin']) ? esc_url_raw($this->_req_data['organization_linkedin']) : EE_Registry::instance()->CFG->organization->linkedin;
454
+		EE_Registry::instance()->CFG->organization->pinterest = isset($this->_req_data['organization_pinterest']) ? esc_url_raw($this->_req_data['organization_pinterest']) : EE_Registry::instance()->CFG->organization->pinterest;
455
+		EE_Registry::instance()->CFG->organization->google = isset($this->_req_data['organization_google']) ? esc_url_raw($this->_req_data['organization_google']) : EE_Registry::instance()->CFG->organization->google;
456
+		EE_Registry::instance()->CFG->organization->instagram = isset($this->_req_data['organization_instagram']) ? esc_url_raw($this->_req_data['organization_instagram']) : EE_Registry::instance()->CFG->organization->instagram;
457
+		EE_Registry::instance()->CFG->core->ee_ueip_optin = isset($this->_req_data['ueip_optin']) && ! empty($this->_req_data['ueip_optin']) ? $this->_req_data['ueip_optin'] : EE_Registry::instance()->CFG->core->ee_ueip_optin;
458
+
459
+		EE_Registry::instance()->CFG->currency = new EE_Currency_Config(EE_Registry::instance()->CFG->organization->CNT_ISO);
460
+
461
+		EE_Registry::instance()->CFG = apply_filters('FHEE__General_Settings_Admin_Page___update_your_organization_settings__CFG', EE_Registry::instance()->CFG);
462 462
 
463 463
 		$what = 'Your Organization Settings';
464
-		$success = $this->_update_espresso_configuration( $what, EE_Registry::instance()->CFG, __FILE__, __FUNCTION__, __LINE__ );
464
+		$success = $this->_update_espresso_configuration($what, EE_Registry::instance()->CFG, __FILE__, __FUNCTION__, __LINE__);
465 465
 
466
-		$this->_redirect_after_action( $success, $what, 'updated', array( 'action' => 'default' ) );
466
+		$this->_redirect_after_action($success, $what, 'updated', array('action' => 'default'));
467 467
 
468 468
 	}
469 469
 
@@ -529,7 +529,7 @@  discard block
 block discarded – undo
529 529
             ),
530 530
             'Admin Options',
531 531
             'updated',
532
-            array( 'action' => 'admin_option_settings' )
532
+            array('action' => 'admin_option_settings')
533 533
         );
534 534
 
535 535
 	}
@@ -543,20 +543,20 @@  discard block
 block discarded – undo
543 543
 
544 544
 	protected function _country_settings() {
545 545
 
546
-		$CNT_ISO = isset( EE_Registry::instance()->CFG->organization->CNT_ISO ) ? EE_Registry::instance()->CFG->organization->CNT_ISO : 'US';
547
-		$CNT_ISO = isset( $this->_req_data['country'] ) ? strtoupper( sanitize_text_field( $this->_req_data['country'] )) : $CNT_ISO;
546
+		$CNT_ISO = isset(EE_Registry::instance()->CFG->organization->CNT_ISO) ? EE_Registry::instance()->CFG->organization->CNT_ISO : 'US';
547
+		$CNT_ISO = isset($this->_req_data['country']) ? strtoupper(sanitize_text_field($this->_req_data['country'])) : $CNT_ISO;
548 548
 
549 549
 		//load field generator helper
550 550
 
551 551
 		$this->_template_args['values'] = $this->_yes_no_values;
552 552
 
553 553
 		$this->_template_args['countries'] = new EE_Question_Form_Input(
554
-				EE_Question::new_instance ( array(
554
+				EE_Question::new_instance(array(
555 555
 					'QST_ID'=> 0,
556 556
 					'QST_display_text'=> __('Select Country', 'event_espresso'),
557 557
 					'QST_system'=>'admin-country'
558 558
 				)),
559
-				EE_Answer::new_instance ( array(
559
+				EE_Answer::new_instance(array(
560 560
 					'ANS_ID' => 0,
561 561
 					'ANS_value' => $CNT_ISO
562 562
 				)),
@@ -569,14 +569,14 @@  discard block
 block discarded – undo
569 569
 			);
570 570
 //		EEH_Debug_Tools::printr( $this->_template_args['countries'], 'countries  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
571 571
 
572
-		add_filter( 'FHEE__EEH_Form_Fields__label_html', array( $this, 'country_form_field_label_wrap' ), 10, 2 );
573
-		add_filter( 'FHEE__EEH_Form_Fields__input_html', array( $this, 'country_form_field_input__wrap' ), 10, 2 );
572
+		add_filter('FHEE__EEH_Form_Fields__label_html', array($this, 'country_form_field_label_wrap'), 10, 2);
573
+		add_filter('FHEE__EEH_Form_Fields__input_html', array($this, 'country_form_field_input__wrap'), 10, 2);
574 574
 		$this->_template_args['country_details_settings'] = $this->display_country_settings();
575 575
 		$this->_template_args['country_states_settings'] = $this->display_country_states();
576 576
 
577
-		$this->_set_add_edit_form_tags( 'update_country_settings' );
578
-		$this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
579
-		$this->_template_args['admin_page_content'] = EEH_Template::display_template( GEN_SET_TEMPLATE_PATH . 'countries_settings.template.php', $this->_template_args, TRUE );
577
+		$this->_set_add_edit_form_tags('update_country_settings');
578
+		$this->_set_publish_post_box_vars(NULL, FALSE, FALSE, NULL, FALSE);
579
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(GEN_SET_TEMPLATE_PATH.'countries_settings.template.php', $this->_template_args, TRUE);
580 580
 		$this->display_admin_page_with_no_sidebar();
581 581
 	}
582 582
 
@@ -589,43 +589,43 @@  discard block
 block discarded – undo
589 589
 	 * 		@param 	string 		$CNT_ISO
590 590
 	 * 		@return 		mixed		string | array
591 591
 	 */
592
-	public function display_country_settings( $CNT_ISO = '' ) {
592
+	public function display_country_settings($CNT_ISO = '') {
593 593
 
594
-		$CNT_ISO = isset( $this->_req_data['country'] ) ? strtoupper( sanitize_text_field( $this->_req_data['country'] )) : $CNT_ISO;
595
-		if ( ! $CNT_ISO ) {
594
+		$CNT_ISO = isset($this->_req_data['country']) ? strtoupper(sanitize_text_field($this->_req_data['country'])) : $CNT_ISO;
595
+		if ( ! $CNT_ISO) {
596 596
 			return '';
597 597
 		}
598 598
 
599 599
 		// for ajax
600
-		remove_all_filters( 'FHEE__EEH_Form_Fields__label_html' );
601
-		remove_all_filters( 'FHEE__EEH_Form_Fields__input_html' );
602
-		add_filter( 'FHEE__EEH_Form_Fields__label_html', array( $this, 'country_form_field_label_wrap' ), 10, 2 );
603
-		add_filter( 'FHEE__EEH_Form_Fields__input_html', array( $this, 'country_form_field_input__wrap' ), 10, 2 );
604
-		$country = EEM_Country::instance()->get_one_by_ID( $CNT_ISO );
600
+		remove_all_filters('FHEE__EEH_Form_Fields__label_html');
601
+		remove_all_filters('FHEE__EEH_Form_Fields__input_html');
602
+		add_filter('FHEE__EEH_Form_Fields__label_html', array($this, 'country_form_field_label_wrap'), 10, 2);
603
+		add_filter('FHEE__EEH_Form_Fields__input_html', array($this, 'country_form_field_input__wrap'), 10, 2);
604
+		$country = EEM_Country::instance()->get_one_by_ID($CNT_ISO);
605 605
 		//EEH_Debug_Tools::printr( $country, '$country  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
606 606
 		$country_input_types = array(
607
-			'CNT_active' => array( 'type' => 'RADIO_BTN', 'input_name' => 'cntry[' . $CNT_ISO . ']', 'class' => '', 'options' => $this->_yes_no_values, 'use_desc_4_label' => TRUE  ),
608
-			'CNT_ISO' => array( 'type' => 'TEXT', 'input_name' => 'cntry[' . $CNT_ISO . ']', 'class' => 'small-text' ),
609
-			'CNT_ISO3' => array( 'type' => 'TEXT', 'input_name' => 'cntry[' . $CNT_ISO . ']', 'class' => 'small-text' ),
610
-			'RGN_ID' => array( 'type' => 'TEXT', 'input_name' => 'cntry[' . $CNT_ISO . ']', 'class' => 'small-text' ),
611
-			'CNT_name' => array( 'type' => 'TEXT', 'input_name' => 'cntry[' . $CNT_ISO . ']', 'class' => 'regular-text' ),
612
-			'CNT_cur_code' => array( 'type' => 'TEXT', 'input_name' => 'cntry[' . $CNT_ISO . ']', 'class' => 'small-text' ),
613
-			'CNT_cur_single' => array( 'type' => 'TEXT', 'input_name' => 'cntry[' . $CNT_ISO . ']', 'class' => 'medium-text' ),
614
-			'CNT_cur_plural' => array( 'type' => 'TEXT', 'input_name' => 'cntry[' . $CNT_ISO . ']', 'class' => 'medium-text' ),
615
-			'CNT_cur_sign' => array( 'type' => 'TEXT', 'input_name' => 'cntry[' . $CNT_ISO . ']', 'class' => 'small-text', 'htmlentities' => FALSE ),
616
-			'CNT_cur_sign_b4' => array( 'type' => 'RADIO_BTN', 'input_name' => 'cntry[' . $CNT_ISO . ']', 'class' => '', 'options' => $this->_yes_no_values, 'use_desc_4_label' => TRUE ),
617
-			'CNT_cur_dec_plc' => array( 'type' => 'RADIO_BTN', 'input_name' => 'cntry[' . $CNT_ISO . ']', 'class' => '', 'options' => array( array( 'id' => 0, 'text' => '' ), array( 'id' => 1, 'text' => '' ), array( 'id' => 2, 'text' => '' ), array( 'id' => 3, 'text' => '' ))),
618
-			'CNT_cur_dec_mrk' => array( 'type' => 'RADIO_BTN', 'input_name' => 'cntry[' . $CNT_ISO . ']', 'class' => '', 'options' => array( array( 'id' => ',', 'text' => __(', (comma)', 'event_espresso')), array( 'id' => '.', 'text' => __('. (decimal)', 'event_espresso'))), 'use_desc_4_label' => TRUE ),
619
-			'CNT_cur_thsnds' => array( 'type' => 'RADIO_BTN', 'input_name' => 'cntry[' . $CNT_ISO . ']', 'class' => '', 'options' => array( array( 'id' => ',', 'text' => __(', (comma)', 'event_espresso')), array( 'id' => '.', 'text' => __('. (decimal)', 'event_espresso'))), 'use_desc_4_label' => TRUE ),
620
-			'CNT_tel_code' => array( 'type' => 'TEXT', 'input_name' => 'cntry[' . $CNT_ISO . ']', 'class' => 'small-text' ),
621
-			'CNT_is_EU' => array( 'type' => 'RADIO_BTN', 'input_name' => 'cntry[' . $CNT_ISO . ']', 'class' => '', 'options' => $this->_yes_no_values, 'use_desc_4_label' => TRUE  )
607
+			'CNT_active' => array('type' => 'RADIO_BTN', 'input_name' => 'cntry['.$CNT_ISO.']', 'class' => '', 'options' => $this->_yes_no_values, 'use_desc_4_label' => TRUE),
608
+			'CNT_ISO' => array('type' => 'TEXT', 'input_name' => 'cntry['.$CNT_ISO.']', 'class' => 'small-text'),
609
+			'CNT_ISO3' => array('type' => 'TEXT', 'input_name' => 'cntry['.$CNT_ISO.']', 'class' => 'small-text'),
610
+			'RGN_ID' => array('type' => 'TEXT', 'input_name' => 'cntry['.$CNT_ISO.']', 'class' => 'small-text'),
611
+			'CNT_name' => array('type' => 'TEXT', 'input_name' => 'cntry['.$CNT_ISO.']', 'class' => 'regular-text'),
612
+			'CNT_cur_code' => array('type' => 'TEXT', 'input_name' => 'cntry['.$CNT_ISO.']', 'class' => 'small-text'),
613
+			'CNT_cur_single' => array('type' => 'TEXT', 'input_name' => 'cntry['.$CNT_ISO.']', 'class' => 'medium-text'),
614
+			'CNT_cur_plural' => array('type' => 'TEXT', 'input_name' => 'cntry['.$CNT_ISO.']', 'class' => 'medium-text'),
615
+			'CNT_cur_sign' => array('type' => 'TEXT', 'input_name' => 'cntry['.$CNT_ISO.']', 'class' => 'small-text', 'htmlentities' => FALSE),
616
+			'CNT_cur_sign_b4' => array('type' => 'RADIO_BTN', 'input_name' => 'cntry['.$CNT_ISO.']', 'class' => '', 'options' => $this->_yes_no_values, 'use_desc_4_label' => TRUE),
617
+			'CNT_cur_dec_plc' => array('type' => 'RADIO_BTN', 'input_name' => 'cntry['.$CNT_ISO.']', 'class' => '', 'options' => array(array('id' => 0, 'text' => ''), array('id' => 1, 'text' => ''), array('id' => 2, 'text' => ''), array('id' => 3, 'text' => ''))),
618
+			'CNT_cur_dec_mrk' => array('type' => 'RADIO_BTN', 'input_name' => 'cntry['.$CNT_ISO.']', 'class' => '', 'options' => array(array('id' => ',', 'text' => __(', (comma)', 'event_espresso')), array('id' => '.', 'text' => __('. (decimal)', 'event_espresso'))), 'use_desc_4_label' => TRUE),
619
+			'CNT_cur_thsnds' => array('type' => 'RADIO_BTN', 'input_name' => 'cntry['.$CNT_ISO.']', 'class' => '', 'options' => array(array('id' => ',', 'text' => __(', (comma)', 'event_espresso')), array('id' => '.', 'text' => __('. (decimal)', 'event_espresso'))), 'use_desc_4_label' => TRUE),
620
+			'CNT_tel_code' => array('type' => 'TEXT', 'input_name' => 'cntry['.$CNT_ISO.']', 'class' => 'small-text'),
621
+			'CNT_is_EU' => array('type' => 'RADIO_BTN', 'input_name' => 'cntry['.$CNT_ISO.']', 'class' => '', 'options' => $this->_yes_no_values, 'use_desc_4_label' => TRUE)
622 622
 		);
623
-		$this->_template_args['inputs'] = EE_Question_Form_Input::generate_question_form_inputs_for_object( $country, $country_input_types );
624
-		$country_details_settings = EEH_Template::display_template( GEN_SET_TEMPLATE_PATH . 'country_details_settings.template.php', $this->_template_args, TRUE );
623
+		$this->_template_args['inputs'] = EE_Question_Form_Input::generate_question_form_inputs_for_object($country, $country_input_types);
624
+		$country_details_settings = EEH_Template::display_template(GEN_SET_TEMPLATE_PATH.'country_details_settings.template.php', $this->_template_args, TRUE);
625 625
 
626
-		if ( defined( 'DOING_AJAX' )) {
627
-			$notices = EE_Error::get_notices( FALSE, FALSE, FALSE );
628
-			echo json_encode( array( 'return_data' => $country_details_settings, 'success' => $notices['success'], 'errors' => $notices['errors'] ));
626
+		if (defined('DOING_AJAX')) {
627
+			$notices = EE_Error::get_notices(FALSE, FALSE, FALSE);
628
+			echo json_encode(array('return_data' => $country_details_settings, 'success' => $notices['success'], 'errors' => $notices['errors']));
629 629
 			die();
630 630
 		} else {
631 631
 			return $country_details_settings;
@@ -643,49 +643,49 @@  discard block
 block discarded – undo
643 643
 	 * 		@param 	string 		$CNT_ISO
644 644
 	 * 		@return 		string
645 645
 	 */
646
-	public function display_country_states( $CNT_ISO = '' ) {
646
+	public function display_country_states($CNT_ISO = '') {
647 647
 
648
-		$CNT_ISO = isset( $this->_req_data['country'] ) ? sanitize_text_field( $this->_req_data['country'] ) : $CNT_ISO;
648
+		$CNT_ISO = isset($this->_req_data['country']) ? sanitize_text_field($this->_req_data['country']) : $CNT_ISO;
649 649
 
650
-		if ( ! $CNT_ISO ) {
650
+		if ( ! $CNT_ISO) {
651 651
 			return '';
652 652
 		}
653 653
 		// for ajax
654
-		remove_all_filters( 'FHEE__EEH_Form_Fields__label_html' );
655
-		remove_all_filters( 'FHEE__EEH_Form_Fields__input_html' );
656
-		add_filter( 'FHEE__EEH_Form_Fields__label_html', array( $this, 'state_form_field_label_wrap' ), 10, 2 );
657
-		add_filter( 'FHEE__EEH_Form_Fields__input_html', array( $this, 'state_form_field_input__wrap' ), 10, 2 );
658
-		$states = EEM_State::instance()->get_all_states_for_these_countries( array( $CNT_ISO => $CNT_ISO ));
654
+		remove_all_filters('FHEE__EEH_Form_Fields__label_html');
655
+		remove_all_filters('FHEE__EEH_Form_Fields__input_html');
656
+		add_filter('FHEE__EEH_Form_Fields__label_html', array($this, 'state_form_field_label_wrap'), 10, 2);
657
+		add_filter('FHEE__EEH_Form_Fields__input_html', array($this, 'state_form_field_input__wrap'), 10, 2);
658
+		$states = EEM_State::instance()->get_all_states_for_these_countries(array($CNT_ISO => $CNT_ISO));
659 659
 
660 660
 //			echo '<h4>$CNT_ISO : ' . $CNT_ISO . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
661 661
 //			global $wpdb;
662 662
 //			echo '<h4>' . $wpdb->last_query . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
663 663
 //			EEH_Debug_Tools::printr( $states, '$states  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
664
-		if ( $states ) {
665
-			foreach ( $states as $STA_ID => $state ) {
666
-				if ( $state instanceof EE_State ) {
664
+		if ($states) {
665
+			foreach ($states as $STA_ID => $state) {
666
+				if ($state instanceof EE_State) {
667 667
 					//STA_abbrev 	STA_name 	STA_active
668 668
 					$state_input_types = array(
669
-						'STA_abbrev' => array( 'type' => 'TEXT', 'input_name' => 'states[' . $STA_ID . ']', 'class' => 'mid-text' ),
670
-						'STA_name'   => array( 'type'       => 'TEXT', 'input_name' => 'states[' . $STA_ID . ']', 'class' => 'regular-text' ),
671
-						'STA_active' => array( 'type' => 'RADIO_BTN', 'input_name' => 'states[' . $STA_ID . ']', 'options' => $this->_yes_no_values, 'use_desc_4_label' => true )
669
+						'STA_abbrev' => array('type' => 'TEXT', 'input_name' => 'states['.$STA_ID.']', 'class' => 'mid-text'),
670
+						'STA_name'   => array('type'       => 'TEXT', 'input_name' => 'states['.$STA_ID.']', 'class' => 'regular-text'),
671
+						'STA_active' => array('type' => 'RADIO_BTN', 'input_name' => 'states['.$STA_ID.']', 'options' => $this->_yes_no_values, 'use_desc_4_label' => true)
672 672
 					);
673
-					$this->_template_args[ 'states' ][ $STA_ID ][ 'inputs' ] = EE_Question_Form_Input::generate_question_form_inputs_for_object( $state, $state_input_types );
674
-					$query_args = array( 'action'     => 'delete_state', 'STA_ID' => $STA_ID, 'CNT_ISO' => $CNT_ISO, 'STA_abbrev' => $state->abbrev() );
675
-					$this->_template_args[ 'states' ][ $STA_ID ][ 'delete_state_url' ] = EE_Admin_Page::add_query_args_and_nonce( $query_args, GEN_SET_ADMIN_URL );
673
+					$this->_template_args['states'][$STA_ID]['inputs'] = EE_Question_Form_Input::generate_question_form_inputs_for_object($state, $state_input_types);
674
+					$query_args = array('action'     => 'delete_state', 'STA_ID' => $STA_ID, 'CNT_ISO' => $CNT_ISO, 'STA_abbrev' => $state->abbrev());
675
+					$this->_template_args['states'][$STA_ID]['delete_state_url'] = EE_Admin_Page::add_query_args_and_nonce($query_args, GEN_SET_ADMIN_URL);
676 676
 				}
677 677
 			}
678 678
 		} else {
679 679
 			$this->_template_args['states'] = FALSE;
680 680
 		}
681 681
 //		EEH_Debug_Tools::printr( $this->_template_args['states'], 'states  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
682
-		$this->_template_args['add_new_state_url'] = EE_Admin_Page::add_query_args_and_nonce( array( 'action' => 'add_new_state' ),  GEN_SET_ADMIN_URL );
682
+		$this->_template_args['add_new_state_url'] = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'add_new_state'), GEN_SET_ADMIN_URL);
683 683
 
684
-		$state_details_settings = EEH_Template::display_template( GEN_SET_TEMPLATE_PATH . 'state_details_settings.template.php', $this->_template_args, TRUE );
684
+		$state_details_settings = EEH_Template::display_template(GEN_SET_TEMPLATE_PATH.'state_details_settings.template.php', $this->_template_args, TRUE);
685 685
 
686
-		if ( defined( 'DOING_AJAX' )) {
687
-			$notices = EE_Error::get_notices( FALSE, FALSE, FALSE );
688
-			echo json_encode( array( 'return_data' => $state_details_settings, 'success' => $notices['success'], 'errors' => $notices['errors'] ));
686
+		if (defined('DOING_AJAX')) {
687
+			$notices = EE_Error::get_notices(FALSE, FALSE, FALSE);
688
+			echo json_encode(array('return_data' => $state_details_settings, 'success' => $notices['success'], 'errors' => $notices['errors']));
689 689
 			die();
690 690
 		} else {
691 691
 			return $state_details_settings;
@@ -706,40 +706,39 @@  discard block
 block discarded – undo
706 706
 
707 707
 		$success = TRUE;
708 708
 
709
-		$CNT_ISO = isset( $this->_req_data['CNT_ISO'] ) ? strtoupper( sanitize_text_field( $this->_req_data['CNT_ISO'] )) : FALSE;
710
-		if ( ! $CNT_ISO ) {
711
-			EE_Error::add_error( __( 'No Country ISO code or an invalid Country ISO code was received.', 'event_espresso' ), __FILE__, __FUNCTION__, __LINE__ );
709
+		$CNT_ISO = isset($this->_req_data['CNT_ISO']) ? strtoupper(sanitize_text_field($this->_req_data['CNT_ISO'])) : FALSE;
710
+		if ( ! $CNT_ISO) {
711
+			EE_Error::add_error(__('No Country ISO code or an invalid Country ISO code was received.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
712 712
 			$success = FALSE;
713 713
 		}
714
-		$STA_abbrev = isset( $this->_req_data['STA_abbrev'] ) ? sanitize_text_field( $this->_req_data['STA_abbrev'] ) : FALSE;
715
-		if ( ! $STA_abbrev ) {
716
-			EE_Error::add_error( __( 'No State ISO code or an invalid State ISO code was received.', 'event_espresso' ), __FILE__, __FUNCTION__, __LINE__ );
714
+		$STA_abbrev = isset($this->_req_data['STA_abbrev']) ? sanitize_text_field($this->_req_data['STA_abbrev']) : FALSE;
715
+		if ( ! $STA_abbrev) {
716
+			EE_Error::add_error(__('No State ISO code or an invalid State ISO code was received.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
717 717
 			$success = FALSE;
718 718
 		}
719
-		$STA_name = isset( $this->_req_data['STA_name'] ) ?  sanitize_text_field( $this->_req_data['STA_name'] ) :
720
-			FALSE;
721
-		if ( ! $STA_name ) {
722
-			EE_Error::add_error( __( 'No State name or an invalid State name was received.', 'event_espresso' ), __FILE__, __FUNCTION__, __LINE__ );
719
+		$STA_name = isset($this->_req_data['STA_name']) ? sanitize_text_field($this->_req_data['STA_name']) : FALSE;
720
+		if ( ! $STA_name) {
721
+			EE_Error::add_error(__('No State name or an invalid State name was received.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
723 722
 			$success = FALSE;
724 723
 		}
725 724
 
726
-		if ( $success ) {
725
+		if ($success) {
727 726
 			$cols_n_values = array(
728 727
 				'CNT_ISO' => $CNT_ISO,
729 728
 				'STA_abbrev' => $STA_abbrev,
730 729
 				'STA_name' => $STA_name,
731 730
 				'STA_active' => TRUE
732 731
 			);
733
-			$success = EEM_State::instance()->insert ( $cols_n_values );
734
-			EE_Error::add_success( __( 'The State was added successfully.', 'event_espresso' ) );
732
+			$success = EEM_State::instance()->insert($cols_n_values);
733
+			EE_Error::add_success(__('The State was added successfully.', 'event_espresso'));
735 734
 		}
736 735
 
737
-		if ( defined( 'DOING_AJAX' )) {
738
-			$notices = EE_Error::get_notices( FALSE, FALSE, FALSE );
739
-			echo json_encode( array_merge( $notices, array( 'return_data' => $CNT_ISO ) ) );
736
+		if (defined('DOING_AJAX')) {
737
+			$notices = EE_Error::get_notices(FALSE, FALSE, FALSE);
738
+			echo json_encode(array_merge($notices, array('return_data' => $CNT_ISO)));
740 739
 			die();
741 740
 		} else {
742
-			$this->_redirect_after_action( $success, 'State', 'added', array( 'action' => 'country_settings' ) );
741
+			$this->_redirect_after_action($success, 'State', 'added', array('action' => 'country_settings'));
743 742
 		}
744 743
 	}
745 744
 
@@ -752,25 +751,25 @@  discard block
 block discarded – undo
752 751
 	 * 		@return 		boolean | void
753 752
 	 */
754 753
 	public function delete_state() {
755
-		$CNT_ISO = isset( $this->_req_data['CNT_ISO'] ) ? strtoupper( sanitize_text_field( $this->_req_data['CNT_ISO'] )) : FALSE;
756
-		$STA_ID = isset( $this->_req_data['STA_ID'] ) ? sanitize_text_field( $this->_req_data['STA_ID'] ) : FALSE;
757
-		$STA_abbrev = isset( $this->_req_data['STA_abbrev'] ) ? sanitize_text_field( $this->_req_data['STA_abbrev'] ) : FALSE;
758
-		if ( ! $STA_ID ) {
759
-			EE_Error::add_error( __( 'No State ID or an invalid State ID was received.', 'event_espresso' ), __FILE__, __FUNCTION__, __LINE__ );
754
+		$CNT_ISO = isset($this->_req_data['CNT_ISO']) ? strtoupper(sanitize_text_field($this->_req_data['CNT_ISO'])) : FALSE;
755
+		$STA_ID = isset($this->_req_data['STA_ID']) ? sanitize_text_field($this->_req_data['STA_ID']) : FALSE;
756
+		$STA_abbrev = isset($this->_req_data['STA_abbrev']) ? sanitize_text_field($this->_req_data['STA_abbrev']) : FALSE;
757
+		if ( ! $STA_ID) {
758
+			EE_Error::add_error(__('No State ID or an invalid State ID was received.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
760 759
 			return FALSE;
761 760
 		}
762
-		$success = EEM_State::instance()->delete_by_ID( $STA_ID );
763
-		if ( $success !== FALSE ) {
764
-			do_action( 'AHEE__General_Settings_Admin_Page__delete_state__state_deleted', $CNT_ISO, $STA_ID, array( 'STA_abbrev' => $STA_abbrev ));
765
-			EE_Error::add_success( __( 'The State was deleted successfully.', 'event_espresso' ));
761
+		$success = EEM_State::instance()->delete_by_ID($STA_ID);
762
+		if ($success !== FALSE) {
763
+			do_action('AHEE__General_Settings_Admin_Page__delete_state__state_deleted', $CNT_ISO, $STA_ID, array('STA_abbrev' => $STA_abbrev));
764
+			EE_Error::add_success(__('The State was deleted successfully.', 'event_espresso'));
766 765
 		}
767
-		if ( defined( 'DOING_AJAX' )) {
768
-			$notices = EE_Error::get_notices( FALSE, FALSE );
766
+		if (defined('DOING_AJAX')) {
767
+			$notices = EE_Error::get_notices(FALSE, FALSE);
769 768
 			$notices['return_data'] = TRUE;
770
-			echo json_encode( $notices );
769
+			echo json_encode($notices);
771 770
 			die();
772 771
 		} else {
773
-			$this->_redirect_after_action( $success, 'State', 'deleted', array( 'action' => 'country_settings' ) );
772
+			$this->_redirect_after_action($success, 'State', 'deleted', array('action' => 'country_settings'));
774 773
 		}
775 774
 	}
776 775
 
@@ -786,63 +785,63 @@  discard block
 block discarded – undo
786 785
 	protected function _update_country_settings() {
787 786
 //		EEH_Debug_Tools::printr( $this->_req_data, '$this->_req_data  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
788 787
 		// grab the country ISO code
789
-		$CNT_ISO = isset( $this->_req_data['country'] ) ? strtoupper( sanitize_text_field( $this->_req_data['country'] )) : FALSE;
790
-		if ( ! $CNT_ISO ) {
791
-			EE_Error::add_error( __( 'No Country ISO code or an invalid Country ISO code was received.', 'event_espresso' ), __FILE__, __FUNCTION__, __LINE__ );
788
+		$CNT_ISO = isset($this->_req_data['country']) ? strtoupper(sanitize_text_field($this->_req_data['country'])) : FALSE;
789
+		if ( ! $CNT_ISO) {
790
+			EE_Error::add_error(__('No Country ISO code or an invalid Country ISO code was received.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
792 791
 			return;
793 792
 		}
794 793
 		$cols_n_values = array();
795
-		$cols_n_values['CNT_ISO3'] = isset( $this->_req_data['cntry'][$CNT_ISO]['CNT_ISO3'] ) ? strtoupper( sanitize_text_field( $this->_req_data['cntry'][$CNT_ISO]['CNT_ISO3'] )) : FALSE;
796
-		$cols_n_values['RGN_ID'] = isset( $this->_req_data['cntry'][$CNT_ISO]['RGN_ID'] ) ? absint( $this->_req_data['cntry'][$CNT_ISO]['RGN_ID'] ) : NULL;
797
-		$cols_n_values['CNT_name'] = isset( $this->_req_data['cntry'][$CNT_ISO]['CNT_name'] ) ? sanitize_text_field( $this->_req_data['cntry'][$CNT_ISO]['CNT_name'] ) : NULL;
798
-		$cols_n_values['CNT_cur_code'] = isset( $this->_req_data['cntry'][$CNT_ISO]['CNT_cur_code'] ) ? strtoupper( sanitize_text_field( $this->_req_data['cntry'][$CNT_ISO]['CNT_cur_code'] )) : 'USD';
799
-		$cols_n_values['CNT_cur_single'] = isset( $this->_req_data['cntry'][$CNT_ISO]['CNT_cur_single'] ) ? sanitize_text_field( $this->_req_data['cntry'][$CNT_ISO]['CNT_cur_single'] ) : 'dollar';
800
-		$cols_n_values['CNT_cur_plural'] = isset( $this->_req_data['cntry'][$CNT_ISO]['CNT_cur_plural'] ) ? sanitize_text_field( $this->_req_data['cntry'][$CNT_ISO]['CNT_cur_plural'] ) : 'dollars';
801
-		$cols_n_values['CNT_cur_sign'] = isset( $this->_req_data['cntry'][$CNT_ISO]['CNT_cur_sign'] ) ? sanitize_text_field( $this->_req_data['cntry'][$CNT_ISO]['CNT_cur_sign'] ) : '$';
802
-		$cols_n_values['CNT_cur_sign_b4'] = isset( $this->_req_data['cntry'][$CNT_ISO]['CNT_cur_sign_b4'] ) ? absint( $this->_req_data['cntry'][$CNT_ISO]['CNT_cur_sign_b4'] ) : TRUE;
803
-		$cols_n_values['CNT_cur_dec_plc'] = isset( $this->_req_data['cntry'][$CNT_ISO]['CNT_cur_dec_plc'] ) ? absint( $this->_req_data['cntry'][$CNT_ISO]['CNT_cur_dec_plc'] ) : 2;
804
-		$cols_n_values['CNT_cur_dec_mrk'] = isset( $this->_req_data['cntry'][$CNT_ISO]['CNT_cur_dec_mrk'] ) ? sanitize_text_field( $this->_req_data['cntry'][$CNT_ISO]['CNT_cur_dec_mrk'] ) : '.';
805
-		$cols_n_values['CNT_cur_thsnds'] = isset( $this->_req_data['cntry'][$CNT_ISO]['CNT_cur_thsnds'] ) ? sanitize_text_field( $this->_req_data['cntry'][$CNT_ISO]['CNT_cur_thsnds'] ) : ',';
806
-		$cols_n_values['CNT_tel_code'] = isset( $this->_req_data['cntry'][$CNT_ISO]['CNT_tel_code'] ) ? sanitize_text_field( $this->_req_data['cntry'][$CNT_ISO]['CNT_tel_code'] ) : NULL;
807
-		$cols_n_values['CNT_is_EU'] = isset( $this->_req_data['cntry'][$CNT_ISO]['CNT_is_EU'] ) ? absint( $this->_req_data['cntry'][$CNT_ISO]['CNT_is_EU'] ) : FALSE;
808
-		$cols_n_values['CNT_active'] = isset( $this->_req_data['cntry'][$CNT_ISO]['CNT_active'] ) ? absint( $this->_req_data['cntry'][$CNT_ISO]['CNT_active'] ) : FALSE;
794
+		$cols_n_values['CNT_ISO3'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_ISO3']) ? strtoupper(sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_ISO3'])) : FALSE;
795
+		$cols_n_values['RGN_ID'] = isset($this->_req_data['cntry'][$CNT_ISO]['RGN_ID']) ? absint($this->_req_data['cntry'][$CNT_ISO]['RGN_ID']) : NULL;
796
+		$cols_n_values['CNT_name'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_name']) ? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_name']) : NULL;
797
+		$cols_n_values['CNT_cur_code'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_code']) ? strtoupper(sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_code'])) : 'USD';
798
+		$cols_n_values['CNT_cur_single'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_single']) ? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_single']) : 'dollar';
799
+		$cols_n_values['CNT_cur_plural'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_plural']) ? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_plural']) : 'dollars';
800
+		$cols_n_values['CNT_cur_sign'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_sign']) ? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_sign']) : '$';
801
+		$cols_n_values['CNT_cur_sign_b4'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_sign_b4']) ? absint($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_sign_b4']) : TRUE;
802
+		$cols_n_values['CNT_cur_dec_plc'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_dec_plc']) ? absint($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_dec_plc']) : 2;
803
+		$cols_n_values['CNT_cur_dec_mrk'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_dec_mrk']) ? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_dec_mrk']) : '.';
804
+		$cols_n_values['CNT_cur_thsnds'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_thsnds']) ? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_cur_thsnds']) : ',';
805
+		$cols_n_values['CNT_tel_code'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_tel_code']) ? sanitize_text_field($this->_req_data['cntry'][$CNT_ISO]['CNT_tel_code']) : NULL;
806
+		$cols_n_values['CNT_is_EU'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_is_EU']) ? absint($this->_req_data['cntry'][$CNT_ISO]['CNT_is_EU']) : FALSE;
807
+		$cols_n_values['CNT_active'] = isset($this->_req_data['cntry'][$CNT_ISO]['CNT_active']) ? absint($this->_req_data['cntry'][$CNT_ISO]['CNT_active']) : FALSE;
809 808
 		// allow filtering of country data
810
-		$cols_n_values = apply_filters( 'FHEE__General_Settings_Admin_Page___update_country_settings__cols_n_values', $cols_n_values );
809
+		$cols_n_values = apply_filters('FHEE__General_Settings_Admin_Page___update_country_settings__cols_n_values', $cols_n_values);
811 810
 		//EEH_Debug_Tools::printr( $cols_n_values, '$cols_n_values  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
812 811
 		// where values
813
-		$where_cols_n_values = array( array( 'CNT_ISO' => $CNT_ISO ));
812
+		$where_cols_n_values = array(array('CNT_ISO' => $CNT_ISO));
814 813
 		// run the update
815
-		$success = EEM_Country::instance()->update( $cols_n_values, $where_cols_n_values );
814
+		$success = EEM_Country::instance()->update($cols_n_values, $where_cols_n_values);
816 815
 //		global $wpdb;
817 816
 //		echo '<h4>' . $wpdb->last_query . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
818 817
 //		echo '<h4>$success : ' . $success . '  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span></h4>';
819
-		if ( isset( $this->_req_data['states'] ) && is_array( $this->_req_data['states'] ) && $success !== FALSE ) {
818
+		if (isset($this->_req_data['states']) && is_array($this->_req_data['states']) && $success !== FALSE) {
820 819
 			// allow filtering of states data
821
-			$states = apply_filters( 'FHEE__General_Settings_Admin_Page___update_country_settings__states', $this->_req_data['states'] );
820
+			$states = apply_filters('FHEE__General_Settings_Admin_Page___update_country_settings__states', $this->_req_data['states']);
822 821
 //			EEH_Debug_Tools::printr( $states, '$states  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
823 822
 			// loop thru state data ( looks like : states[75][STA_name] )
824
-			foreach( $states as $STA_ID => $state ) {
823
+			foreach ($states as $STA_ID => $state) {
825 824
 				$cols_n_values = array(
826 825
 					'CNT_ISO' 		=> $CNT_ISO,
827
-					'STA_abbrev' => sanitize_text_field( $state['STA_abbrev'] ),
828
-					'STA_name' 	=> sanitize_text_field( $state['STA_name'] ),
829
-					'STA_active' 	=> (bool)absint( $state['STA_active'] )
826
+					'STA_abbrev' => sanitize_text_field($state['STA_abbrev']),
827
+					'STA_name' 	=> sanitize_text_field($state['STA_name']),
828
+					'STA_active' 	=> (bool) absint($state['STA_active'])
830 829
 				);
831 830
 				// where values
832
-				$where_cols_n_values = array( array( 'STA_ID' => $STA_ID ));
831
+				$where_cols_n_values = array(array('STA_ID' => $STA_ID));
833 832
 				// run the update
834
-				$success = EEM_State::instance()->update( $cols_n_values, $where_cols_n_values );
835
-				if ( $success !== FALSE ) {
836
-					do_action( 'AHEE__General_Settings_Admin_Page__update_country_settings__state_saved', $CNT_ISO, $STA_ID, $cols_n_values );
833
+				$success = EEM_State::instance()->update($cols_n_values, $where_cols_n_values);
834
+				if ($success !== FALSE) {
835
+					do_action('AHEE__General_Settings_Admin_Page__update_country_settings__state_saved', $CNT_ISO, $STA_ID, $cols_n_values);
837 836
 				}
838 837
 			}
839 838
 		}
840 839
 		// check if country being edited matches org option country, and if so, then  update EE_Config with new settings
841
-		if ( isset( EE_Registry::instance()->CFG->organization->CNT_ISO ) && $CNT_ISO == EE_Registry::instance()->CFG->organization->CNT_ISO ) {
842
-			EE_Registry::instance()->CFG->currency = new EE_Currency_Config( $CNT_ISO );
840
+		if (isset(EE_Registry::instance()->CFG->organization->CNT_ISO) && $CNT_ISO == EE_Registry::instance()->CFG->organization->CNT_ISO) {
841
+			EE_Registry::instance()->CFG->currency = new EE_Currency_Config($CNT_ISO);
843 842
 			EE_Registry::instance()->CFG->update_espresso_config();
844 843
 		}
845
-		$this->_redirect_after_action( $success, 'Countries', 'updated', array( 'action' => 'country_settings', 'country' => $CNT_ISO ));
844
+		$this->_redirect_after_action($success, 'Countries', 'updated', array('action' => 'country_settings', 'country' => $CNT_ISO));
846 845
 	}
847 846
 
848 847
 
@@ -856,11 +855,11 @@  discard block
 block discarded – undo
856 855
 	 * 		@param 		string 		$label
857 856
 	 * 		@return 		string
858 857
 	 */
859
-	public function country_form_field_label_wrap( $label, $required_text ) {
858
+	public function country_form_field_label_wrap($label, $required_text) {
860 859
 		return '
861 860
 			<tr>
862 861
 				<th>
863
-					' . $label  . '
862
+					' . $label.'
864 863
 				</th>';
865 864
 	}
866 865
 
@@ -874,10 +873,10 @@  discard block
 block discarded – undo
874 873
 	 * 		@param 		string 		$label
875 874
 	 * 		@return 		string
876 875
 	 */
877
-	public function country_form_field_input__wrap( $input, $label ) {
876
+	public function country_form_field_input__wrap($input, $label) {
878 877
 		return '
879 878
 				<td class="general-settings-country-input-td">
880
-					' . $input . '
879
+					' . $input.'
881 880
 				</td>
882 881
 			</tr>';
883 882
 	}
@@ -893,7 +892,7 @@  discard block
 block discarded – undo
893 892
 	 * 		@param 		string 		$required_text
894 893
 	 * 		@return 		string
895 894
 	 */
896
-	public function state_form_field_label_wrap( $label, $required_text  ) {
895
+	public function state_form_field_label_wrap($label, $required_text) {
897 896
 		return $required_text;
898 897
 	}
899 898
 
@@ -907,10 +906,10 @@  discard block
 block discarded – undo
907 906
 	 * 		@param 		string 		$label
908 907
 	 * 		@return 		string
909 908
 	 */
910
-	public function state_form_field_input__wrap( $input, $label ) {
909
+	public function state_form_field_input__wrap($input, $label) {
911 910
 		return '
912 911
 				<td class="general-settings-country-state-input-td">
913
-					' . $input . '
912
+					' . $input.'
914 913
 				</td>';
915 914
 
916 915
 	}
@@ -933,10 +932,10 @@  discard block
 block discarded – undo
933 932
 	 * @param int $ee_page_id
934 933
 	 * @return string
935 934
 	 */
936
-	public static function edit_view_links( $ee_page_id ) {
937
-		$links = '<a href="' . add_query_arg( array( 'post' => $ee_page_id, 'action' => 'edit' ),  admin_url( 'post.php' )) . '" >' . __('Edit', 'event_espresso') . '</a>';
935
+	public static function edit_view_links($ee_page_id) {
936
+		$links = '<a href="'.add_query_arg(array('post' => $ee_page_id, 'action' => 'edit'), admin_url('post.php')).'" >'.__('Edit', 'event_espresso').'</a>';
938 937
 		$links .= ' &nbsp;|&nbsp; ';
939
-		$links .= '<a href="' . get_permalink( $ee_page_id ) . '" >' . __('View', 'event_espresso') . '</a>';
938
+		$links .= '<a href="'.get_permalink($ee_page_id).'" >'.__('View', 'event_espresso').'</a>';
940 939
 		return $links;
941 940
 	}
942 941
 
@@ -949,27 +948,27 @@  discard block
 block discarded – undo
949 948
 	 * @param WP page object $ee_page
950 949
 	 * @return string
951 950
 	 */
952
-	public static function page_and_shortcode_status( $ee_page, $shortcode ) {
951
+	public static function page_and_shortcode_status($ee_page, $shortcode) {
953 952
 
954 953
 		// page status
955
-		if ( isset( $ee_page->post_status ) && $ee_page->post_status == 'publish') {
954
+		if (isset($ee_page->post_status) && $ee_page->post_status == 'publish') {
956 955
 			$pg_colour = 'green';
957
-			$pg_status = sprintf( __('Page%sStatus%sOK', 'event_espresso'), '&nbsp;' , '&nbsp;' );
956
+			$pg_status = sprintf(__('Page%sStatus%sOK', 'event_espresso'), '&nbsp;', '&nbsp;');
958 957
 		 } else {
959 958
 			$pg_colour = 'red';
960
-			$pg_status = sprintf( __('Page%sVisibility%sProblem', 'event_espresso'), '&nbsp;', '&nbsp;'  );
959
+			$pg_status = sprintf(__('Page%sVisibility%sProblem', 'event_espresso'), '&nbsp;', '&nbsp;');
961 960
 		}
962 961
 
963 962
 		// shortcode status
964
-		if ( isset( $ee_page->post_content ) && strpos( $ee_page->post_content, $shortcode ) !== FALSE ) {
963
+		if (isset($ee_page->post_content) && strpos($ee_page->post_content, $shortcode) !== FALSE) {
965 964
 			$sc_colour = 'green';
966
-			$sc_status = sprintf( __('Shortcode%sOK', 'event_espresso'), '&nbsp;' );
965
+			$sc_status = sprintf(__('Shortcode%sOK', 'event_espresso'), '&nbsp;');
967 966
 		 } else {
968 967
 			$sc_colour = 'red';
969
-			$sc_status = sprintf( __('Shortcode%sProblem', 'event_espresso'), '&nbsp;' );
968
+			$sc_status = sprintf(__('Shortcode%sProblem', 'event_espresso'), '&nbsp;');
970 969
 		}
971 970
 
972
-		return '<span style="color:' . $pg_colour . '; margin-right:2em;"><strong>' . $pg_status . '</strong></span><span style="color:' . $sc_colour . '"><strong>' . $sc_status . '</strong></span>';
971
+		return '<span style="color:'.$pg_colour.'; margin-right:2em;"><strong>'.$pg_status.'</strong></span><span style="color:'.$sc_colour.'"><strong>'.$sc_status.'</strong></span>';
973 972
 
974 973
 	}
975 974
 
@@ -984,20 +983,20 @@  discard block
 block discarded – undo
984 983
 	 * @param unknown_type $level
985 984
 	 * @return unknown
986 985
 	 */
987
-	public static function page_settings_dropdown( $default = 0, $parent = 0, $level = 0 ) {
986
+	public static function page_settings_dropdown($default = 0, $parent = 0, $level = 0) {
988 987
 		global $wpdb;
989
-		$items = $wpdb->get_results( $wpdb->prepare("SELECT ID, post_parent, post_title FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'page' AND post_status != 'trash' ORDER BY menu_order", $parent) );
988
+		$items = $wpdb->get_results($wpdb->prepare("SELECT ID, post_parent, post_title FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'page' AND post_status != 'trash' ORDER BY menu_order", $parent));
990 989
 
991
-		if ( $items ) {
992
-			foreach ( $items as $item ) {
993
-				$pad = str_repeat( '&nbsp;', $level * 3 );
994
-				if ( $item->ID == $default)
990
+		if ($items) {
991
+			foreach ($items as $item) {
992
+				$pad = str_repeat('&nbsp;', $level * 3);
993
+				if ($item->ID == $default)
995 994
 					$current = ' selected="selected"';
996 995
 				else
997 996
 					$current = '';
998 997
 
999
-				echo "\n\t<option class='level-$level' value='$item->ID'$current>$pad " . esc_html($item->post_title) . "</option>";
1000
-				parent_dropdown( $default, $item->ID, $level +1 );
998
+				echo "\n\t<option class='level-$level' value='$item->ID'$current>$pad ".esc_html($item->post_title)."</option>";
999
+				parent_dropdown($default, $item->ID, $level + 1);
1001 1000
 			}
1002 1001
 		} else {
1003 1002
 			return false;
Please login to merge, or discard this patch.
core/request_stack/EE_Request.core.php 2 patches
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * class EE_Request
@@ -133,10 +133,10 @@  discard block
 block discarded – undo
133 133
 	public function set( $key, $value, $override_ee = FALSE ) {
134 134
 		// don't allow "ee" to be overwritten unless explicitly instructed to do so
135 135
 		if (
136
-		    $key !== 'ee'
137
-            || ( $key === 'ee' && empty( $this->_params['ee'] ))
138
-            || ( $key === 'ee' && ! empty( $this->_params['ee'] ) && $override_ee )
139
-        ) {
136
+			$key !== 'ee'
137
+			|| ( $key === 'ee' && empty( $this->_params['ee'] ))
138
+			|| ( $key === 'ee' && ! empty( $this->_params['ee'] ) && $override_ee )
139
+		) {
140 140
 			$this->_params[ $key ] = $value;
141 141
 		}
142 142
 	}
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -69,15 +69,15 @@  discard block
 block discarded – undo
69 69
 	 * @param array $post
70 70
 	 * @param array $cookie
71 71
 	 */
72
-	public function __construct( $get, $post, $cookie ) {
72
+	public function __construct($get, $post, $cookie) {
73 73
 		// grab request vars
74 74
 		$this->_get    = (array) $get;
75 75
 		$this->_post   = (array) $post;
76 76
 		$this->_cookie = (array) $cookie;
77 77
 		$this->_params = array_merge($this->_get, $this->_post);
78 78
 		// AJAX ???
79
-		$this->ajax       = defined( 'DOING_AJAX' ) ? true : false;
80
-		$this->front_ajax = $this->is_set( 'ee_front_ajax' ) && (int) $this->get( 'ee_front_ajax' ) === 1;
79
+		$this->ajax       = defined('DOING_AJAX') ? true : false;
80
+		$this->front_ajax = $this->is_set('ee_front_ajax') && (int) $this->get('ee_front_ajax') === 1;
81 81
 		// grab user IP
82 82
 		$this->_ip_address = $this->_visitor_ip();
83 83
 	}
@@ -130,14 +130,14 @@  discard block
 block discarded – undo
130 130
 	 * @param bool $override_ee
131 131
 	 * @return    void
132 132
 	 */
133
-	public function set( $key, $value, $override_ee = FALSE ) {
133
+	public function set($key, $value, $override_ee = FALSE) {
134 134
 		// don't allow "ee" to be overwritten unless explicitly instructed to do so
135 135
 		if (
136 136
 		    $key !== 'ee'
137
-            || ( $key === 'ee' && empty( $this->_params['ee'] ))
138
-            || ( $key === 'ee' && ! empty( $this->_params['ee'] ) && $override_ee )
137
+            || ($key === 'ee' && empty($this->_params['ee']))
138
+            || ($key === 'ee' && ! empty($this->_params['ee']) && $override_ee)
139 139
         ) {
140
-			$this->_params[ $key ] = $value;
140
+			$this->_params[$key] = $value;
141 141
 		}
142 142
 	}
143 143
 
@@ -151,8 +151,8 @@  discard block
 block discarded – undo
151 151
 	 * @param null $default
152 152
 	 * @return    mixed
153 153
 	 */
154
-	public function get( $key, $default = NULL ) {
155
-		return isset( $this->_params[ $key ] ) ? $this->_params[ $key ] : $default;
154
+	public function get($key, $default = NULL) {
155
+		return isset($this->_params[$key]) ? $this->_params[$key] : $default;
156 156
 	}
157 157
 
158 158
 
@@ -164,8 +164,8 @@  discard block
 block discarded – undo
164 164
 	 * @param $key
165 165
 	 * @return    boolean
166 166
 	 */
167
-	public function is_set( $key ) {
168
-		return isset( $this->_params[ $key ] ) ? TRUE : FALSE;
167
+	public function is_set($key) {
168
+		return isset($this->_params[$key]) ? TRUE : FALSE;
169 169
 	}
170 170
 
171 171
 
@@ -177,10 +177,10 @@  discard block
 block discarded – undo
177 177
 	 * @param $key
178 178
 	 * @param bool $unset_from_global_too
179 179
 	 */
180
-	public function un_set( $key, $unset_from_global_too = false ) {
181
-		unset( $this->_params[ $key ] );
182
-		if ( $unset_from_global_too ) {
183
-			unset( $_REQUEST[ $key ] );
180
+	public function un_set($key, $unset_from_global_too = false) {
181
+		unset($this->_params[$key]);
182
+		if ($unset_from_global_too) {
183
+			unset($_REQUEST[$key]);
184 184
 		}
185 185
 	}
186 186
 
@@ -214,10 +214,10 @@  discard block
 block discarded – undo
214 214
 			'HTTP_FORWARDED',
215 215
 			'REMOTE_ADDR'
216 216
 		);
217
-		foreach ( $server_keys as $key ) {
218
-			if ( isset( $_SERVER[ $key ] ) ) {
219
-				foreach ( array_map( 'trim', explode( ',', $_SERVER[ $key ] ) ) as $ip ) {
220
-					if ( $ip === '127.0.0.1' || filter_var( $ip, FILTER_VALIDATE_IP ) !== false ) {
217
+		foreach ($server_keys as $key) {
218
+			if (isset($_SERVER[$key])) {
219
+				foreach (array_map('trim', explode(',', $_SERVER[$key])) as $ip) {
220
+					if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
221 221
 						$visitor_ip = $ip;
222 222
 					}
223 223
 				}
Please login to merge, or discard this patch.
admin_pages/registrations/EE_Registrations_List_Table.class.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -227,7 +227,7 @@
 block discarded – undo
227 227
      *    _get_table_filters
228 228
      *
229 229
      * @access protected
230
-     * @return array
230
+     * @return string[]
231 231
      */
232 232
     protected function _get_table_filters()
233 233
     {
Please login to merge, or discard this patch.
Spacing   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
         );
158 158
         $this->_primary_column = '_REG_ID';
159 159
         $this->_sortable_columns = array(
160
-            '_REG_date'     => array('_REG_date' => true),   //true means its already sorted
160
+            '_REG_date'     => array('_REG_date' => true), //true means its already sorted
161 161
             'ATT_fname'     => array('ATT_fname' => false),
162 162
             'event_name'    => array('event_name' => false),
163 163
             'DTT_EVT_start' => array('DTT_EVT_start' => false),
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
     {
180 180
         $class = parent::_get_row_class($item);
181 181
         //add status class
182
-        $class .= ' ee-status-strip reg-status-' . $item->status_ID();
182
+        $class .= ' ee-status-strip reg-status-'.$item->status_ID();
183 183
         if ($this->_has_checkbox_column) {
184 184
             $class .= ' has-checkbox-column';
185 185
         }
@@ -327,11 +327,11 @@  discard block
 block discarded – undo
327 327
         //setup date query.
328 328
         $beginning_string = EEM_Registration::instance()
329 329
                                             ->convert_datetime_for_query('REG_date',
330
-                                                $this_year_r . '-' . $this_month_r . '-01' . ' ' . $time_start,
330
+                                                $this_year_r.'-'.$this_month_r.'-01'.' '.$time_start,
331 331
                                                 'Y-m-d H:i:s');
332 332
         $end_string = EEM_Registration::instance()
333 333
                                       ->convert_datetime_for_query('REG_date',
334
-                                          $this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' ' . $time_end,
334
+                                          $this_year_r.'-'.$this_month_r.'-'.$days_this_month.' '.$time_end,
335 335
                                           'Y-m-d H:i:s');
336 336
         $_where['REG_date'] = array(
337 337
             'BETWEEN',
@@ -364,9 +364,9 @@  discard block
 block discarded – undo
364 364
             'BETWEEN',
365 365
             array(
366 366
                 EEM_Registration::instance()
367
-                                ->convert_datetime_for_query('REG_date', $current_date . $time_start, 'Y-m-d H:i:s'),
367
+                                ->convert_datetime_for_query('REG_date', $current_date.$time_start, 'Y-m-d H:i:s'),
368 368
                 EEM_Registration::instance()
369
-                                ->convert_datetime_for_query('REG_date', $current_date . $time_end, 'Y-m-d H:i:s'),
369
+                                ->convert_datetime_for_query('REG_date', $current_date.$time_end, 'Y-m-d H:i:s'),
370 370
             ),
371 371
         );
372 372
         $_where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
@@ -410,8 +410,8 @@  discard block
 block discarded – undo
410 410
         $content .= '<div class="show-on-mobile-view-only">';
411 411
         $content .= '<br>';
412 412
         $content .= $attendee instanceof EE_Attendee ? $attendee->full_name() : '';
413
-        $content .= '&nbsp;' . sprintf(__('(%1$s / %2$s)', 'event_espresso'), $item->count(), $item->group_size());
414
-        $content .= '<br>' . sprintf(__('Reg Code: %s', 'event_espresso'), $item->get('REG_code'));
413
+        $content .= '&nbsp;'.sprintf(__('(%1$s / %2$s)', 'event_espresso'), $item->count(), $item->group_size());
414
+        $content .= '<br>'.sprintf(__('Reg Code: %s', 'event_espresso'), $item->get('REG_code'));
415 415
         $content .= '</div>';
416 416
         return $content;
417 417
     }
@@ -482,10 +482,10 @@  discard block
 block discarded – undo
482 482
                   . $event_name
483 483
                   . '</a>' : $event_name;
484 484
             $edit_event_url = EE_Admin_Page::add_query_args_and_nonce(array('event_id' => $EVT_ID), REG_ADMIN_URL);
485
-            $actions['event_filter'] = '<a href="' . $edit_event_url . '" title="';
485
+            $actions['event_filter'] = '<a href="'.$edit_event_url.'" title="';
486 486
             $actions['event_filter'] .= sprintf(esc_attr__('Filter this list to only show registrations for %s',
487 487
                 'event_espresso'), $event_name);
488
-            $actions['event_filter'] .= '">' . __('View Registrations', 'event_espresso') . '</a>';
488
+            $actions['event_filter'] .= '">'.__('View Registrations', 'event_espresso').'</a>';
489 489
         } else {
490 490
             $edit_event = $event_name;
491 491
             $actions['event_filter'] = '';
@@ -551,12 +551,12 @@  discard block
 block discarded – undo
551 551
         $t = $item->get_first_related('Transaction');
552 552
         $payment_count = $t instanceof EE_Transaction ? $t->count_related('Payment') : 0;
553 553
         //append group count to name
554
-        $link .= '&nbsp;' . sprintf(__('(%1$s / %2$s)', 'event_espresso'), $item->count(), $item->group_size());
554
+        $link .= '&nbsp;'.sprintf(__('(%1$s / %2$s)', 'event_espresso'), $item->count(), $item->group_size());
555 555
         //append reg_code
556
-        $link .= '<br>' . sprintf(__('Reg Code: %s', 'event_espresso'), $item->get('REG_code'));
556
+        $link .= '<br>'.sprintf(__('Reg Code: %s', 'event_espresso'), $item->get('REG_code'));
557 557
         //reg status text for accessibility
558
-        $link .= '<br><span class="ee-status-text-small">' . EEH_Template::pretty_status($item->status_ID(), false,
559
-                'sentence') . '</span>';
558
+        $link .= '<br><span class="ee-status-text-small">'.EEH_Template::pretty_status($item->status_ID(), false,
559
+                'sentence').'</span>';
560 560
         //trash/restore/delete actions
561 561
         $actions = array();
562 562
         if ($this->_view !== 'trash'
@@ -568,8 +568,8 @@  discard block
 block discarded – undo
568 568
                 'action'  => 'trash_registrations',
569 569
                 '_REG_ID' => $item->ID(),
570 570
             ), REG_ADMIN_URL);
571
-            $actions['trash'] = '<a href="' . $trash_lnk_url . '" title="' . esc_attr__('Trash Registration',
572
-                    'event_espresso') . '">' . __('Trash', 'event_espresso') . '</a>';
571
+            $actions['trash'] = '<a href="'.$trash_lnk_url.'" title="'.esc_attr__('Trash Registration',
572
+                    'event_espresso').'">'.__('Trash', 'event_espresso').'</a>';
573 573
         } elseif ($this->_view === 'trash') {
574 574
             // restore registration link
575 575
             if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registration',
@@ -579,8 +579,8 @@  discard block
 block discarded – undo
579 579
                     'action'  => 'restore_registrations',
580 580
                     '_REG_ID' => $item->ID(),
581 581
                 ), REG_ADMIN_URL);
582
-                $actions['restore'] = '<a href="' . $restore_lnk_url . '" title="' . esc_attr__('Restore Registration',
583
-                        'event_espresso') . '">' . __('Restore', 'event_espresso') . '</a>';
582
+                $actions['restore'] = '<a href="'.$restore_lnk_url.'" title="'.esc_attr__('Restore Registration',
583
+                        'event_espresso').'">'.__('Restore', 'event_espresso').'</a>';
584 584
             }
585 585
             if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registration',
586 586
                 'espresso_registrations_ee_delete_registrations', $item->ID())
@@ -648,7 +648,7 @@  discard block
 block discarded – undo
648 648
                                                                               . $ticket->name()
649 649
                                                                               . '</span><br />' : '';
650 650
         if ($item->final_price() > 0) {
651
-            $content .= '<span class="reg-pad-rght">' . $item->pretty_final_price() . '</span>';
651
+            $content .= '<span class="reg-pad-rght">'.$item->pretty_final_price().'</span>';
652 652
         } else {
653 653
             // free event
654 654
             $content .= '<span class="reg-overview-free-event-spn reg-pad-rght">'
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
             : '<span class="TKT_name">'
676 676
               . $ticket->name()
677 677
               . '</span><br />';
678
-        $content .= '<span class="reg-pad-rght">' . $item->pretty_final_price() . '</span>';
678
+        $content .= '<span class="reg-pad-rght">'.$item->pretty_final_price().'</span>';
679 679
         return $content;
680 680
     }
681 681
 
@@ -693,10 +693,10 @@  discard block
 block discarded – undo
693 693
         $payment_method = $item->payment_method();
694 694
         $payment_method_name = $payment_method instanceof EE_Payment_Method ? $payment_method->admin_name()
695 695
             : __('Unknown', 'event_espresso');
696
-        $content = '<span class="reg-pad-rght">' . $item->pretty_paid() . '</span>';
696
+        $content = '<span class="reg-pad-rght">'.$item->pretty_paid().'</span>';
697 697
         if ($item->paid() > 0) {
698
-            $content .= '<br><span class="ee-status-text-small">' . sprintf(__('...via %s', 'event_espresso'),
699
-                    $payment_method_name) . '</span>';
698
+            $content .= '<br><span class="ee-status-text-small">'.sprintf(__('...via %s', 'event_espresso'),
699
+                    $payment_method_name).'</span>';
700 700
         }
701 701
         return $content;
702 702
     }
@@ -728,7 +728,7 @@  discard block
 block discarded – undo
728 728
                   . esc_attr__('View Transaction', 'event_espresso')
729 729
                   . '">'
730 730
                   . $item->transaction()->pretty_total()
731
-                  . '</a></span>' : '<span class="reg-pad-rght">' . $item->transaction()->pretty_total() . '</span>';
731
+                  . '</a></span>' : '<span class="reg-pad-rght">'.$item->transaction()->pretty_total().'</span>';
732 732
         } else {
733 733
             return __("None", "event_espresso");
734 734
         }
@@ -765,7 +765,7 @@  discard block
 block discarded – undo
765 765
                       . esc_attr__('View Transaction', 'event_espresso')
766 766
                       . '">'
767 767
                       . $item->transaction()->pretty_paid()
768
-                      . '</a><span>' : '<span class="reg-pad-rght">' . $item->transaction()->pretty_paid() . '</span>';
768
+                      . '</a><span>' : '<span class="reg-pad-rght">'.$item->transaction()->pretty_paid().'</span>';
769 769
             }
770 770
         }
771 771
         return '&nbsp;';
@@ -805,7 +805,7 @@  discard block
 block discarded – undo
805 805
         $actions['view_lnk'] = EE_Registry::instance()->CAP->current_user_can('ee_read_registration',
806 806
             'espresso_registrations_view_registration', $item->ID()) ? '
807 807
 			<li>
808
-			<a href="' . $view_lnk_url . '" title="' . esc_attr__('View Registration Details', 'event_espresso') . '" class="tiny-text">
808
+			<a href="' . $view_lnk_url.'" title="'.esc_attr__('View Registration Details', 'event_espresso').'" class="tiny-text">
809 809
 				<div class="dashicons dashicons-clipboard"></div>
810 810
 			</a>
811 811
 			</li>' : '';
@@ -813,7 +813,7 @@  discard block
 block discarded – undo
813 813
             'espresso_registrations_edit_attendee')
814 814
                                && $attendee instanceof EE_Attendee ? '
815 815
 			<li>
816
-			<a href="' . $edit_lnk_url . '" title="' . esc_attr__('Edit Contact Details', 'event_espresso') . '" class="tiny-text">
816
+			<a href="' . $edit_lnk_url.'" title="'.esc_attr__('Edit Contact Details', 'event_espresso').'" class="tiny-text">
817 817
 				<div class="ee-icon ee-icon-user-edit ee-icon-size-16"></div>
818 818
 			</a>
819 819
 			</li>' : '';
Please login to merge, or discard this patch.
Indentation   +818 added lines, -818 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -26,847 +26,847 @@  discard block
 block discarded – undo
26 26
 
27 27
 
28 28
 
29
-    private $_status;
30
-
31
-
32
-
33
-    /**
34
-     * An array of transaction details for the related transaction to the registration being processed.
35
-     * This is set via the _set_related_details method.
36
-     *
37
-     * @var array
38
-     */
39
-    protected $_transaction_details = array();
40
-
41
-
42
-
43
-    /**
44
-     * An array of event details for the related event to the registration being processed.
45
-     * This is set via the _set_related_details method.
46
-     *
47
-     * @var array
48
-     */
49
-    protected $_event_details = array();
50
-
51
-
52
-
53
-    /**
54
-     * @param \Registrations_Admin_Page $admin_page
55
-     */
56
-    public function __construct(Registrations_Admin_Page $admin_page)
57
-    {
58
-        if ( ! empty($_GET['event_id'])) {
59
-            $extra_query_args = array();
60
-            foreach ($admin_page->get_views() as $key => $view_details) {
61
-                $extra_query_args[$view_details['slug']] = array('event_id' => $_GET['event_id']);
62
-            }
63
-            $this->_views = $admin_page->get_list_table_view_RLs($extra_query_args);
64
-        }
65
-        parent::__construct($admin_page);
66
-        $this->_status = $this->_admin_page->get_registration_status_array();
67
-    }
68
-
69
-
70
-
71
-    /**
72
-     *    _setup_data
73
-     *
74
-     * @access protected
75
-     * @return void
76
-     */
77
-    protected function _setup_data()
78
-    {
79
-        $this->_data = $this->_admin_page->get_registrations($this->_per_page);
80
-        $this->_all_data_count = $this->_admin_page->get_registrations($this->_per_page, true, false, false);
81
-    }
82
-
83
-
84
-
85
-    /**
86
-     *    _set_properties
87
-     *
88
-     * @access protected
89
-     * @return void
90
-     */
91
-    protected function _set_properties()
92
-    {
93
-        $this->_wp_list_args = array(
94
-            'singular' => __('registration', 'event_espresso'),
95
-            'plural'   => __('registrations', 'event_espresso'),
96
-            'ajax'     => true,
97
-            'screen'   => $this->_admin_page->get_current_screen()->id,
98
-        );
99
-        $ID_column_name = __('ID', 'event_espresso');
100
-        $ID_column_name .= ' : <span class="show-on-mobile-view-only" style="float:none">';
101
-        $ID_column_name .= __('Registrant Name', 'event_espresso');
102
-        $ID_column_name .= '</span> ';
103
-        if (isset($_GET['event_id'])) {
104
-            $this->_columns = array(
105
-                'cb'               => '<input type="checkbox" />', //Render a checkbox instead of text
106
-                '_REG_ID'          => $ID_column_name,
107
-                'ATT_fname'        => __('Name', 'event_espresso'),
108
-                'ATT_email'        => __('Email', 'event_espresso'),
109
-                '_REG_date'        => __('Reg Date', 'event_espresso'),
110
-                'PRC_amount'       => __('TKT Price', 'event_espresso'),
111
-                '_REG_final_price' => __('Final Price', 'event_espresso'),
112
-                'TXN_total'        => __('Total Txn', 'event_espresso'),
113
-                'TXN_paid'         => __('Paid', 'event_espresso'),
114
-                'actions'          => __('Actions', 'event_espresso'),
115
-            );
116
-            $this->_bottom_buttons = array(
117
-                'report' => array(
118
-                    'route'         => 'registrations_report',
119
-                    'extra_request' => array(
120
-                        'EVT_ID'     => isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null,
121
-                        'return_url' => urlencode("//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"),
122
-                    ),
123
-                ),
124
-            );
125
-        } else {
126
-            $this->_columns = array(
127
-                'cb'               => '<input type="checkbox" />', //Render a checkbox instead of text
128
-                '_REG_ID'          => $ID_column_name,
129
-                'ATT_fname'        => __('Name', 'event_espresso'),
130
-                '_REG_date'        => __('TXN Date', 'event_espresso'),
131
-                'event_name'       => __('Event', 'event_espresso'),
132
-                'DTT_EVT_start'    => __('Event Date', 'event_espresso'),
133
-                '_REG_final_price' => __('Price', 'event_espresso'),
134
-                '_REG_paid'        => __('Paid', 'event_espresso'),
135
-                'actions'          => __('Actions', 'event_espresso'),
136
-            );
137
-            $this->_bottom_buttons = array(
138
-                'report_all' => array(
139
-                    'route'         => 'registrations_report',
140
-                    'extra_request' => array(
141
-                        'return_url' => urlencode("//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"),
142
-                    ),
143
-                ),
144
-            );
145
-        }
146
-        $this->_primary_column = '_REG_ID';
147
-        $this->_sortable_columns = array(
148
-            '_REG_date'     => array('_REG_date' => true),   //true means its already sorted
149
-            'ATT_fname'     => array('ATT_fname' => false),
150
-            'event_name'    => array('event_name' => false),
151
-            'DTT_EVT_start' => array('DTT_EVT_start' => false),
152
-            '_REG_ID'       => array('_REG_ID' => false),
153
-        );
154
-        $this->_hidden_columns = array();
155
-    }
156
-
157
-
158
-
159
-    /**
160
-     * This simply sets up the row class for the table rows.
161
-     * Allows for easier overriding of child methods for setting up sorting.
162
-     *
163
-     * @param  EE_Registration $item the current item
164
-     * @return string
165
-     */
166
-    protected function _get_row_class($item)
167
-    {
168
-        $class = parent::_get_row_class($item);
169
-        //add status class
170
-        $class .= ' ee-status-strip reg-status-' . $item->status_ID();
171
-        if ($this->_has_checkbox_column) {
172
-            $class .= ' has-checkbox-column';
173
-        }
174
-        return $class;
175
-    }
176
-
177
-
178
-
179
-    /**
180
-     * Set the $_transaction_details property if not set yet.
181
-     *
182
-     * @param EE_Registration $registration
183
-     * @throws \EE_Error
184
-     */
185
-    protected function _set_related_details(EE_Registration $registration)
186
-    {
187
-        $transaction = $registration->get_first_related('Transaction');
188
-        $status = $transaction instanceof EE_Transaction ? $transaction->status_ID()
189
-            : EEM_Transaction::failed_status_code;
190
-        $this->_transaction_details = array(
191
-            'transaction' => $transaction,
192
-            'status'      => $status,
193
-            'id'          => $transaction instanceof EE_Transaction ? $transaction->ID() : 0,
194
-            'title_attr'  => sprintf(__('View Transaction Details (%s)', 'event_espresso'),
195
-                EEH_Template::pretty_status($status, false, 'sentence')),
196
-        );
197
-        try {
198
-            $event = $registration->event();
199
-        } catch (\EventEspresso\core\exceptions\EntityNotFoundException $e) {
200
-            $event = null;
201
-        }
202
-        $status = $event instanceof EE_Event ? $event->get_active_status() : EE_Datetime::inactive;
203
-        $this->_event_details = array(
204
-            'event'      => $event,
205
-            'status'     => $status,
206
-            'id'         => $event instanceof EE_Event ? $event->ID() : 0,
207
-            'title_attr' => sprintf(__('Edit Event (%s)', 'event_espresso'),
208
-                EEH_Template::pretty_status($status, false, 'sentence')),
209
-        );
210
-    }
211
-
212
-
213
-
214
-    /**
215
-     *    _get_table_filters
216
-     *
217
-     * @access protected
218
-     * @return array
219
-     */
220
-    protected function _get_table_filters()
221
-    {
222
-        $filters = array();
223
-        //todo we're currently using old functions here. We need to move things into the Events_Admin_Page() class as methods.
224
-        $cur_date = isset($this->_req_data['month_range']) ? $this->_req_data['month_range'] : '';
225
-        $cur_category = isset($this->_req_data['EVT_CAT']) ? $this->_req_data['EVT_CAT'] : -1;
226
-        $reg_status = isset($this->_req_data['_reg_status']) ? $this->_req_data['_reg_status'] : '';
227
-        $filters[] = EEH_Form_Fields::generate_registration_months_dropdown($cur_date, $reg_status, $cur_category);
228
-        $filters[] = EEH_Form_Fields::generate_event_category_dropdown($cur_category);
229
-        $status = array();
230
-        $status[] = array('id' => 0, 'text' => __('Select Status', 'event_espresso'));
231
-        foreach ($this->_status as $key => $value) {
232
-            $status[] = array('id' => $key, 'text' => $value);
233
-        }
234
-        if ($this->_view !== 'incomplete') {
235
-            $filters[] = EEH_Form_Fields::select_input('_reg_status', $status,
236
-                isset($this->_req_data['_reg_status']) ? strtoupper(sanitize_key($this->_req_data['_reg_status']))
237
-                    : '');
238
-        }
239
-        if (isset($this->_req_data['event_id'])) {
240
-            $filters[] = EEH_Form_Fields::hidden_input('event_id', $this->_req_data['event_id'], 'reg_event_id');
241
-        }
242
-        return $filters;
243
-    }
244
-
245
-
246
-
247
-    /**
248
-     *    _add_view_counts
249
-     *
250
-     * @access protected
251
-     * @return void
252
-     * @throws \EE_Error
253
-     */
254
-    protected function _add_view_counts()
255
-    {
256
-        $this->_views['all']['count'] = $this->_total_registrations();
257
-        $this->_views['month']['count'] = $this->_total_registrations_this_month();
258
-        $this->_views['today']['count'] = $this->_total_registrations_today();
259
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registrations',
260
-            'espresso_registrations_trash_registrations')
261
-        ) {
262
-            $this->_views['incomplete']['count'] = $this->_total_registrations('incomplete');
263
-            $this->_views['trash']['count'] = $this->_total_registrations('trash');
264
-        }
265
-    }
266
-
267
-
268
-
269
-    /**
270
-     * _total_registrations
271
-     *
272
-     * @access protected
273
-     * @param string $view
274
-     * @return int
275
-     * @throws \EE_Error
276
-     */
277
-    protected function _total_registrations($view = '')
278
-    {
279
-        $_where = array();
280
-        $EVT_ID = isset($this->_req_data['event_id']) ? absint($this->_req_data['event_id']) : false;
281
-        if ($EVT_ID) {
282
-            $_where['EVT_ID'] = $EVT_ID;
283
-        }
284
-        switch ($view) {
285
-            case 'trash' :
286
-                return EEM_Registration::instance()->count_deleted(array($_where));
287
-                break;
288
-            case 'incomplete' :
289
-                $_where['STS_ID'] = EEM_Registration::status_id_incomplete;
290
-                break;
291
-            default :
292
-                $_where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
293
-        }
294
-        return EEM_Registration::instance()->count(array($_where));
295
-    }
296
-
297
-
298
-
299
-    /**
300
-     * _total_registrations_this_month
301
-     *
302
-     * @access protected
303
-     * @return int
304
-     * @throws \EE_Error
305
-     */
306
-    protected function _total_registrations_this_month()
307
-    {
308
-        $EVT_ID = isset($this->_req_data['event_id']) ? absint($this->_req_data['event_id']) : false;
309
-        $_where = $EVT_ID ? array('EVT_ID' => $EVT_ID) : array();
310
-        $this_year_r = date('Y', current_time('timestamp'));
311
-        $time_start = ' 00:00:00';
312
-        $time_end = ' 23:59:59';
313
-        $this_month_r = date('m', current_time('timestamp'));
314
-        $days_this_month = date('t', current_time('timestamp'));
315
-        //setup date query.
316
-        $beginning_string = EEM_Registration::instance()
317
-                                            ->convert_datetime_for_query('REG_date',
318
-                                                $this_year_r . '-' . $this_month_r . '-01' . ' ' . $time_start,
319
-                                                'Y-m-d H:i:s');
320
-        $end_string = EEM_Registration::instance()
321
-                                      ->convert_datetime_for_query('REG_date',
322
-                                          $this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' ' . $time_end,
323
-                                          'Y-m-d H:i:s');
324
-        $_where['REG_date'] = array(
325
-            'BETWEEN',
326
-            array(
327
-                $beginning_string,
328
-                $end_string,
329
-            ),
330
-        );
331
-        $_where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
332
-        return EEM_Registration::instance()->count(array($_where));
333
-    }
334
-
335
-
336
-
337
-    /**
338
-     * _total_registrations_today
339
-     *
340
-     * @access protected
341
-     * @return int
342
-     * @throws \EE_Error
343
-     */
344
-    protected function _total_registrations_today()
345
-    {
346
-        $EVT_ID = isset($this->_req_data['event_id']) ? absint($this->_req_data['event_id']) : false;
347
-        $_where = $EVT_ID ? array('EVT_ID' => $EVT_ID) : array();
348
-        $current_date = date('Y-m-d', current_time('timestamp'));
349
-        $time_start = ' 00:00:00';
350
-        $time_end = ' 23:59:59';
351
-        $_where['REG_date'] = array(
352
-            'BETWEEN',
353
-            array(
354
-                EEM_Registration::instance()
355
-                                ->convert_datetime_for_query('REG_date', $current_date . $time_start, 'Y-m-d H:i:s'),
356
-                EEM_Registration::instance()
357
-                                ->convert_datetime_for_query('REG_date', $current_date . $time_end, 'Y-m-d H:i:s'),
358
-            ),
359
-        );
360
-        $_where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
361
-        return EEM_Registration::instance()->count(array($_where));
362
-    }
363
-
364
-
365
-
366
-    /**
367
-     * column_cb
368
-     *
369
-     * @access public
370
-     * @param \EE_Registration $item
371
-     * @return string
372
-     * @throws \EE_Error
373
-     */
374
-    public function column_cb($item)
375
-    {
376
-        /** checkbox/lock **/
377
-        $transaction = $item->get_first_related('Transaction');
378
-        $payment_count = $transaction instanceof EE_Transaction ? $transaction->count_related('Payment') : 0;
379
-        return $payment_count > 0 ? sprintf('<input type="checkbox" name="_REG_ID[]" value="%1$s" />', $item->ID())
380
-                                    . '<span class="ee-lock-icon"></span>'
381
-            : sprintf('<input type="checkbox" name="_REG_ID[]" value="%1$s" />', $item->ID());
382
-    }
383
-
384
-
385
-
386
-    /**
387
-     * column__REG_ID
388
-     *
389
-     * @access public
390
-     * @param \EE_Registration $item
391
-     * @return string
392
-     * @throws \EE_Error
393
-     */
394
-    public function column__REG_ID(EE_Registration $item)
395
-    {
396
-        $attendee = $item->attendee();
397
-        $content = $item->ID();
398
-        $content .= '<div class="show-on-mobile-view-only">';
399
-        $content .= '<br>';
400
-        $content .= $attendee instanceof EE_Attendee ? $attendee->full_name() : '';
401
-        $content .= '&nbsp;' . sprintf(__('(%1$s / %2$s)', 'event_espresso'), $item->count(), $item->group_size());
402
-        $content .= '<br>' . sprintf(__('Reg Code: %s', 'event_espresso'), $item->get('REG_code'));
403
-        $content .= '</div>';
404
-        return $content;
405
-    }
406
-
407
-
408
-
409
-    /**
410
-     * column__REG_date
411
-     *
412
-     * @access public
413
-     * @param \EE_Registration $item
414
-     * @return string
415
-     * @throws \EE_Error
416
-     */
417
-    public function column__REG_date(EE_Registration $item)
418
-    {
419
-        $this->_set_related_details($item);
420
-        //Build row actions
421
-        $view_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
422
-            'action' => 'view_transaction',
423
-            'TXN_ID' => $this->_transaction_details['id'],
424
-        ), TXN_ADMIN_URL);
425
-        $view_link = EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
426
-            'espresso_transactions_view_transaction') ? '<a class="ee-status-color-'
427
-                                                        . $this->_transaction_details['status']
428
-                                                        . '" href="'
429
-                                                        . $view_lnk_url
430
-                                                        . '" title="'
431
-                                                        . esc_attr($this->_transaction_details['title_attr'])
432
-                                                        . '">'
433
-                                                        . $item->get_i18n_datetime('REG_date')
434
-                                                        . '</a>' : $item->get_i18n_datetime('REG_date');
435
-        $view_link .= '<br><span class="ee-status-text-small">'
436
-                      . EEH_Template::pretty_status($this->_transaction_details['status'], false, 'sentence')
437
-                      . '</span>';
438
-        return $view_link;
439
-    }
440
-
441
-
442
-
443
-    /**
444
-     * column_event_name
445
-     *
446
-     * @access public
447
-     * @param \EE_Registration $item
448
-     * @return string
449
-     * @throws \EE_Error
450
-     */
451
-    public function column_event_name(EE_Registration $item)
452
-    {
453
-        $this->_set_related_details($item);
454
-        // page=espresso_events&action=edit_event&EVT_ID=2&edit_event_nonce=cf3a7e5b62
455
-        $EVT_ID = $item->event_ID();
456
-        $event_name = $item->event_name();
457
-        $event_name = $event_name ? $event_name : __("No Associated Event", 'event_espresso');
458
-        $event_name = wp_trim_words($event_name, 30, '...');
459
-        if ($EVT_ID) {
460
-            $edit_event_url = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'edit', 'post' => $EVT_ID),
461
-                EVENTS_ADMIN_URL);
462
-            $edit_event = EE_Registry::instance()->CAP->current_user_can('ee_edit_event', 'edit_event', $EVT_ID)
463
-                ? '<a class="ee-status-color-'
464
-                  . $this->_event_details['status']
465
-                  . '" href="'
466
-                  . $edit_event_url
467
-                  . '" title="'
468
-                  . esc_attr($this->_event_details['title_attr'])
469
-                  . '">'
470
-                  . $event_name
471
-                  . '</a>' : $event_name;
472
-            $edit_event_url = EE_Admin_Page::add_query_args_and_nonce(array('event_id' => $EVT_ID), REG_ADMIN_URL);
473
-            $actions['event_filter'] = '<a href="' . $edit_event_url . '" title="';
474
-            $actions['event_filter'] .= sprintf(esc_attr__('Filter this list to only show registrations for %s',
475
-                'event_espresso'), $event_name);
476
-            $actions['event_filter'] .= '">' . __('View Registrations', 'event_espresso') . '</a>';
477
-        } else {
478
-            $edit_event = $event_name;
479
-            $actions['event_filter'] = '';
480
-        }
481
-        return sprintf('%1$s %2$s', $edit_event, $this->row_actions($actions));
482
-    }
483
-
484
-
485
-
486
-    /**
487
-     * column_DTT_EVT_start
488
-     *
489
-     * @access public
490
-     * @param \EE_Registration $item
491
-     * @return string
492
-     * @throws \EE_Error
493
-     */
494
-    public function column_DTT_EVT_start(EE_Registration $item)
495
-    {
496
-        $datetime_strings = array();
497
-        $ticket = $item->ticket(true);
498
-        if ($ticket instanceof EE_Ticket) {
499
-            $remove_defaults = array('default_where_conditions' => 'none');
500
-            $datetimes = $ticket->datetimes($remove_defaults);
501
-            foreach ($datetimes as $datetime) {
502
-                $datetime_strings[] = $datetime->get_i18n_datetime('DTT_EVT_start');
503
-            }
504
-            return implode("<br />", $datetime_strings);
505
-        } else {
506
-            return __('There is no ticket on this registration', 'event_espresso');
507
-        }
508
-    }
509
-
510
-
511
-
512
-    /**
513
-     * column_ATT_fname
514
-     *
515
-     * @access public
516
-     * @param \EE_Registration $item
517
-     * @return string
518
-     * @throws \EE_Error
519
-     */
520
-    public function column_ATT_fname(EE_Registration $item)
521
-    {
522
-        $attendee = $item->attendee();
523
-        $edit_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
524
-            'action'  => 'view_registration',
525
-            '_REG_ID' => $item->ID(),
526
-        ), REG_ADMIN_URL);
527
-        $attendee_name = $attendee instanceof EE_Attendee ? $attendee->full_name() : '';
528
-        $link = EE_Registry::instance()->CAP->current_user_can('ee_read_registration',
529
-            'espresso_registrations_view_registration', $item->ID()) ? '<a href="'
530
-                                                                       . $edit_lnk_url
531
-                                                                       . '" title="'
532
-                                                                       . esc_attr__('View Registration Details',
533
-                'event_espresso')
534
-                                                                       . '">'
535
-                                                                       . $attendee_name
536
-                                                                       . '</a>' : $attendee_name;
537
-        $link .= $item->count() === 1
538
-            ? '&nbsp;<sup><div class="dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8"></div></sup>' : '';
539
-        $t = $item->get_first_related('Transaction');
540
-        $payment_count = $t instanceof EE_Transaction ? $t->count_related('Payment') : 0;
541
-        //append group count to name
542
-        $link .= '&nbsp;' . sprintf(__('(%1$s / %2$s)', 'event_espresso'), $item->count(), $item->group_size());
543
-        //append reg_code
544
-        $link .= '<br>' . sprintf(__('Reg Code: %s', 'event_espresso'), $item->get('REG_code'));
545
-        //reg status text for accessibility
546
-        $link .= '<br><span class="ee-status-text-small">' . EEH_Template::pretty_status($item->status_ID(), false,
547
-                'sentence') . '</span>';
548
-        //trash/restore/delete actions
549
-        $actions = array();
550
-        if ($this->_view !== 'trash'
551
-            && $payment_count === 0
552
-            && EE_Registry::instance()->CAP->current_user_can('ee_delete_registration',
553
-                'espresso_registrations_trash_registrations', $item->ID())
554
-        ) {
555
-            $trash_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
556
-                'action'  => 'trash_registrations',
557
-                '_REG_ID' => $item->ID(),
558
-            ), REG_ADMIN_URL);
559
-            $actions['trash'] = '<a href="' . $trash_lnk_url . '" title="' . esc_attr__('Trash Registration',
560
-                    'event_espresso') . '">' . __('Trash', 'event_espresso') . '</a>';
561
-        } elseif ($this->_view === 'trash') {
562
-            // restore registration link
563
-            if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registration',
564
-                'espresso_registrations_restore_registrations', $item->ID())
565
-            ) {
566
-                $restore_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
567
-                    'action'  => 'restore_registrations',
568
-                    '_REG_ID' => $item->ID(),
569
-                ), REG_ADMIN_URL);
570
-                $actions['restore'] = '<a href="' . $restore_lnk_url . '" title="' . esc_attr__('Restore Registration',
571
-                        'event_espresso') . '">' . __('Restore', 'event_espresso') . '</a>';
572
-            }
573
-            if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registration',
574
-                'espresso_registrations_ee_delete_registrations', $item->ID())
575
-            ) {
576
-                $delete_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
577
-                    'action'  => 'delete_registrations',
578
-                    '_REG_ID' => $item->ID(),
579
-                ), REG_ADMIN_URL);
580
-                $actions['delete'] = '<a href="'
581
-                                     . $delete_lnk_url
582
-                                     . '" title="'
583
-                                     . esc_attr__('Delete Registration Permanently', 'event_espresso')
584
-                                     . '">'
585
-                                     . __('Delete', 'event_espresso')
586
-                                     . '</a>';
587
-            }
588
-        }
589
-        return sprintf('%1$s %2$s', $link, $this->row_actions($actions));
590
-    }
591
-
592
-
593
-
594
-    /**
595
-     * column_ATT_email
596
-     *
597
-     * @access public
598
-     * @param \EE_Registration $item
599
-     * @return string
600
-     * @throws \EE_Error
601
-     */
602
-    public function column_ATT_email(EE_Registration $item)
603
-    {
604
-        $attendee = $item->get_first_related('Attendee');
605
-        return ! $attendee instanceof EE_Attendee ? __('No attached contact record.', 'event_espresso')
606
-            : $attendee->email();
607
-    }
608
-
609
-
610
-
611
-    /**
612
-     * column__REG_count
613
-     *
614
-     * @access public
615
-     * @param \EE_Registration $item
616
-     * @return string
617
-     */
618
-    public function column__REG_count(EE_Registration $item)
619
-    {
620
-        return sprintf(__('%1$s / %2$s', 'event_espresso'), $item->count(), $item->group_size());
621
-    }
622
-
623
-
624
-
625
-    /**
626
-     * column_PRC_amount
627
-     *
628
-     * @access public
629
-     * @param \EE_Registration $item
630
-     * @return string
631
-     */
632
-    public function column_PRC_amount(EE_Registration $item)
633
-    {
634
-        $ticket = $item->ticket();
635
-        $content = isset($_GET['event_id']) && $ticket instanceof EE_Ticket ? '<span class="TKT_name">'
636
-                                                                              . $ticket->name()
637
-                                                                              . '</span><br />' : '';
638
-        if ($item->final_price() > 0) {
639
-            $content .= '<span class="reg-pad-rght">' . $item->pretty_final_price() . '</span>';
640
-        } else {
641
-            // free event
642
-            $content .= '<span class="reg-overview-free-event-spn reg-pad-rght">'
643
-                        . __('free', 'event_espresso')
644
-                        . '</span>';
645
-        }
646
-        return $content;
647
-    }
648
-
649
-
650
-
651
-    /**
652
-     * column__REG_final_price
653
-     *
654
-     * @access public
655
-     * @param \EE_Registration $item
656
-     * @return string
657
-     */
658
-    public function column__REG_final_price(EE_Registration $item)
659
-    {
660
-        $ticket = $item->ticket();
661
-        $content = isset($_GET['event_id']) || ! $ticket instanceof EE_Ticket
662
-            ? ''
663
-            : '<span class="TKT_name">'
664
-              . $ticket->name()
665
-              . '</span><br />';
666
-        $content .= '<span class="reg-pad-rght">' . $item->pretty_final_price() . '</span>';
667
-        return $content;
668
-    }
669
-
670
-
671
-
672
-    /**
673
-     * column__REG_paid
674
-     *
675
-     * @access public
676
-     * @param \EE_Registration $item
677
-     * @return string
678
-     */
679
-    public function column__REG_paid(EE_Registration $item)
680
-    {
681
-        $payment_method = $item->payment_method();
682
-        $payment_method_name = $payment_method instanceof EE_Payment_Method ? $payment_method->admin_name()
683
-            : __('Unknown', 'event_espresso');
684
-        $content = '<span class="reg-pad-rght">' . $item->pretty_paid() . '</span>';
685
-        if ($item->paid() > 0) {
686
-            $content .= '<br><span class="ee-status-text-small">' . sprintf(__('...via %s', 'event_espresso'),
687
-                    $payment_method_name) . '</span>';
688
-        }
689
-        return $content;
690
-    }
691
-
692
-
693
-
694
-    /**
695
-     * column_TXN_total
696
-     *
697
-     * @access public
698
-     * @param \EE_Registration $item
699
-     * @return string
700
-     * @throws \EE_Error
701
-     */
702
-    public function column_TXN_total(EE_Registration $item)
703
-    {
704
-        if ($item->transaction()) {
705
-            $view_txn_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
706
-                'action' => 'view_transaction',
707
-                'TXN_ID' => $item->transaction_ID(),
708
-            ), TXN_ADMIN_URL);
709
-            return EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
710
-                'espresso_transactions_view_transaction', $item->transaction_ID())
711
-                ? '<span class="reg-pad-rght"><a class="status-'
712
-                  . $item->transaction()->status_ID()
713
-                  . '" href="'
714
-                  . $view_txn_lnk_url
715
-                  . '"  title="'
716
-                  . esc_attr__('View Transaction', 'event_espresso')
717
-                  . '">'
718
-                  . $item->transaction()->pretty_total()
719
-                  . '</a></span>' : '<span class="reg-pad-rght">' . $item->transaction()->pretty_total() . '</span>';
720
-        } else {
721
-            return __("None", "event_espresso");
722
-        }
723
-    }
724
-
725
-
726
-
727
-    /**
728
-     * column_TXN_paid
729
-     *
730
-     * @access public
731
-     * @param \EE_Registration $item
732
-     * @return string
733
-     * @throws \EE_Error
734
-     */
735
-    public function column_TXN_paid(EE_Registration $item)
736
-    {
737
-        if ($item->count() === 1) {
738
-            $transaction = $item->transaction() ? $item->transaction() : EE_Transaction::new_instance();
739
-            if ($transaction->paid() >= $transaction->total()) {
740
-                return '<span class="reg-pad-rght"><div class="dashicons dashicons-yes green-icon"></div></span>';
741
-            } else {
742
-                $view_txn_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
743
-                    'action' => 'view_transaction',
744
-                    'TXN_ID' => $item->transaction_ID(),
745
-                ), TXN_ADMIN_URL);
746
-                return EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
747
-                    'espresso_transactions_view_transaction', $item->transaction_ID())
748
-                    ? '<span class="reg-pad-rght"><a class="status-'
749
-                      . $transaction->status_ID()
750
-                      . '" href="'
751
-                      . $view_txn_lnk_url
752
-                      . '"  title="'
753
-                      . esc_attr__('View Transaction', 'event_espresso')
754
-                      . '">'
755
-                      . $item->transaction()->pretty_paid()
756
-                      . '</a><span>' : '<span class="reg-pad-rght">' . $item->transaction()->pretty_paid() . '</span>';
757
-            }
758
-        }
759
-        return '&nbsp;';
760
-    }
761
-
762
-
763
-
764
-    /**
765
-     * column_actions
766
-     *
767
-     * @access public
768
-     * @param \EE_Registration $item
769
-     * @return string
770
-     * @throws \EE_Error
771
-     */
772
-    public function column_actions(EE_Registration $item)
773
-    {
774
-        $actions = array();
775
-        $attendee = $item->attendee();
776
-        $this->_set_related_details($item);
777
-        //Build row actions
778
-        $view_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
779
-            'action'  => 'view_registration',
780
-            '_REG_ID' => $item->ID(),
781
-        ), REG_ADMIN_URL);
782
-        $edit_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
783
-            'action' => 'edit_attendee',
784
-            'post'   => $item->attendee_ID(),
785
-        ), REG_ADMIN_URL);
786
-        // page=attendees&event_admin_reports=resend_email&registration_id=43653465634&event_id=2&form_action=resend_email
787
-        //$resend_reg_lnk_url_params = array( 'action'=>'resend_registration', '_REG_ID'=>$item->REG_ID );
788
-        $resend_reg_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
789
-            'action'  => 'resend_registration',
790
-            '_REG_ID' => $item->ID(),
791
-        ), REG_ADMIN_URL, true);
792
-        //Build row actions
793
-        $actions['view_lnk'] = EE_Registry::instance()->CAP->current_user_can('ee_read_registration',
794
-            'espresso_registrations_view_registration', $item->ID()) ? '
29
+	private $_status;
30
+
31
+
32
+
33
+	/**
34
+	 * An array of transaction details for the related transaction to the registration being processed.
35
+	 * This is set via the _set_related_details method.
36
+	 *
37
+	 * @var array
38
+	 */
39
+	protected $_transaction_details = array();
40
+
41
+
42
+
43
+	/**
44
+	 * An array of event details for the related event to the registration being processed.
45
+	 * This is set via the _set_related_details method.
46
+	 *
47
+	 * @var array
48
+	 */
49
+	protected $_event_details = array();
50
+
51
+
52
+
53
+	/**
54
+	 * @param \Registrations_Admin_Page $admin_page
55
+	 */
56
+	public function __construct(Registrations_Admin_Page $admin_page)
57
+	{
58
+		if ( ! empty($_GET['event_id'])) {
59
+			$extra_query_args = array();
60
+			foreach ($admin_page->get_views() as $key => $view_details) {
61
+				$extra_query_args[$view_details['slug']] = array('event_id' => $_GET['event_id']);
62
+			}
63
+			$this->_views = $admin_page->get_list_table_view_RLs($extra_query_args);
64
+		}
65
+		parent::__construct($admin_page);
66
+		$this->_status = $this->_admin_page->get_registration_status_array();
67
+	}
68
+
69
+
70
+
71
+	/**
72
+	 *    _setup_data
73
+	 *
74
+	 * @access protected
75
+	 * @return void
76
+	 */
77
+	protected function _setup_data()
78
+	{
79
+		$this->_data = $this->_admin_page->get_registrations($this->_per_page);
80
+		$this->_all_data_count = $this->_admin_page->get_registrations($this->_per_page, true, false, false);
81
+	}
82
+
83
+
84
+
85
+	/**
86
+	 *    _set_properties
87
+	 *
88
+	 * @access protected
89
+	 * @return void
90
+	 */
91
+	protected function _set_properties()
92
+	{
93
+		$this->_wp_list_args = array(
94
+			'singular' => __('registration', 'event_espresso'),
95
+			'plural'   => __('registrations', 'event_espresso'),
96
+			'ajax'     => true,
97
+			'screen'   => $this->_admin_page->get_current_screen()->id,
98
+		);
99
+		$ID_column_name = __('ID', 'event_espresso');
100
+		$ID_column_name .= ' : <span class="show-on-mobile-view-only" style="float:none">';
101
+		$ID_column_name .= __('Registrant Name', 'event_espresso');
102
+		$ID_column_name .= '</span> ';
103
+		if (isset($_GET['event_id'])) {
104
+			$this->_columns = array(
105
+				'cb'               => '<input type="checkbox" />', //Render a checkbox instead of text
106
+				'_REG_ID'          => $ID_column_name,
107
+				'ATT_fname'        => __('Name', 'event_espresso'),
108
+				'ATT_email'        => __('Email', 'event_espresso'),
109
+				'_REG_date'        => __('Reg Date', 'event_espresso'),
110
+				'PRC_amount'       => __('TKT Price', 'event_espresso'),
111
+				'_REG_final_price' => __('Final Price', 'event_espresso'),
112
+				'TXN_total'        => __('Total Txn', 'event_espresso'),
113
+				'TXN_paid'         => __('Paid', 'event_espresso'),
114
+				'actions'          => __('Actions', 'event_espresso'),
115
+			);
116
+			$this->_bottom_buttons = array(
117
+				'report' => array(
118
+					'route'         => 'registrations_report',
119
+					'extra_request' => array(
120
+						'EVT_ID'     => isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null,
121
+						'return_url' => urlencode("//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"),
122
+					),
123
+				),
124
+			);
125
+		} else {
126
+			$this->_columns = array(
127
+				'cb'               => '<input type="checkbox" />', //Render a checkbox instead of text
128
+				'_REG_ID'          => $ID_column_name,
129
+				'ATT_fname'        => __('Name', 'event_espresso'),
130
+				'_REG_date'        => __('TXN Date', 'event_espresso'),
131
+				'event_name'       => __('Event', 'event_espresso'),
132
+				'DTT_EVT_start'    => __('Event Date', 'event_espresso'),
133
+				'_REG_final_price' => __('Price', 'event_espresso'),
134
+				'_REG_paid'        => __('Paid', 'event_espresso'),
135
+				'actions'          => __('Actions', 'event_espresso'),
136
+			);
137
+			$this->_bottom_buttons = array(
138
+				'report_all' => array(
139
+					'route'         => 'registrations_report',
140
+					'extra_request' => array(
141
+						'return_url' => urlencode("//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"),
142
+					),
143
+				),
144
+			);
145
+		}
146
+		$this->_primary_column = '_REG_ID';
147
+		$this->_sortable_columns = array(
148
+			'_REG_date'     => array('_REG_date' => true),   //true means its already sorted
149
+			'ATT_fname'     => array('ATT_fname' => false),
150
+			'event_name'    => array('event_name' => false),
151
+			'DTT_EVT_start' => array('DTT_EVT_start' => false),
152
+			'_REG_ID'       => array('_REG_ID' => false),
153
+		);
154
+		$this->_hidden_columns = array();
155
+	}
156
+
157
+
158
+
159
+	/**
160
+	 * This simply sets up the row class for the table rows.
161
+	 * Allows for easier overriding of child methods for setting up sorting.
162
+	 *
163
+	 * @param  EE_Registration $item the current item
164
+	 * @return string
165
+	 */
166
+	protected function _get_row_class($item)
167
+	{
168
+		$class = parent::_get_row_class($item);
169
+		//add status class
170
+		$class .= ' ee-status-strip reg-status-' . $item->status_ID();
171
+		if ($this->_has_checkbox_column) {
172
+			$class .= ' has-checkbox-column';
173
+		}
174
+		return $class;
175
+	}
176
+
177
+
178
+
179
+	/**
180
+	 * Set the $_transaction_details property if not set yet.
181
+	 *
182
+	 * @param EE_Registration $registration
183
+	 * @throws \EE_Error
184
+	 */
185
+	protected function _set_related_details(EE_Registration $registration)
186
+	{
187
+		$transaction = $registration->get_first_related('Transaction');
188
+		$status = $transaction instanceof EE_Transaction ? $transaction->status_ID()
189
+			: EEM_Transaction::failed_status_code;
190
+		$this->_transaction_details = array(
191
+			'transaction' => $transaction,
192
+			'status'      => $status,
193
+			'id'          => $transaction instanceof EE_Transaction ? $transaction->ID() : 0,
194
+			'title_attr'  => sprintf(__('View Transaction Details (%s)', 'event_espresso'),
195
+				EEH_Template::pretty_status($status, false, 'sentence')),
196
+		);
197
+		try {
198
+			$event = $registration->event();
199
+		} catch (\EventEspresso\core\exceptions\EntityNotFoundException $e) {
200
+			$event = null;
201
+		}
202
+		$status = $event instanceof EE_Event ? $event->get_active_status() : EE_Datetime::inactive;
203
+		$this->_event_details = array(
204
+			'event'      => $event,
205
+			'status'     => $status,
206
+			'id'         => $event instanceof EE_Event ? $event->ID() : 0,
207
+			'title_attr' => sprintf(__('Edit Event (%s)', 'event_espresso'),
208
+				EEH_Template::pretty_status($status, false, 'sentence')),
209
+		);
210
+	}
211
+
212
+
213
+
214
+	/**
215
+	 *    _get_table_filters
216
+	 *
217
+	 * @access protected
218
+	 * @return array
219
+	 */
220
+	protected function _get_table_filters()
221
+	{
222
+		$filters = array();
223
+		//todo we're currently using old functions here. We need to move things into the Events_Admin_Page() class as methods.
224
+		$cur_date = isset($this->_req_data['month_range']) ? $this->_req_data['month_range'] : '';
225
+		$cur_category = isset($this->_req_data['EVT_CAT']) ? $this->_req_data['EVT_CAT'] : -1;
226
+		$reg_status = isset($this->_req_data['_reg_status']) ? $this->_req_data['_reg_status'] : '';
227
+		$filters[] = EEH_Form_Fields::generate_registration_months_dropdown($cur_date, $reg_status, $cur_category);
228
+		$filters[] = EEH_Form_Fields::generate_event_category_dropdown($cur_category);
229
+		$status = array();
230
+		$status[] = array('id' => 0, 'text' => __('Select Status', 'event_espresso'));
231
+		foreach ($this->_status as $key => $value) {
232
+			$status[] = array('id' => $key, 'text' => $value);
233
+		}
234
+		if ($this->_view !== 'incomplete') {
235
+			$filters[] = EEH_Form_Fields::select_input('_reg_status', $status,
236
+				isset($this->_req_data['_reg_status']) ? strtoupper(sanitize_key($this->_req_data['_reg_status']))
237
+					: '');
238
+		}
239
+		if (isset($this->_req_data['event_id'])) {
240
+			$filters[] = EEH_Form_Fields::hidden_input('event_id', $this->_req_data['event_id'], 'reg_event_id');
241
+		}
242
+		return $filters;
243
+	}
244
+
245
+
246
+
247
+	/**
248
+	 *    _add_view_counts
249
+	 *
250
+	 * @access protected
251
+	 * @return void
252
+	 * @throws \EE_Error
253
+	 */
254
+	protected function _add_view_counts()
255
+	{
256
+		$this->_views['all']['count'] = $this->_total_registrations();
257
+		$this->_views['month']['count'] = $this->_total_registrations_this_month();
258
+		$this->_views['today']['count'] = $this->_total_registrations_today();
259
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registrations',
260
+			'espresso_registrations_trash_registrations')
261
+		) {
262
+			$this->_views['incomplete']['count'] = $this->_total_registrations('incomplete');
263
+			$this->_views['trash']['count'] = $this->_total_registrations('trash');
264
+		}
265
+	}
266
+
267
+
268
+
269
+	/**
270
+	 * _total_registrations
271
+	 *
272
+	 * @access protected
273
+	 * @param string $view
274
+	 * @return int
275
+	 * @throws \EE_Error
276
+	 */
277
+	protected function _total_registrations($view = '')
278
+	{
279
+		$_where = array();
280
+		$EVT_ID = isset($this->_req_data['event_id']) ? absint($this->_req_data['event_id']) : false;
281
+		if ($EVT_ID) {
282
+			$_where['EVT_ID'] = $EVT_ID;
283
+		}
284
+		switch ($view) {
285
+			case 'trash' :
286
+				return EEM_Registration::instance()->count_deleted(array($_where));
287
+				break;
288
+			case 'incomplete' :
289
+				$_where['STS_ID'] = EEM_Registration::status_id_incomplete;
290
+				break;
291
+			default :
292
+				$_where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
293
+		}
294
+		return EEM_Registration::instance()->count(array($_where));
295
+	}
296
+
297
+
298
+
299
+	/**
300
+	 * _total_registrations_this_month
301
+	 *
302
+	 * @access protected
303
+	 * @return int
304
+	 * @throws \EE_Error
305
+	 */
306
+	protected function _total_registrations_this_month()
307
+	{
308
+		$EVT_ID = isset($this->_req_data['event_id']) ? absint($this->_req_data['event_id']) : false;
309
+		$_where = $EVT_ID ? array('EVT_ID' => $EVT_ID) : array();
310
+		$this_year_r = date('Y', current_time('timestamp'));
311
+		$time_start = ' 00:00:00';
312
+		$time_end = ' 23:59:59';
313
+		$this_month_r = date('m', current_time('timestamp'));
314
+		$days_this_month = date('t', current_time('timestamp'));
315
+		//setup date query.
316
+		$beginning_string = EEM_Registration::instance()
317
+											->convert_datetime_for_query('REG_date',
318
+												$this_year_r . '-' . $this_month_r . '-01' . ' ' . $time_start,
319
+												'Y-m-d H:i:s');
320
+		$end_string = EEM_Registration::instance()
321
+									  ->convert_datetime_for_query('REG_date',
322
+										  $this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' ' . $time_end,
323
+										  'Y-m-d H:i:s');
324
+		$_where['REG_date'] = array(
325
+			'BETWEEN',
326
+			array(
327
+				$beginning_string,
328
+				$end_string,
329
+			),
330
+		);
331
+		$_where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
332
+		return EEM_Registration::instance()->count(array($_where));
333
+	}
334
+
335
+
336
+
337
+	/**
338
+	 * _total_registrations_today
339
+	 *
340
+	 * @access protected
341
+	 * @return int
342
+	 * @throws \EE_Error
343
+	 */
344
+	protected function _total_registrations_today()
345
+	{
346
+		$EVT_ID = isset($this->_req_data['event_id']) ? absint($this->_req_data['event_id']) : false;
347
+		$_where = $EVT_ID ? array('EVT_ID' => $EVT_ID) : array();
348
+		$current_date = date('Y-m-d', current_time('timestamp'));
349
+		$time_start = ' 00:00:00';
350
+		$time_end = ' 23:59:59';
351
+		$_where['REG_date'] = array(
352
+			'BETWEEN',
353
+			array(
354
+				EEM_Registration::instance()
355
+								->convert_datetime_for_query('REG_date', $current_date . $time_start, 'Y-m-d H:i:s'),
356
+				EEM_Registration::instance()
357
+								->convert_datetime_for_query('REG_date', $current_date . $time_end, 'Y-m-d H:i:s'),
358
+			),
359
+		);
360
+		$_where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
361
+		return EEM_Registration::instance()->count(array($_where));
362
+	}
363
+
364
+
365
+
366
+	/**
367
+	 * column_cb
368
+	 *
369
+	 * @access public
370
+	 * @param \EE_Registration $item
371
+	 * @return string
372
+	 * @throws \EE_Error
373
+	 */
374
+	public function column_cb($item)
375
+	{
376
+		/** checkbox/lock **/
377
+		$transaction = $item->get_first_related('Transaction');
378
+		$payment_count = $transaction instanceof EE_Transaction ? $transaction->count_related('Payment') : 0;
379
+		return $payment_count > 0 ? sprintf('<input type="checkbox" name="_REG_ID[]" value="%1$s" />', $item->ID())
380
+									. '<span class="ee-lock-icon"></span>'
381
+			: sprintf('<input type="checkbox" name="_REG_ID[]" value="%1$s" />', $item->ID());
382
+	}
383
+
384
+
385
+
386
+	/**
387
+	 * column__REG_ID
388
+	 *
389
+	 * @access public
390
+	 * @param \EE_Registration $item
391
+	 * @return string
392
+	 * @throws \EE_Error
393
+	 */
394
+	public function column__REG_ID(EE_Registration $item)
395
+	{
396
+		$attendee = $item->attendee();
397
+		$content = $item->ID();
398
+		$content .= '<div class="show-on-mobile-view-only">';
399
+		$content .= '<br>';
400
+		$content .= $attendee instanceof EE_Attendee ? $attendee->full_name() : '';
401
+		$content .= '&nbsp;' . sprintf(__('(%1$s / %2$s)', 'event_espresso'), $item->count(), $item->group_size());
402
+		$content .= '<br>' . sprintf(__('Reg Code: %s', 'event_espresso'), $item->get('REG_code'));
403
+		$content .= '</div>';
404
+		return $content;
405
+	}
406
+
407
+
408
+
409
+	/**
410
+	 * column__REG_date
411
+	 *
412
+	 * @access public
413
+	 * @param \EE_Registration $item
414
+	 * @return string
415
+	 * @throws \EE_Error
416
+	 */
417
+	public function column__REG_date(EE_Registration $item)
418
+	{
419
+		$this->_set_related_details($item);
420
+		//Build row actions
421
+		$view_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
422
+			'action' => 'view_transaction',
423
+			'TXN_ID' => $this->_transaction_details['id'],
424
+		), TXN_ADMIN_URL);
425
+		$view_link = EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
426
+			'espresso_transactions_view_transaction') ? '<a class="ee-status-color-'
427
+														. $this->_transaction_details['status']
428
+														. '" href="'
429
+														. $view_lnk_url
430
+														. '" title="'
431
+														. esc_attr($this->_transaction_details['title_attr'])
432
+														. '">'
433
+														. $item->get_i18n_datetime('REG_date')
434
+														. '</a>' : $item->get_i18n_datetime('REG_date');
435
+		$view_link .= '<br><span class="ee-status-text-small">'
436
+					  . EEH_Template::pretty_status($this->_transaction_details['status'], false, 'sentence')
437
+					  . '</span>';
438
+		return $view_link;
439
+	}
440
+
441
+
442
+
443
+	/**
444
+	 * column_event_name
445
+	 *
446
+	 * @access public
447
+	 * @param \EE_Registration $item
448
+	 * @return string
449
+	 * @throws \EE_Error
450
+	 */
451
+	public function column_event_name(EE_Registration $item)
452
+	{
453
+		$this->_set_related_details($item);
454
+		// page=espresso_events&action=edit_event&EVT_ID=2&edit_event_nonce=cf3a7e5b62
455
+		$EVT_ID = $item->event_ID();
456
+		$event_name = $item->event_name();
457
+		$event_name = $event_name ? $event_name : __("No Associated Event", 'event_espresso');
458
+		$event_name = wp_trim_words($event_name, 30, '...');
459
+		if ($EVT_ID) {
460
+			$edit_event_url = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'edit', 'post' => $EVT_ID),
461
+				EVENTS_ADMIN_URL);
462
+			$edit_event = EE_Registry::instance()->CAP->current_user_can('ee_edit_event', 'edit_event', $EVT_ID)
463
+				? '<a class="ee-status-color-'
464
+				  . $this->_event_details['status']
465
+				  . '" href="'
466
+				  . $edit_event_url
467
+				  . '" title="'
468
+				  . esc_attr($this->_event_details['title_attr'])
469
+				  . '">'
470
+				  . $event_name
471
+				  . '</a>' : $event_name;
472
+			$edit_event_url = EE_Admin_Page::add_query_args_and_nonce(array('event_id' => $EVT_ID), REG_ADMIN_URL);
473
+			$actions['event_filter'] = '<a href="' . $edit_event_url . '" title="';
474
+			$actions['event_filter'] .= sprintf(esc_attr__('Filter this list to only show registrations for %s',
475
+				'event_espresso'), $event_name);
476
+			$actions['event_filter'] .= '">' . __('View Registrations', 'event_espresso') . '</a>';
477
+		} else {
478
+			$edit_event = $event_name;
479
+			$actions['event_filter'] = '';
480
+		}
481
+		return sprintf('%1$s %2$s', $edit_event, $this->row_actions($actions));
482
+	}
483
+
484
+
485
+
486
+	/**
487
+	 * column_DTT_EVT_start
488
+	 *
489
+	 * @access public
490
+	 * @param \EE_Registration $item
491
+	 * @return string
492
+	 * @throws \EE_Error
493
+	 */
494
+	public function column_DTT_EVT_start(EE_Registration $item)
495
+	{
496
+		$datetime_strings = array();
497
+		$ticket = $item->ticket(true);
498
+		if ($ticket instanceof EE_Ticket) {
499
+			$remove_defaults = array('default_where_conditions' => 'none');
500
+			$datetimes = $ticket->datetimes($remove_defaults);
501
+			foreach ($datetimes as $datetime) {
502
+				$datetime_strings[] = $datetime->get_i18n_datetime('DTT_EVT_start');
503
+			}
504
+			return implode("<br />", $datetime_strings);
505
+		} else {
506
+			return __('There is no ticket on this registration', 'event_espresso');
507
+		}
508
+	}
509
+
510
+
511
+
512
+	/**
513
+	 * column_ATT_fname
514
+	 *
515
+	 * @access public
516
+	 * @param \EE_Registration $item
517
+	 * @return string
518
+	 * @throws \EE_Error
519
+	 */
520
+	public function column_ATT_fname(EE_Registration $item)
521
+	{
522
+		$attendee = $item->attendee();
523
+		$edit_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
524
+			'action'  => 'view_registration',
525
+			'_REG_ID' => $item->ID(),
526
+		), REG_ADMIN_URL);
527
+		$attendee_name = $attendee instanceof EE_Attendee ? $attendee->full_name() : '';
528
+		$link = EE_Registry::instance()->CAP->current_user_can('ee_read_registration',
529
+			'espresso_registrations_view_registration', $item->ID()) ? '<a href="'
530
+																	   . $edit_lnk_url
531
+																	   . '" title="'
532
+																	   . esc_attr__('View Registration Details',
533
+				'event_espresso')
534
+																	   . '">'
535
+																	   . $attendee_name
536
+																	   . '</a>' : $attendee_name;
537
+		$link .= $item->count() === 1
538
+			? '&nbsp;<sup><div class="dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8"></div></sup>' : '';
539
+		$t = $item->get_first_related('Transaction');
540
+		$payment_count = $t instanceof EE_Transaction ? $t->count_related('Payment') : 0;
541
+		//append group count to name
542
+		$link .= '&nbsp;' . sprintf(__('(%1$s / %2$s)', 'event_espresso'), $item->count(), $item->group_size());
543
+		//append reg_code
544
+		$link .= '<br>' . sprintf(__('Reg Code: %s', 'event_espresso'), $item->get('REG_code'));
545
+		//reg status text for accessibility
546
+		$link .= '<br><span class="ee-status-text-small">' . EEH_Template::pretty_status($item->status_ID(), false,
547
+				'sentence') . '</span>';
548
+		//trash/restore/delete actions
549
+		$actions = array();
550
+		if ($this->_view !== 'trash'
551
+			&& $payment_count === 0
552
+			&& EE_Registry::instance()->CAP->current_user_can('ee_delete_registration',
553
+				'espresso_registrations_trash_registrations', $item->ID())
554
+		) {
555
+			$trash_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
556
+				'action'  => 'trash_registrations',
557
+				'_REG_ID' => $item->ID(),
558
+			), REG_ADMIN_URL);
559
+			$actions['trash'] = '<a href="' . $trash_lnk_url . '" title="' . esc_attr__('Trash Registration',
560
+					'event_espresso') . '">' . __('Trash', 'event_espresso') . '</a>';
561
+		} elseif ($this->_view === 'trash') {
562
+			// restore registration link
563
+			if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registration',
564
+				'espresso_registrations_restore_registrations', $item->ID())
565
+			) {
566
+				$restore_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
567
+					'action'  => 'restore_registrations',
568
+					'_REG_ID' => $item->ID(),
569
+				), REG_ADMIN_URL);
570
+				$actions['restore'] = '<a href="' . $restore_lnk_url . '" title="' . esc_attr__('Restore Registration',
571
+						'event_espresso') . '">' . __('Restore', 'event_espresso') . '</a>';
572
+			}
573
+			if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registration',
574
+				'espresso_registrations_ee_delete_registrations', $item->ID())
575
+			) {
576
+				$delete_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
577
+					'action'  => 'delete_registrations',
578
+					'_REG_ID' => $item->ID(),
579
+				), REG_ADMIN_URL);
580
+				$actions['delete'] = '<a href="'
581
+									 . $delete_lnk_url
582
+									 . '" title="'
583
+									 . esc_attr__('Delete Registration Permanently', 'event_espresso')
584
+									 . '">'
585
+									 . __('Delete', 'event_espresso')
586
+									 . '</a>';
587
+			}
588
+		}
589
+		return sprintf('%1$s %2$s', $link, $this->row_actions($actions));
590
+	}
591
+
592
+
593
+
594
+	/**
595
+	 * column_ATT_email
596
+	 *
597
+	 * @access public
598
+	 * @param \EE_Registration $item
599
+	 * @return string
600
+	 * @throws \EE_Error
601
+	 */
602
+	public function column_ATT_email(EE_Registration $item)
603
+	{
604
+		$attendee = $item->get_first_related('Attendee');
605
+		return ! $attendee instanceof EE_Attendee ? __('No attached contact record.', 'event_espresso')
606
+			: $attendee->email();
607
+	}
608
+
609
+
610
+
611
+	/**
612
+	 * column__REG_count
613
+	 *
614
+	 * @access public
615
+	 * @param \EE_Registration $item
616
+	 * @return string
617
+	 */
618
+	public function column__REG_count(EE_Registration $item)
619
+	{
620
+		return sprintf(__('%1$s / %2$s', 'event_espresso'), $item->count(), $item->group_size());
621
+	}
622
+
623
+
624
+
625
+	/**
626
+	 * column_PRC_amount
627
+	 *
628
+	 * @access public
629
+	 * @param \EE_Registration $item
630
+	 * @return string
631
+	 */
632
+	public function column_PRC_amount(EE_Registration $item)
633
+	{
634
+		$ticket = $item->ticket();
635
+		$content = isset($_GET['event_id']) && $ticket instanceof EE_Ticket ? '<span class="TKT_name">'
636
+																			  . $ticket->name()
637
+																			  . '</span><br />' : '';
638
+		if ($item->final_price() > 0) {
639
+			$content .= '<span class="reg-pad-rght">' . $item->pretty_final_price() . '</span>';
640
+		} else {
641
+			// free event
642
+			$content .= '<span class="reg-overview-free-event-spn reg-pad-rght">'
643
+						. __('free', 'event_espresso')
644
+						. '</span>';
645
+		}
646
+		return $content;
647
+	}
648
+
649
+
650
+
651
+	/**
652
+	 * column__REG_final_price
653
+	 *
654
+	 * @access public
655
+	 * @param \EE_Registration $item
656
+	 * @return string
657
+	 */
658
+	public function column__REG_final_price(EE_Registration $item)
659
+	{
660
+		$ticket = $item->ticket();
661
+		$content = isset($_GET['event_id']) || ! $ticket instanceof EE_Ticket
662
+			? ''
663
+			: '<span class="TKT_name">'
664
+			  . $ticket->name()
665
+			  . '</span><br />';
666
+		$content .= '<span class="reg-pad-rght">' . $item->pretty_final_price() . '</span>';
667
+		return $content;
668
+	}
669
+
670
+
671
+
672
+	/**
673
+	 * column__REG_paid
674
+	 *
675
+	 * @access public
676
+	 * @param \EE_Registration $item
677
+	 * @return string
678
+	 */
679
+	public function column__REG_paid(EE_Registration $item)
680
+	{
681
+		$payment_method = $item->payment_method();
682
+		$payment_method_name = $payment_method instanceof EE_Payment_Method ? $payment_method->admin_name()
683
+			: __('Unknown', 'event_espresso');
684
+		$content = '<span class="reg-pad-rght">' . $item->pretty_paid() . '</span>';
685
+		if ($item->paid() > 0) {
686
+			$content .= '<br><span class="ee-status-text-small">' . sprintf(__('...via %s', 'event_espresso'),
687
+					$payment_method_name) . '</span>';
688
+		}
689
+		return $content;
690
+	}
691
+
692
+
693
+
694
+	/**
695
+	 * column_TXN_total
696
+	 *
697
+	 * @access public
698
+	 * @param \EE_Registration $item
699
+	 * @return string
700
+	 * @throws \EE_Error
701
+	 */
702
+	public function column_TXN_total(EE_Registration $item)
703
+	{
704
+		if ($item->transaction()) {
705
+			$view_txn_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
706
+				'action' => 'view_transaction',
707
+				'TXN_ID' => $item->transaction_ID(),
708
+			), TXN_ADMIN_URL);
709
+			return EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
710
+				'espresso_transactions_view_transaction', $item->transaction_ID())
711
+				? '<span class="reg-pad-rght"><a class="status-'
712
+				  . $item->transaction()->status_ID()
713
+				  . '" href="'
714
+				  . $view_txn_lnk_url
715
+				  . '"  title="'
716
+				  . esc_attr__('View Transaction', 'event_espresso')
717
+				  . '">'
718
+				  . $item->transaction()->pretty_total()
719
+				  . '</a></span>' : '<span class="reg-pad-rght">' . $item->transaction()->pretty_total() . '</span>';
720
+		} else {
721
+			return __("None", "event_espresso");
722
+		}
723
+	}
724
+
725
+
726
+
727
+	/**
728
+	 * column_TXN_paid
729
+	 *
730
+	 * @access public
731
+	 * @param \EE_Registration $item
732
+	 * @return string
733
+	 * @throws \EE_Error
734
+	 */
735
+	public function column_TXN_paid(EE_Registration $item)
736
+	{
737
+		if ($item->count() === 1) {
738
+			$transaction = $item->transaction() ? $item->transaction() : EE_Transaction::new_instance();
739
+			if ($transaction->paid() >= $transaction->total()) {
740
+				return '<span class="reg-pad-rght"><div class="dashicons dashicons-yes green-icon"></div></span>';
741
+			} else {
742
+				$view_txn_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
743
+					'action' => 'view_transaction',
744
+					'TXN_ID' => $item->transaction_ID(),
745
+				), TXN_ADMIN_URL);
746
+				return EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
747
+					'espresso_transactions_view_transaction', $item->transaction_ID())
748
+					? '<span class="reg-pad-rght"><a class="status-'
749
+					  . $transaction->status_ID()
750
+					  . '" href="'
751
+					  . $view_txn_lnk_url
752
+					  . '"  title="'
753
+					  . esc_attr__('View Transaction', 'event_espresso')
754
+					  . '">'
755
+					  . $item->transaction()->pretty_paid()
756
+					  . '</a><span>' : '<span class="reg-pad-rght">' . $item->transaction()->pretty_paid() . '</span>';
757
+			}
758
+		}
759
+		return '&nbsp;';
760
+	}
761
+
762
+
763
+
764
+	/**
765
+	 * column_actions
766
+	 *
767
+	 * @access public
768
+	 * @param \EE_Registration $item
769
+	 * @return string
770
+	 * @throws \EE_Error
771
+	 */
772
+	public function column_actions(EE_Registration $item)
773
+	{
774
+		$actions = array();
775
+		$attendee = $item->attendee();
776
+		$this->_set_related_details($item);
777
+		//Build row actions
778
+		$view_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
779
+			'action'  => 'view_registration',
780
+			'_REG_ID' => $item->ID(),
781
+		), REG_ADMIN_URL);
782
+		$edit_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
783
+			'action' => 'edit_attendee',
784
+			'post'   => $item->attendee_ID(),
785
+		), REG_ADMIN_URL);
786
+		// page=attendees&event_admin_reports=resend_email&registration_id=43653465634&event_id=2&form_action=resend_email
787
+		//$resend_reg_lnk_url_params = array( 'action'=>'resend_registration', '_REG_ID'=>$item->REG_ID );
788
+		$resend_reg_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
789
+			'action'  => 'resend_registration',
790
+			'_REG_ID' => $item->ID(),
791
+		), REG_ADMIN_URL, true);
792
+		//Build row actions
793
+		$actions['view_lnk'] = EE_Registry::instance()->CAP->current_user_can('ee_read_registration',
794
+			'espresso_registrations_view_registration', $item->ID()) ? '
795 795
 			<li>
796 796
 			<a href="' . $view_lnk_url . '" title="' . esc_attr__('View Registration Details', 'event_espresso') . '" class="tiny-text">
797 797
 				<div class="dashicons dashicons-clipboard"></div>
798 798
 			</a>
799 799
 			</li>' : '';
800
-        $actions['edit_lnk'] = EE_Registry::instance()->CAP->current_user_can('ee_edit_contacts',
801
-            'espresso_registrations_edit_attendee')
802
-                               && $attendee instanceof EE_Attendee ? '
800
+		$actions['edit_lnk'] = EE_Registry::instance()->CAP->current_user_can('ee_edit_contacts',
801
+			'espresso_registrations_edit_attendee')
802
+							   && $attendee instanceof EE_Attendee ? '
803 803
 			<li>
804 804
 			<a href="' . $edit_lnk_url . '" title="' . esc_attr__('Edit Contact Details', 'event_espresso') . '" class="tiny-text">
805 805
 				<div class="ee-icon ee-icon-user-edit ee-icon-size-16"></div>
806 806
 			</a>
807 807
 			</li>' : '';
808
-        $actions['resend_reg_lnk'] = $attendee instanceof EE_Attendee
809
-                                     && EE_Registry::instance()->CAP->current_user_can('ee_send_message',
810
-            'espresso_registrations_resend_registration', $item->ID()) ? '
808
+		$actions['resend_reg_lnk'] = $attendee instanceof EE_Attendee
809
+									 && EE_Registry::instance()->CAP->current_user_can('ee_send_message',
810
+			'espresso_registrations_resend_registration', $item->ID()) ? '
811 811
 			<li>
812 812
 			<a href="'
813
-                                                                         . $resend_reg_lnk_url
814
-                                                                         . '" title="'
815
-                                                                         . esc_attr__('Resend Registration Details',
816
-                'event_espresso')
817
-                                                                         . '" class="tiny-text">
813
+																		 . $resend_reg_lnk_url
814
+																		 . '" title="'
815
+																		 . esc_attr__('Resend Registration Details',
816
+				'event_espresso')
817
+																		 . '" class="tiny-text">
818 818
 				<div class="dashicons dashicons-email-alt"></div>
819 819
 			</a>
820 820
 			</li>' : '';
821
-        // page=transactions&action=view_transaction&txn=256&_wpnonce=6414da4dbb
822
-        $view_txn_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
823
-            'action' => 'view_transaction',
824
-            'TXN_ID' => $this->_transaction_details['id'],
825
-        ), TXN_ADMIN_URL);
826
-        $actions['view_txn_lnk'] = EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
827
-            'espresso_transactions_view_transaction', $this->_transaction_details['id']) ? '
821
+		// page=transactions&action=view_transaction&txn=256&_wpnonce=6414da4dbb
822
+		$view_txn_lnk_url = EE_Admin_Page::add_query_args_and_nonce(array(
823
+			'action' => 'view_transaction',
824
+			'TXN_ID' => $this->_transaction_details['id'],
825
+		), TXN_ADMIN_URL);
826
+		$actions['view_txn_lnk'] = EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
827
+			'espresso_transactions_view_transaction', $this->_transaction_details['id']) ? '
828 828
 			<li>
829 829
 			<a class="ee-status-color-'
830
-                                                                                           . $this->_transaction_details['status']
831
-                                                                                           . ' tiny-text" href="'
832
-                                                                                           . $view_txn_lnk_url
833
-                                                                                           . '"  title="'
834
-                                                                                           . $this->_transaction_details['title_attr']
835
-                                                                                           . '">
830
+																						   . $this->_transaction_details['status']
831
+																						   . ' tiny-text" href="'
832
+																						   . $view_txn_lnk_url
833
+																						   . '"  title="'
834
+																						   . $this->_transaction_details['title_attr']
835
+																						   . '">
836 836
 				<div class="dashicons dashicons-cart"></div>
837 837
 			</a>
838 838
 			</li>' : '';
839
-        //invoice link
840
-        $actions['dl_invoice_lnk'] = '';
841
-        $dl_invoice_lnk_url = $item->invoice_url();
842
-        //only show invoice link if message type is active.
843
-        if ($attendee instanceof EE_Attendee
844
-            && $item->is_primary_registrant()
845
-            && EEH_MSG_Template::is_mt_active('invoice')
846
-        ) {
847
-            $actions['dl_invoice_lnk'] = '
839
+		//invoice link
840
+		$actions['dl_invoice_lnk'] = '';
841
+		$dl_invoice_lnk_url = $item->invoice_url();
842
+		//only show invoice link if message type is active.
843
+		if ($attendee instanceof EE_Attendee
844
+			&& $item->is_primary_registrant()
845
+			&& EEH_MSG_Template::is_mt_active('invoice')
846
+		) {
847
+			$actions['dl_invoice_lnk'] = '
848 848
 		<li>
849 849
 			<a title="'
850
-                                         . esc_attr__('View Transaction Invoice', 'event_espresso')
851
-                                         . '" target="_blank" href="'
852
-                                         . $dl_invoice_lnk_url
853
-                                         . '" class="tiny-text">
850
+										 . esc_attr__('View Transaction Invoice', 'event_espresso')
851
+										 . '" target="_blank" href="'
852
+										 . $dl_invoice_lnk_url
853
+										 . '" class="tiny-text">
854 854
 				<span class="dashicons dashicons-media-spreadsheet ee-icon-size-18"></span>
855 855
 			</a>
856 856
 		</li>';
857
-        }
858
-        $actions['filtered_messages_link'] = '';
859
-        //message list table link (filtered by REG_ID
860
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
861
-            $actions['filtered_messages_link'] = '<li>'
862
-                                                 . EEH_MSG_Template::get_message_action_link('see_notifications_for',
863
-                    null, array(
864
-                        '_REG_ID' => $item->ID(),
865
-                    ))
866
-                                                 . '</li>';
867
-        }
868
-        $actions = apply_filters('FHEE__EE_Registrations_List_Table__column_actions__actions', $actions, $item, $this);
869
-        return $this->_action_string(implode('', $actions), $item, 'ul', 'reg-overview-actions-ul');
870
-    }
857
+		}
858
+		$actions['filtered_messages_link'] = '';
859
+		//message list table link (filtered by REG_ID
860
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
861
+			$actions['filtered_messages_link'] = '<li>'
862
+												 . EEH_MSG_Template::get_message_action_link('see_notifications_for',
863
+					null, array(
864
+						'_REG_ID' => $item->ID(),
865
+					))
866
+												 . '</li>';
867
+		}
868
+		$actions = apply_filters('FHEE__EE_Registrations_List_Table__column_actions__actions', $actions, $item, $this);
869
+		return $this->_action_string(implode('', $actions), $item, 'ul', 'reg-overview-actions-ul');
870
+	}
871 871
 
872 872
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +16 added lines, -14 removed lines patch added patch discarded remove patch
@@ -860,7 +860,7 @@  discard block
 block discarded – undo
860 860
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
861 861
      * foreign key to the WP_User table)
862 862
      *
863
-     * @return string|boolean string on success, boolean false when there is no
863
+     * @return string|false string on success, boolean false when there is no
864 864
      * foreign key to the WP_User table
865 865
      */
866 866
     public function wp_user_field_name()
@@ -966,7 +966,7 @@  discard block
 block discarded – undo
966 966
      *
967 967
      * @param array  $query_params      like EEM_Base::get_all's $query_params
968 968
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
969
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
969
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
970 970
      *                                  fields on the model, and the models we joined to in the query. However, you can
971 971
      *                                  override this and set the select to "*", or a specific column name, like
972 972
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1358,7 +1358,7 @@  discard block
 block discarded – undo
1358 1358
      * @param string $field_name The name of the field the formats are being retrieved for.
1359 1359
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1360 1360
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1361
-     * @return array formats in an array with the date format first, and the time format last.
1361
+     * @return string[] formats in an array with the date format first, and the time format last.
1362 1362
      */
1363 1363
     public function get_formats_for($field_name, $pretty = false)
1364 1364
     {
@@ -1391,7 +1391,7 @@  discard block
 block discarded – undo
1391 1391
      *                                 be returned.
1392 1392
      * @param string $what             Whether to return the string in just the time format, the date format, or both.
1393 1393
      * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1394
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1394
+     * @return string|null  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1395 1395
      *                                 exception is triggered.
1396 1396
      */
1397 1397
     public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
@@ -1723,7 +1723,7 @@  discard block
 block discarded – undo
1723 1723
      * Wrapper for EEM_Base::delete_permanently()
1724 1724
      *
1725 1725
      * @param mixed $id
1726
-     * @return boolean whether the row got deleted or not
1726
+     * @return integer whether the row got deleted or not
1727 1727
      * @throws \EE_Error
1728 1728
      */
1729 1729
     public function delete_permanently_by_ID($id)
@@ -1743,7 +1743,7 @@  discard block
 block discarded – undo
1743 1743
      * Wrapper for EEM_Base::delete()
1744 1744
      *
1745 1745
      * @param mixed $id
1746
-     * @return boolean whether the row got deleted or not
1746
+     * @return integer whether the row got deleted or not
1747 1747
      * @throws \EE_Error
1748 1748
      */
1749 1749
     public function delete_by_ID($id)
@@ -2193,7 +2193,7 @@  discard block
 block discarded – undo
2193 2193
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2194 2194
      * EEM_Base::$_db_verification_level
2195 2195
      *
2196
-     * @param $wpdb_method
2196
+     * @param string $wpdb_method
2197 2197
      * @param $arguments_to_provide
2198 2198
      * @return string
2199 2199
      */
@@ -2317,6 +2317,7 @@  discard block
 block discarded – undo
2317 2317
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2318 2318
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2319 2319
      *                             because these will be inserted in any new rows created as well.
2320
+     * @param EE_Base_Class $id_or_obj
2320 2321
      */
2321 2322
     public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2322 2323
     {
@@ -2327,7 +2328,7 @@  discard block
 block discarded – undo
2327 2328
 
2328 2329
 
2329 2330
     /**
2330
-     * @param mixed           $id_or_obj
2331
+     * @param EE_Base_Class           $id_or_obj
2331 2332
      * @param string          $relationName
2332 2333
      * @param array           $where_query_params
2333 2334
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2368,7 +2369,7 @@  discard block
 block discarded – undo
2368 2369
      * However, if the model objects can't be deleted because of blocking related model objects, then
2369 2370
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2370 2371
      *
2371
-     * @param EE_Base_Class|int|string $id_or_obj
2372
+     * @param EE_Base_Class $id_or_obj
2372 2373
      * @param string                   $model_name
2373 2374
      * @param array                    $query_params
2374 2375
      * @return int how many deleted
@@ -2389,7 +2390,7 @@  discard block
 block discarded – undo
2389 2390
      * the model objects can't be hard deleted because of blocking related model objects,
2390 2391
      * just does a soft-delete on them instead.
2391 2392
      *
2392
-     * @param EE_Base_Class|int|string $id_or_obj
2393
+     * @param EE_Base_Class $id_or_obj
2393 2394
      * @param string                   $model_name
2394 2395
      * @param array                    $query_params
2395 2396
      * @return int how many deleted
@@ -2446,6 +2447,7 @@  discard block
 block discarded – undo
2446 2447
      * @param string $model_name   like 'Event', or 'Registration'
2447 2448
      * @param array  $query_params like EEM_Base::get_all's
2448 2449
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2450
+     * @param EE_Base_Class $id_or_obj
2449 2451
      * @return float
2450 2452
      * @throws \EE_Error
2451 2453
      */
@@ -2909,7 +2911,7 @@  discard block
 block discarded – undo
2909 2911
      * Finds all the fields that correspond to the given table
2910 2912
      *
2911 2913
      * @param string $table_alias , array key in EEM_Base::_tables
2912
-     * @return EE_Model_Field_Base[]
2914
+     * @return EE_Model_Field_Base
2913 2915
      */
2914 2916
     public function _get_fields_for_table($table_alias)
2915 2917
     {
@@ -4354,7 +4356,7 @@  discard block
 block discarded – undo
4354 4356
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4355 4357
      * Eg, on EE_Answer that would be ANS_ID field object
4356 4358
      *
4357
-     * @param $field_obj
4359
+     * @param EE_Model_Field_Base $field_obj
4358 4360
      * @return boolean
4359 4361
      */
4360 4362
     public function is_primary_key_field($field_obj)
@@ -4465,7 +4467,7 @@  discard block
 block discarded – undo
4465 4467
      * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4466 4468
      *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4467 4469
      *                            Either one works
4468
-     * @return EE_Table_Base
4470
+     * @return string
4469 4471
      */
4470 4472
     public function get_table_for_alias($table_alias)
4471 4473
     {
@@ -5075,7 +5077,7 @@  discard block
 block discarded – undo
5075 5077
     /**
5076 5078
      * Read comments for assume_values_already_prepared_by_model_object()
5077 5079
      *
5078
-     * @return int
5080
+     * @return boolean
5079 5081
      */
5080 5082
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5081 5083
     {
Please login to merge, or discard this patch.
Indentation   +5511 added lines, -5511 removed lines patch added patch discarded remove patch
@@ -29,5526 +29,5526 @@
 block discarded – undo
29 29
 abstract class EEM_Base extends EE_Base
30 30
 {
31 31
 
32
-    //admin posty
33
-    //basic -> grants access to mine -> if they don't have it, select none
34
-    //*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
35
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
36
-    //*_published -> grants access to published -> if they dont have it, select non-published
37
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
38
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
39
-    //frontend posty
40
-    //by default has access to published
41
-    //basic -> grants access to mine that arent published, and all published
42
-    //*_others ->grants access to others that arent private, all mine
43
-    //*_private -> grants full access
44
-    //frontend non-posty
45
-    //like admin posty
46
-    //category-y
47
-    //assign -> grants access to join-table
48
-    //(delete, edit)
49
-    //payment-method-y
50
-    //for each registered payment method,
51
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
52
-    /**
53
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
54
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
55
-     * They almost always WILL NOT, but it's not necessarily a requirement.
56
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
57
-     *
58
-     * @var boolean
59
-     */
60
-    private $_values_already_prepared_by_model_object = 0;
61
-
62
-    /**
63
-     * when $_values_already_prepared_by_model_object equals this, we assume
64
-     * the data is just like form input that needs to have the model fields'
65
-     * prepare_for_set and prepare_for_use_in_db called on it
66
-     */
67
-    const not_prepared_by_model_object = 0;
68
-
69
-    /**
70
-     * when $_values_already_prepared_by_model_object equals this, we
71
-     * assume this value is coming from a model object and doesn't need to have
72
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
73
-     */
74
-    const prepared_by_model_object = 1;
75
-
76
-    /**
77
-     * when $_values_already_prepared_by_model_object equals this, we assume
78
-     * the values are already to be used in the database (ie no processing is done
79
-     * on them by the model's fields)
80
-     */
81
-    const prepared_for_use_in_db = 2;
82
-
83
-
84
-    protected $singular_item = 'Item';
85
-
86
-    protected $plural_item   = 'Items';
87
-
88
-    /**
89
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
90
-     */
91
-    protected $_tables;
92
-
93
-    /**
94
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
95
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
96
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
97
-     *
98
-     * @var \EE_Model_Field_Base[] $_fields
99
-     */
100
-    protected $_fields;
101
-
102
-    /**
103
-     * array of different kinds of relations
104
-     *
105
-     * @var \EE_Model_Relation_Base[] $_model_relations
106
-     */
107
-    protected $_model_relations;
108
-
109
-    /**
110
-     * @var \EE_Index[] $_indexes
111
-     */
112
-    protected $_indexes = array();
113
-
114
-    /**
115
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
116
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
117
-     * by setting the same columns as used in these queries in the query yourself.
118
-     *
119
-     * @var EE_Default_Where_Conditions
120
-     */
121
-    protected $_default_where_conditions_strategy;
122
-
123
-    /**
124
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
125
-     * This is particularly useful when you want something between 'none' and 'default'
126
-     *
127
-     * @var EE_Default_Where_Conditions
128
-     */
129
-    protected $_minimum_where_conditions_strategy;
130
-
131
-    /**
132
-     * String describing how to find the "owner" of this model's objects.
133
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
134
-     * But when there isn't, this indicates which related model, or transiently-related model,
135
-     * has the foreign key to the wp_users table.
136
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
137
-     * related to events, and events have a foreign key to wp_users.
138
-     * On EEM_Transaction, this would be 'Transaction.Event'
139
-     *
140
-     * @var string
141
-     */
142
-    protected $_model_chain_to_wp_user = '';
143
-
144
-    /**
145
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
146
-     * don't need it (particularly CPT models)
147
-     *
148
-     * @var bool
149
-     */
150
-    protected $_ignore_where_strategy = false;
151
-
152
-    /**
153
-     * String used in caps relating to this model. Eg, if the caps relating to this
154
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
155
-     *
156
-     * @var string. If null it hasn't been initialized yet. If false then we
157
-     * have indicated capabilities don't apply to this
158
-     */
159
-    protected $_caps_slug = null;
160
-
161
-    /**
162
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
163
-     * and next-level keys are capability names, and each's value is a
164
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
165
-     * they specify which context to use (ie, frontend, backend, edit or delete)
166
-     * and then each capability in the corresponding sub-array that they're missing
167
-     * adds the where conditions onto the query.
168
-     *
169
-     * @var array
170
-     */
171
-    protected $_cap_restrictions = array(
172
-        self::caps_read       => array(),
173
-        self::caps_read_admin => array(),
174
-        self::caps_edit       => array(),
175
-        self::caps_delete     => array(),
176
-    );
177
-
178
-    /**
179
-     * Array defining which cap restriction generators to use to create default
180
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
181
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
182
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
183
-     * automatically set this to false (not just null).
184
-     *
185
-     * @var EE_Restriction_Generator_Base[]
186
-     */
187
-    protected $_cap_restriction_generators = array();
188
-
189
-    /**
190
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
191
-     */
192
-    const caps_read       = 'read';
193
-
194
-    const caps_read_admin = 'read_admin';
195
-
196
-    const caps_edit       = 'edit';
197
-
198
-    const caps_delete     = 'delete';
199
-
200
-    /**
201
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
202
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
203
-     * maps to 'read' because when looking for relevant permissions we're going to use
204
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
205
-     *
206
-     * @var array
207
-     */
208
-    protected $_cap_contexts_to_cap_action_map = array(
209
-        self::caps_read       => 'read',
210
-        self::caps_read_admin => 'read',
211
-        self::caps_edit       => 'edit',
212
-        self::caps_delete     => 'delete',
213
-    );
214
-
215
-    /**
216
-     * Timezone
217
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
218
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
219
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
220
-     * EE_Datetime_Field data type will have access to it.
221
-     *
222
-     * @var string
223
-     */
224
-    protected $_timezone;
225
-
226
-
227
-    /**
228
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
229
-     * multisite.
230
-     *
231
-     * @var int
232
-     */
233
-    protected static $_model_query_blog_id;
234
-
235
-    /**
236
-     * A copy of _fields, except the array keys are the model names pointed to by
237
-     * the field
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cache_foreign_key_to_fields = array();
242
-
243
-    /**
244
-     * Cached list of all the fields on the model, indexed by their name
245
-     *
246
-     * @var EE_Model_Field_Base[]
247
-     */
248
-    private $_cached_fields = null;
249
-
250
-    /**
251
-     * Cached list of all the fields on the model, except those that are
252
-     * marked as only pertinent to the database
253
-     *
254
-     * @var EE_Model_Field_Base[]
255
-     */
256
-    private $_cached_fields_non_db_only = null;
257
-
258
-    /**
259
-     * A cached reference to the primary key for quick lookup
260
-     *
261
-     * @var EE_Model_Field_Base
262
-     */
263
-    private $_primary_key_field = null;
264
-
265
-    /**
266
-     * Flag indicating whether this model has a primary key or not
267
-     *
268
-     * @var boolean
269
-     */
270
-    protected $_has_primary_key_field = null;
271
-
272
-    /**
273
-     * Whether or not this model is based off a table in WP core only (CPTs should set
274
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
275
-     *
276
-     * @var boolean
277
-     */
278
-    protected $_wp_core_model = false;
279
-
280
-    /**
281
-     *    List of valid operators that can be used for querying.
282
-     * The keys are all operators we'll accept, the values are the real SQL
283
-     * operators used
284
-     *
285
-     * @var array
286
-     */
287
-    protected $_valid_operators = array(
288
-        '='           => '=',
289
-        '<='          => '<=',
290
-        '<'           => '<',
291
-        '>='          => '>=',
292
-        '>'           => '>',
293
-        '!='          => '!=',
294
-        'LIKE'        => 'LIKE',
295
-        'like'        => 'LIKE',
296
-        'NOT_LIKE'    => 'NOT LIKE',
297
-        'not_like'    => 'NOT LIKE',
298
-        'NOT LIKE'    => 'NOT LIKE',
299
-        'not like'    => 'NOT LIKE',
300
-        'IN'          => 'IN',
301
-        'in'          => 'IN',
302
-        'NOT_IN'      => 'NOT IN',
303
-        'not_in'      => 'NOT IN',
304
-        'NOT IN'      => 'NOT IN',
305
-        'not in'      => 'NOT IN',
306
-        'between'     => 'BETWEEN',
307
-        'BETWEEN'     => 'BETWEEN',
308
-        'IS_NOT_NULL' => 'IS NOT NULL',
309
-        'is_not_null' => 'IS NOT NULL',
310
-        'IS NOT NULL' => 'IS NOT NULL',
311
-        'is not null' => 'IS NOT NULL',
312
-        'IS_NULL'     => 'IS NULL',
313
-        'is_null'     => 'IS NULL',
314
-        'IS NULL'     => 'IS NULL',
315
-        'is null'     => 'IS NULL',
316
-        'REGEXP'      => 'REGEXP',
317
-        'regexp'      => 'REGEXP',
318
-        'NOT_REGEXP'  => 'NOT REGEXP',
319
-        'not_regexp'  => 'NOT REGEXP',
320
-        'NOT REGEXP'  => 'NOT REGEXP',
321
-        'not regexp'  => 'NOT REGEXP',
322
-    );
323
-
324
-    /**
325
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
326
-     *
327
-     * @var array
328
-     */
329
-    protected $_in_style_operators = array('IN', 'NOT IN');
330
-
331
-    /**
332
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
333
-     * '12-31-2012'"
334
-     *
335
-     * @var array
336
-     */
337
-    protected $_between_style_operators = array('BETWEEN');
338
-
339
-    /**
340
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
341
-     * on a join table.
342
-     *
343
-     * @var array
344
-     */
345
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
346
-
347
-    /**
348
-     * Allowed values for $query_params['order'] for ordering in queries
349
-     *
350
-     * @var array
351
-     */
352
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
353
-
354
-    /**
355
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
356
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
357
-     *
358
-     * @var array
359
-     */
360
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
361
-
362
-    /**
363
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
364
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
365
-     *
366
-     * @var array
367
-     */
368
-    private $_allowed_query_params = array(
369
-        0,
370
-        'limit',
371
-        'order_by',
372
-        'group_by',
373
-        'having',
374
-        'force_join',
375
-        'order',
376
-        'on_join_limit',
377
-        'default_where_conditions',
378
-        'caps',
379
-    );
380
-
381
-    /**
382
-     * All the data types that can be used in $wpdb->prepare statements.
383
-     *
384
-     * @var array
385
-     */
386
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
387
-
388
-    /**
389
-     *    EE_Registry Object
390
-     *
391
-     * @var    object
392
-     * @access    protected
393
-     */
394
-    protected $EE = null;
395
-
396
-
397
-    /**
398
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
399
-     *
400
-     * @var int
401
-     */
402
-    protected $_show_next_x_db_queries = 0;
403
-
404
-    /**
405
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
406
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
407
-     *
408
-     * @var array
409
-     */
410
-    protected $_custom_selections = array();
411
-
412
-    /**
413
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
414
-     * caches every model object we've fetched from the DB on this request
415
-     *
416
-     * @var array
417
-     */
418
-    protected $_entity_map;
419
-
420
-    /**
421
-     * constant used to show EEM_Base has not yet verified the db on this http request
422
-     */
423
-    const db_verified_none = 0;
424
-
425
-    /**
426
-     * constant used to show EEM_Base has verified the EE core db on this http request,
427
-     * but not the addons' dbs
428
-     */
429
-    const db_verified_core = 1;
430
-
431
-    /**
432
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
433
-     * the EE core db too)
434
-     */
435
-    const db_verified_addons = 2;
436
-
437
-    /**
438
-     * indicates whether an EEM_Base child has already re-verified the DB
439
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
440
-     * looking like EEM_Base::db_verified_*
441
-     *
442
-     * @var int - 0 = none, 1 = core, 2 = addons
443
-     */
444
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
445
-
446
-
447
-
448
-    /**
449
-     * About all child constructors:
450
-     * they should define the _tables, _fields and _model_relations arrays.
451
-     * Should ALWAYS be called after child constructor.
452
-     * In order to make the child constructors to be as simple as possible, this parent constructor
453
-     * finalizes constructing all the object's attributes.
454
-     * Generally, rather than requiring a child to code
455
-     * $this->_tables = array(
456
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
457
-     *        ...);
458
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
459
-     * each EE_Table has a function to set the table's alias after the constructor, using
460
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
461
-     * do something similar.
462
-     *
463
-     * @param null $timezone
464
-     * @throws \EE_Error
465
-     */
466
-    protected function __construct($timezone = null)
467
-    {
468
-        // check that the model has not been loaded too soon
469
-        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
470
-            throw new EE_Error (
471
-                sprintf(
472
-                    __('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.',
473
-                        'event_espresso'),
474
-                    get_class($this)
475
-                )
476
-            );
477
-        }
478
-        /**
479
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
480
-         */
481
-        if (empty(EEM_Base::$_model_query_blog_id)) {
482
-            EEM_Base::set_model_query_blog_id();
483
-        }
484
-        /**
485
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
486
-         * just use EE_Register_Model_Extension
487
-         *
488
-         * @var EE_Table_Base[] $_tables
489
-         */
490
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
491
-        foreach ($this->_tables as $table_alias => $table_obj) {
492
-            /** @var $table_obj EE_Table_Base */
493
-            $table_obj->_construct_finalize_with_alias($table_alias);
494
-            if ($table_obj instanceof EE_Secondary_Table) {
495
-                /** @var $table_obj EE_Secondary_Table */
496
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
497
-            }
498
-        }
499
-        /**
500
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
501
-         * EE_Register_Model_Extension
502
-         *
503
-         * @param EE_Model_Field_Base[] $_fields
504
-         */
505
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
506
-        $this->_invalidate_field_caches();
507
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
508
-            if ( ! array_key_exists($table_alias, $this->_tables)) {
509
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
510
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
511
-            }
512
-            foreach ($fields_for_table as $field_name => $field_obj) {
513
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
514
-                //primary key field base has a slightly different _construct_finalize
515
-                /** @var $field_obj EE_Model_Field_Base */
516
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
517
-            }
518
-        }
519
-        // everything is related to Extra_Meta
520
-        if (get_class($this) !== 'EEM_Extra_Meta') {
521
-            //make extra meta related to everything, but don't block deleting things just
522
-            //because they have related extra meta info. For now just orphan those extra meta
523
-            //in the future we should automatically delete them
524
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
525
-        }
526
-        //and change logs
527
-        if (get_class($this) !== 'EEM_Change_Log') {
528
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
529
-        }
530
-        /**
531
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
532
-         * EE_Register_Model_Extension
533
-         *
534
-         * @param EE_Model_Relation_Base[] $_model_relations
535
-         */
536
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
537
-            $this->_model_relations);
538
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
539
-            /** @var $relation_obj EE_Model_Relation_Base */
540
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
541
-        }
542
-        foreach ($this->_indexes as $index_name => $index_obj) {
543
-            /** @var $index_obj EE_Index */
544
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
545
-        }
546
-        $this->set_timezone($timezone);
547
-        //finalize default where condition strategy, or set default
548
-        if ( ! $this->_default_where_conditions_strategy) {
549
-            //nothing was set during child constructor, so set default
550
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
551
-        }
552
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
553
-        if ( ! $this->_minimum_where_conditions_strategy) {
554
-            //nothing was set during child constructor, so set default
555
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
556
-        }
557
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
558
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
559
-        //to indicate to NOT set it, set it to the logical default
560
-        if ($this->_caps_slug === null) {
561
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
562
-        }
563
-        //initialize the standard cap restriction generators if none were specified by the child constructor
564
-        if ($this->_cap_restriction_generators !== false) {
565
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
566
-                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
567
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
568
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
569
-                        new EE_Restriction_Generator_Protected(),
570
-                        $cap_context,
571
-                        $this
572
-                    );
573
-                }
574
-            }
575
-        }
576
-        //if there are cap restriction generators, use them to make the default cap restrictions
577
-        if ($this->_cap_restriction_generators !== false) {
578
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
579
-                if ( ! $generator_object) {
580
-                    continue;
581
-                }
582
-                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
583
-                    throw new EE_Error(
584
-                        sprintf(
585
-                            __('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.',
586
-                                'event_espresso'),
587
-                            $context,
588
-                            $this->get_this_model_name()
589
-                        )
590
-                    );
591
-                }
592
-                $action = $this->cap_action_for_context($context);
593
-                if ( ! $generator_object->construction_finalized()) {
594
-                    $generator_object->_construct_finalize($this, $action);
595
-                }
596
-            }
597
-        }
598
-        do_action('AHEE__' . get_class($this) . '__construct__end');
599
-    }
600
-
601
-
602
-
603
-    /**
604
-     * Generates the cap restrictions for the given context, or if they were
605
-     * already generated just gets what's cached
606
-     *
607
-     * @param string $context one of EEM_Base::valid_cap_contexts()
608
-     * @return EE_Default_Where_Conditions[]
609
-     */
610
-    protected function _generate_cap_restrictions($context)
611
-    {
612
-        if (isset($this->_cap_restriction_generators[$context])
613
-            && $this->_cap_restriction_generators[$context]
614
-               instanceof
615
-               EE_Restriction_Generator_Base
616
-        ) {
617
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
618
-        } else {
619
-            return array();
620
-        }
621
-    }
622
-
623
-
624
-
625
-    /**
626
-     * Used to set the $_model_query_blog_id static property.
627
-     *
628
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
629
-     *                      value for get_current_blog_id() will be used.
630
-     */
631
-    public static function set_model_query_blog_id($blog_id = 0)
632
-    {
633
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
634
-    }
635
-
636
-
637
-
638
-    /**
639
-     * Returns whatever is set as the internal $model_query_blog_id.
640
-     *
641
-     * @return int
642
-     */
643
-    public static function get_model_query_blog_id()
644
-    {
645
-        return EEM_Base::$_model_query_blog_id;
646
-    }
647
-
648
-
649
-
650
-    /**
651
-     *        This function is a singleton method used to instantiate the Espresso_model object
652
-     *
653
-     * @access public
654
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
655
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
656
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
657
-     *                         timezone in the 'timezone_string' wp option)
658
-     * @return static (as in the concrete child class)
659
-     */
660
-    public static function instance($timezone = null)
661
-    {
662
-        // check if instance of Espresso_model already exists
663
-        if ( ! static::$_instance instanceof static) {
664
-            // instantiate Espresso_model
665
-            static::$_instance = new static($timezone);
666
-        }
667
-        //we might have a timezone set, let set_timezone decide what to do with it
668
-        static::$_instance->set_timezone($timezone);
669
-        // Espresso_model object
670
-        return static::$_instance;
671
-    }
672
-
673
-
674
-
675
-    /**
676
-     * resets the model and returns it
677
-     *
678
-     * @param null | string $timezone
679
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
680
-     * all its properties reset; if it wasn't instantiated, returns null)
681
-     */
682
-    public static function reset($timezone = null)
683
-    {
684
-        if (static::$_instance instanceof EEM_Base) {
685
-            //let's try to NOT swap out the current instance for a new one
686
-            //because if someone has a reference to it, we can't remove their reference
687
-            //so it's best to keep using the same reference, but change the original object
688
-            //reset all its properties to their original values as defined in the class
689
-            $r = new ReflectionClass(get_class(static::$_instance));
690
-            $static_properties = $r->getStaticProperties();
691
-            foreach ($r->getDefaultProperties() as $property => $value) {
692
-                //don't set instance to null like it was originally,
693
-                //but it's static anyways, and we're ignoring static properties (for now at least)
694
-                if ( ! isset($static_properties[$property])) {
695
-                    static::$_instance->{$property} = $value;
696
-                }
697
-            }
698
-            //and then directly call its constructor again, like we would if we
699
-            //were creating a new one
700
-            static::$_instance->__construct($timezone);
701
-            return self::instance();
702
-        }
703
-        return null;
704
-    }
705
-
706
-
707
-
708
-    /**
709
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
710
-     *
711
-     * @param  boolean $translated return localized strings or JUST the array.
712
-     * @return array
713
-     * @throws \EE_Error
714
-     */
715
-    public function status_array($translated = false)
716
-    {
717
-        if ( ! array_key_exists('Status', $this->_model_relations)) {
718
-            return array();
719
-        }
720
-        $model_name = $this->get_this_model_name();
721
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
722
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
723
-        $status_array = array();
724
-        foreach ($stati as $status) {
725
-            $status_array[$status->ID()] = $status->get('STS_code');
726
-        }
727
-        return $translated
728
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
729
-            : $status_array;
730
-    }
731
-
732
-
733
-
734
-    /**
735
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
736
-     *
737
-     * @param array $query_params             {
738
-     * @var array $0 (where) array {
739
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
740
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
741
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
742
-     *                                        conditions based on related models (and even
743
-     *                                        models-related-to-related-models) prepend the model's name onto the field
744
-     *                                        name. Eg,
745
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
746
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
747
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
748
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
749
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE Venue_CPT.ID = 12 Notice that automatically took care of joining Events to Venues (even when each of those models actually consisted of two tables). Also, you may chain the model relations together. Eg instead of just having "Venue.VNU_ID", you could have
750
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
751
-     *                                        events are related to Registrations, which are related to Attendees). You
752
-     *                                        can take it even further with
753
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
754
-     *                                        (from the default of '='), change the value to an numerically-indexed
755
-     *                                        array, where the first item in the list is the operator. eg: array(
756
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
757
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
758
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
759
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
760
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN (followed by an array with exactly 2 date strings), IS NULL, and IS NOT NULL Values can be a string, int, or float. They can also be arrays IFF the operator is IN. Also, values can actually be field names. To indicate the value is a field, simply provide a third array item (true) to the operator-value array like so: eg: array( 'DTT_reg_limit' => array('>', 'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold" Note: you can also use related model field names like you would any other field name. eg: array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could 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__>' => 345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp = 345678912...". Also, to negate an entire set of conditions, use 'NOT' as an array key. eg: array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND TXN_paid =23) Note: the 'glue' used to join each condition will continue to be what you last specified. IE, "AND"s by default, but if you had previously specified to use ORs to join, ORs will continue to be used. So, if you specify to use an "OR" to join conditions, it will continue to "stick" until you specify an AND. eg array('OR'=>array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >> "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND STS_ID='TIN'" They can be nested indefinitely. eg: 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 >> "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND PAY_timestamp != 1241234123" This can be applied to condition operators too, eg: array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
761
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
762
-     *      limits of "23", "25,50", and array(23,42) are all valid would become SQL "...LIMIT 23", "...LIMIT 25,50",
763
-     *      and "...LIMIT 23,42" respectively. Remember when you provide two numbers for the limit, the 1st number is
764
-     *      the OFFSET, the 2nd is the LIMIT
765
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
766
-     *      can do paging on one-to-many multi-table-joins. Send an array in the following format array('on_join_limit'
767
-     *      => array( 'table_alias', array(1,2) ) ).
768
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
769
-     *      values are either 'ASC' or 'DESC'. 'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
770
-     *      SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date DESC..." respectively. Like the
771
-     *      'where' conditions, these fields can be on related models. Eg
772
-     *      'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is perfectly valid from any model related
773
-     *      to 'Registration' (like Event, Attendee, Price, Datetime, etc.)
774
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
775
-     *      'order' specifies whether to order the field specified in 'order_by' in ascending or descending order.
776
-     *      Acceptable values are 'ASC' or 'DESC'. If, 'order_by' isn't used, but 'order' is, then it is assumed you
777
-     *      want to order by the primary key. Eg,
778
-     *      EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC'); //(will join
779
-     *      with the Datetime model's table(s) and order by its field DTT_EVT_start) or
780
-     *      EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make SQL "SELECT * FROM
781
-     *      wp_esp_registration ORDER BY REG_ID ASC"
782
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
783
-     *      'group_by'=>'VNU_ID', or 'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note: if no
784
-     *      $group_by is specified, and a limit is set, automatically groups by the model's primary key (or combined
785
-     *      primary keys). This avoids some weirdness that results when using limits, tons of joins, and no group by,
786
-     *      see https://events.codebasehq.com/projects/event-espresso/tickets/9389
787
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
788
-     *      grouped results (whereas WHERE conditions apply to the pre-grouped results)
789
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
790
-     *      array where values are models to be joined in the query.Eg array('Attendee','Payment','Datetime'). You may
791
-     *      join with transient models using period, eg "Registration.Transaction.Payment". You will probably only want
792
-     *      to do this in hopes of increasing efficiency, as related models which belongs to the current model
793
-     *                                        (ie, the current model has a foreign key to them, like how Registration
794
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
795
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
796
-     *      set this to 'none' to disable all default where conditions. Eg, usually soft-deleted objects are
797
-     *      filtered-out if you want to include them, set this query param to 'none'. If you want to ONLY disable THIS
798
-     *      model's default where conditions set it to 'other_models_only'. If you only want this model's default where
799
-     *      conditions added to the query, use 'this_model_only'. If you want to use all default where conditions
800
-     *      (default), set to 'all'.
801
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
802
-     *      we just NOT apply any capabilities/permissions/restrictions and return everything? Or should we only show
803
-     *      the current user items they should be able to view on the frontend, backend, edit, or delete? can be set to
804
-     *      'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
805
-     *                                        }
806
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
807
-     *                          from EE_Base_Class[], use _get_all_wpdb_results()and make it public again. Array keys
808
-     *                          are object IDs (if there is a primary key on the model. if not, numerically indexed)
809
-     *                          Some full examples: get 10 transactions which have Scottish attendees:
810
-     *                          EEM_Transaction::instance()->get_all( array( array(
811
-     *                                        'OR'=>array(
812
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
813
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
814
-     *                                        )
815
-     *                                        ),
816
-     *                                        'limit'=>10,
817
-     *                                        'group_by'=>'TXN_ID'
818
-     *                                        ));
819
-     *                                        get all the answers to the question titled "shirt size" for event with id
820
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
821
-     *                                        'Question.QST_display_text'=>'shirt size',
822
-     *                                        'Registration.Event.EVT_ID'=>12
823
-     *                                        ),
824
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
825
-     *                                        ));
826
-     * @throws \EE_Error
827
-     */
828
-    public function get_all($query_params = array())
829
-    {
830
-        if (isset($query_params['limit'])
831
-            && ! isset($query_params['group_by'])
832
-        ) {
833
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
834
-        }
835
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
836
-    }
837
-
838
-
839
-
840
-    /**
841
-     * Modifies the query parameters so we only get back model objects
842
-     * that "belong" to the current user
843
-     *
844
-     * @param array $query_params @see EEM_Base::get_all()
845
-     * @return array like EEM_Base::get_all
846
-     */
847
-    public function alter_query_params_to_only_include_mine($query_params = array())
848
-    {
849
-        $wp_user_field_name = $this->wp_user_field_name();
850
-        if ($wp_user_field_name) {
851
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
852
-        }
853
-        return $query_params;
854
-    }
855
-
856
-
857
-
858
-    /**
859
-     * Returns the name of the field's name that points to the WP_User table
860
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
861
-     * foreign key to the WP_User table)
862
-     *
863
-     * @return string|boolean string on success, boolean false when there is no
864
-     * foreign key to the WP_User table
865
-     */
866
-    public function wp_user_field_name()
867
-    {
868
-        try {
869
-            if ( ! empty($this->_model_chain_to_wp_user)) {
870
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
871
-                $last_model_name = end($models_to_follow_to_wp_users);
872
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
873
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
874
-            } else {
875
-                $model_with_fk_to_wp_users = $this;
876
-                $model_chain_to_wp_user = '';
877
-            }
878
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
879
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
880
-        } catch (EE_Error $e) {
881
-            return false;
882
-        }
883
-    }
884
-
885
-
886
-
887
-    /**
888
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
889
-     * (or transiently-related model) has a foreign key to the wp_users table;
890
-     * useful for finding if model objects of this type are 'owned' by the current user.
891
-     * This is an empty string when the foreign key is on this model and when it isn't,
892
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
893
-     * (or transiently-related model)
894
-     *
895
-     * @return string
896
-     */
897
-    public function model_chain_to_wp_user()
898
-    {
899
-        return $this->_model_chain_to_wp_user;
900
-    }
901
-
902
-
903
-
904
-    /**
905
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
906
-     * like how registrations don't have a foreign key to wp_users, but the
907
-     * events they are for are), or is unrelated to wp users.
908
-     * generally available
909
-     *
910
-     * @return boolean
911
-     */
912
-    public function is_owned()
913
-    {
914
-        if ($this->model_chain_to_wp_user()) {
915
-            return true;
916
-        } else {
917
-            try {
918
-                $this->get_foreign_key_to('WP_User');
919
-                return true;
920
-            } catch (EE_Error $e) {
921
-                return false;
922
-            }
923
-        }
924
-    }
925
-
926
-
927
-
928
-    /**
929
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
930
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
931
-     * the model)
932
-     *
933
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
934
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
935
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
936
-     *                                  fields on the model, and the models we joined to in the query. However, you can
937
-     *                                  override this and set the select to "*", or a specific column name, like
938
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
939
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
940
-     *                                  the aliases used to refer to this selection, and values are to be
941
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
942
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
943
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
944
-     * @throws \EE_Error
945
-     */
946
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
947
-    {
948
-        // remember the custom selections, if any, and type cast as array
949
-        // (unless $columns_to_select is an object, then just set as an empty array)
950
-        // Note: (array) 'some string' === array( 'some string' )
951
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
952
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
953
-        $select_expressions = $columns_to_select !== null
954
-            ? $this->_construct_select_from_input($columns_to_select)
955
-            : $this->_construct_default_select_sql($model_query_info);
956
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
957
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
958
-    }
959
-
960
-
961
-
962
-    /**
963
-     * Gets an array of rows from the database just like $wpdb->get_results would,
964
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
965
-     * take care of joins, field preparation etc.
966
-     *
967
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
968
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
969
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
970
-     *                                  fields on the model, and the models we joined to in the query. However, you can
971
-     *                                  override this and set the select to "*", or a specific column name, like
972
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
973
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
974
-     *                                  the aliases used to refer to this selection, and values are to be
975
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
976
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
977
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
978
-     * @throws \EE_Error
979
-     */
980
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
981
-    {
982
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
983
-    }
984
-
985
-
986
-
987
-    /**
988
-     * For creating a custom select statement
989
-     *
990
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
991
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
992
-     *                                 SQL, and 1=>is the datatype
993
-     * @throws EE_Error
994
-     * @return string
995
-     */
996
-    private function _construct_select_from_input($columns_to_select)
997
-    {
998
-        if (is_array($columns_to_select)) {
999
-            $select_sql_array = array();
1000
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1001
-                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1002
-                    throw new EE_Error(
1003
-                        sprintf(
1004
-                            __(
1005
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1006
-                                "event_espresso"
1007
-                            ),
1008
-                            $selection_and_datatype,
1009
-                            $alias
1010
-                        )
1011
-                    );
1012
-                }
1013
-                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1014
-                    throw new EE_Error(
1015
-                        sprintf(
1016
-                            __(
1017
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1018
-                                "event_espresso"
1019
-                            ),
1020
-                            $selection_and_datatype[1],
1021
-                            $selection_and_datatype[0],
1022
-                            $alias,
1023
-                            implode(",", $this->_valid_wpdb_data_types)
1024
-                        )
1025
-                    );
1026
-                }
1027
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1028
-            }
1029
-            $columns_to_select_string = implode(", ", $select_sql_array);
1030
-        } else {
1031
-            $columns_to_select_string = $columns_to_select;
1032
-        }
1033
-        return $columns_to_select_string;
1034
-    }
1035
-
1036
-
1037
-
1038
-    /**
1039
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1040
-     *
1041
-     * @return string
1042
-     * @throws \EE_Error
1043
-     */
1044
-    public function primary_key_name()
1045
-    {
1046
-        return $this->get_primary_key_field()->get_name();
1047
-    }
1048
-
1049
-
1050
-
1051
-    /**
1052
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1053
-     * If there is no primary key on this model, $id is treated as primary key string
1054
-     *
1055
-     * @param mixed $id int or string, depending on the type of the model's primary key
1056
-     * @return EE_Base_Class
1057
-     */
1058
-    public function get_one_by_ID($id)
1059
-    {
1060
-        if ($this->get_from_entity_map($id)) {
1061
-            return $this->get_from_entity_map($id);
1062
-        }
1063
-        return $this->get_one(
1064
-            $this->alter_query_params_to_restrict_by_ID(
1065
-                $id,
1066
-                array('default_where_conditions' => 'minimum')
1067
-            )
1068
-        );
1069
-    }
1070
-
1071
-
1072
-
1073
-    /**
1074
-     * Alters query parameters to only get items with this ID are returned.
1075
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1076
-     * or could just be a simple primary key ID
1077
-     *
1078
-     * @param int   $id
1079
-     * @param array $query_params
1080
-     * @return array of normal query params, @see EEM_Base::get_all
1081
-     * @throws \EE_Error
1082
-     */
1083
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1084
-    {
1085
-        if ( ! isset($query_params[0])) {
1086
-            $query_params[0] = array();
1087
-        }
1088
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1089
-        if ($conditions_from_id === null) {
1090
-            $query_params[0][$this->primary_key_name()] = $id;
1091
-        } else {
1092
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1093
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1094
-        }
1095
-        return $query_params;
1096
-    }
1097
-
1098
-
1099
-
1100
-    /**
1101
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1102
-     * array. If no item is found, null is returned.
1103
-     *
1104
-     * @param array $query_params like EEM_Base's $query_params variable.
1105
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1106
-     * @throws \EE_Error
1107
-     */
1108
-    public function get_one($query_params = array())
1109
-    {
1110
-        if ( ! is_array($query_params)) {
1111
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1112
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1113
-                    gettype($query_params)), '4.6.0');
1114
-            $query_params = array();
1115
-        }
1116
-        $query_params['limit'] = 1;
1117
-        $items = $this->get_all($query_params);
1118
-        if (empty($items)) {
1119
-            return null;
1120
-        } else {
1121
-            return array_shift($items);
1122
-        }
1123
-    }
1124
-
1125
-
1126
-
1127
-    /**
1128
-     * Returns the next x number of items in sequence from the given value as
1129
-     * found in the database matching the given query conditions.
1130
-     *
1131
-     * @param mixed $current_field_value    Value used for the reference point.
1132
-     * @param null  $field_to_order_by      What field is used for the
1133
-     *                                      reference point.
1134
-     * @param int   $limit                  How many to return.
1135
-     * @param array $query_params           Extra conditions on the query.
1136
-     * @param null  $columns_to_select      If left null, then an array of
1137
-     *                                      EE_Base_Class objects is returned,
1138
-     *                                      otherwise you can indicate just the
1139
-     *                                      columns you want returned.
1140
-     * @return EE_Base_Class[]|array
1141
-     * @throws \EE_Error
1142
-     */
1143
-    public function next_x(
1144
-        $current_field_value,
1145
-        $field_to_order_by = null,
1146
-        $limit = 1,
1147
-        $query_params = array(),
1148
-        $columns_to_select = null
1149
-    ) {
1150
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1151
-            $columns_to_select);
1152
-    }
1153
-
1154
-
1155
-
1156
-    /**
1157
-     * Returns the previous x number of items in sequence from the given value
1158
-     * as found in the database matching the given query conditions.
1159
-     *
1160
-     * @param mixed $current_field_value    Value used for the reference point.
1161
-     * @param null  $field_to_order_by      What field is used for the
1162
-     *                                      reference point.
1163
-     * @param int   $limit                  How many to return.
1164
-     * @param array $query_params           Extra conditions on the query.
1165
-     * @param null  $columns_to_select      If left null, then an array of
1166
-     *                                      EE_Base_Class objects is returned,
1167
-     *                                      otherwise you can indicate just the
1168
-     *                                      columns you want returned.
1169
-     * @return EE_Base_Class[]|array
1170
-     * @throws \EE_Error
1171
-     */
1172
-    public function previous_x(
1173
-        $current_field_value,
1174
-        $field_to_order_by = null,
1175
-        $limit = 1,
1176
-        $query_params = array(),
1177
-        $columns_to_select = null
1178
-    ) {
1179
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1180
-            $columns_to_select);
1181
-    }
1182
-
1183
-
1184
-
1185
-    /**
1186
-     * Returns the next item in sequence from the given value as found in the
1187
-     * database matching the given query conditions.
1188
-     *
1189
-     * @param mixed $current_field_value    Value used for the reference point.
1190
-     * @param null  $field_to_order_by      What field is used for the
1191
-     *                                      reference point.
1192
-     * @param array $query_params           Extra conditions on the query.
1193
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1194
-     *                                      object is returned, otherwise you
1195
-     *                                      can indicate just the columns you
1196
-     *                                      want and a single array indexed by
1197
-     *                                      the columns will be returned.
1198
-     * @return EE_Base_Class|null|array()
1199
-     * @throws \EE_Error
1200
-     */
1201
-    public function next(
1202
-        $current_field_value,
1203
-        $field_to_order_by = null,
1204
-        $query_params = array(),
1205
-        $columns_to_select = null
1206
-    ) {
1207
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1208
-            $columns_to_select);
1209
-        return empty($results) ? null : reset($results);
1210
-    }
1211
-
1212
-
1213
-
1214
-    /**
1215
-     * Returns the previous item in sequence from the given value as found in
1216
-     * the database matching the given query conditions.
1217
-     *
1218
-     * @param mixed $current_field_value    Value used for the reference point.
1219
-     * @param null  $field_to_order_by      What field is used for the
1220
-     *                                      reference point.
1221
-     * @param array $query_params           Extra conditions on the query.
1222
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1223
-     *                                      object is returned, otherwise you
1224
-     *                                      can indicate just the columns you
1225
-     *                                      want and a single array indexed by
1226
-     *                                      the columns will be returned.
1227
-     * @return EE_Base_Class|null|array()
1228
-     * @throws EE_Error
1229
-     */
1230
-    public function previous(
1231
-        $current_field_value,
1232
-        $field_to_order_by = null,
1233
-        $query_params = array(),
1234
-        $columns_to_select = null
1235
-    ) {
1236
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1237
-            $columns_to_select);
1238
-        return empty($results) ? null : reset($results);
1239
-    }
1240
-
1241
-
1242
-
1243
-    /**
1244
-     * Returns the a consecutive number of items in sequence from the given
1245
-     * value as found in the database matching the given query conditions.
1246
-     *
1247
-     * @param mixed  $current_field_value   Value used for the reference point.
1248
-     * @param string $operand               What operand is used for the sequence.
1249
-     * @param string $field_to_order_by     What field is used for the reference point.
1250
-     * @param int    $limit                 How many to return.
1251
-     * @param array  $query_params          Extra conditions on the query.
1252
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1253
-     *                                      otherwise you can indicate just the columns you want returned.
1254
-     * @return EE_Base_Class[]|array
1255
-     * @throws EE_Error
1256
-     */
1257
-    protected function _get_consecutive(
1258
-        $current_field_value,
1259
-        $operand = '>',
1260
-        $field_to_order_by = null,
1261
-        $limit = 1,
1262
-        $query_params = array(),
1263
-        $columns_to_select = null
1264
-    ) {
1265
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1266
-        if (empty($field_to_order_by)) {
1267
-            if ($this->has_primary_key_field()) {
1268
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1269
-            } else {
1270
-                if (WP_DEBUG) {
1271
-                    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).',
1272
-                        'event_espresso'));
1273
-                }
1274
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1275
-                return array();
1276
-            }
1277
-        }
1278
-        if ( ! is_array($query_params)) {
1279
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1280
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1281
-                    gettype($query_params)), '4.6.0');
1282
-            $query_params = array();
1283
-        }
1284
-        //let's add the where query param for consecutive look up.
1285
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1286
-        $query_params['limit'] = $limit;
1287
-        //set direction
1288
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1289
-        $query_params['order_by'] = $operand === '>'
1290
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1291
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1292
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1293
-        if (empty($columns_to_select)) {
1294
-            return $this->get_all($query_params);
1295
-        } else {
1296
-            //getting just the fields
1297
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1298
-        }
1299
-    }
1300
-
1301
-
1302
-
1303
-    /**
1304
-     * This sets the _timezone property after model object has been instantiated.
1305
-     *
1306
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1307
-     */
1308
-    public function set_timezone($timezone)
1309
-    {
1310
-        if ($timezone !== null) {
1311
-            $this->_timezone = $timezone;
1312
-        }
1313
-        //note we need to loop through relations and set the timezone on those objects as well.
1314
-        foreach ($this->_model_relations as $relation) {
1315
-            $relation->set_timezone($timezone);
1316
-        }
1317
-        //and finally we do the same for any datetime fields
1318
-        foreach ($this->_fields as $field) {
1319
-            if ($field instanceof EE_Datetime_Field) {
1320
-                $field->set_timezone($timezone);
1321
-            }
1322
-        }
1323
-    }
1324
-
1325
-
1326
-
1327
-    /**
1328
-     * This just returns whatever is set for the current timezone.
1329
-     *
1330
-     * @access public
1331
-     * @return string
1332
-     */
1333
-    public function get_timezone()
1334
-    {
1335
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1336
-        if (empty($this->_timezone)) {
1337
-            foreach ($this->_fields as $field) {
1338
-                if ($field instanceof EE_Datetime_Field) {
1339
-                    $this->set_timezone($field->get_timezone());
1340
-                    break;
1341
-                }
1342
-            }
1343
-        }
1344
-        //if timezone STILL empty then return the default timezone for the site.
1345
-        if (empty($this->_timezone)) {
1346
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1347
-        }
1348
-        return $this->_timezone;
1349
-    }
1350
-
1351
-
1352
-
1353
-    /**
1354
-     * This returns the date formats set for the given field name and also ensures that
1355
-     * $this->_timezone property is set correctly.
1356
-     *
1357
-     * @since 4.6.x
1358
-     * @param string $field_name The name of the field the formats are being retrieved for.
1359
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1360
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1361
-     * @return array formats in an array with the date format first, and the time format last.
1362
-     */
1363
-    public function get_formats_for($field_name, $pretty = false)
1364
-    {
1365
-        $field_settings = $this->field_settings_for($field_name);
1366
-        //if not a valid EE_Datetime_Field then throw error
1367
-        if ( ! $field_settings instanceof EE_Datetime_Field) {
1368
-            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.',
1369
-                'event_espresso'), $field_name));
1370
-        }
1371
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1372
-        //the field.
1373
-        $this->_timezone = $field_settings->get_timezone();
1374
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1375
-    }
1376
-
1377
-
1378
-
1379
-    /**
1380
-     * This returns the current time in a format setup for a query on this model.
1381
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1382
-     * it will return:
1383
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1384
-     *  NOW
1385
-     *  - or a unix timestamp (equivalent to time())
1386
-     *
1387
-     * @since 4.6.x
1388
-     * @param string $field_name       The field the current time is needed for.
1389
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1390
-     *                                 formatted string matching the set format for the field in the set timezone will
1391
-     *                                 be returned.
1392
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1393
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1394
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1395
-     *                                 exception is triggered.
1396
-     */
1397
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1398
-    {
1399
-        $formats = $this->get_formats_for($field_name);
1400
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1401
-        if ($timestamp) {
1402
-            return $DateTime->format('U');
1403
-        }
1404
-        //not returning timestamp, so return formatted string in timezone.
1405
-        switch ($what) {
1406
-            case 'time' :
1407
-                return $DateTime->format($formats[1]);
1408
-                break;
1409
-            case 'date' :
1410
-                return $DateTime->format($formats[0]);
1411
-                break;
1412
-            default :
1413
-                return $DateTime->format(implode(' ', $formats));
1414
-                break;
1415
-        }
1416
-    }
1417
-
1418
-
1419
-
1420
-    /**
1421
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1422
-     * for the model are.  Returns a DateTime object.
1423
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1424
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1425
-     * ignored.
1426
-     *
1427
-     * @param string $field_name      The field being setup.
1428
-     * @param string $timestring      The date time string being used.
1429
-     * @param string $incoming_format The format for the time string.
1430
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1431
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1432
-     *                                format is
1433
-     *                                'U', this is ignored.
1434
-     * @return DateTime
1435
-     * @throws \EE_Error
1436
-     */
1437
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1438
-    {
1439
-        //just using this to ensure the timezone is set correctly internally
1440
-        $this->get_formats_for($field_name);
1441
-        //load EEH_DTT_Helper
1442
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1443
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1444
-        return $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone));
1445
-    }
1446
-
1447
-
1448
-
1449
-    /**
1450
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1451
-     *
1452
-     * @return EE_Table_Base[]
1453
-     */
1454
-    public function get_tables()
1455
-    {
1456
-        return $this->_tables;
1457
-    }
1458
-
1459
-
1460
-
1461
-    /**
1462
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1463
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1464
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1465
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1466
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1467
-     * model object with EVT_ID = 1
1468
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1469
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1470
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1471
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1472
-     * are not specified)
1473
-     *
1474
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1475
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1476
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1477
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1478
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1479
-     *                                         ID=34, we'd use this method as follows:
1480
-     *                                         EEM_Transaction::instance()->update(
1481
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1482
-     *                                         array(array('TXN_ID'=>34)));
1483
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1484
-     *                                         in client code into what's expected to be stored on each field. Eg,
1485
-     *                                         consider updating Question's QST_admin_label field is of type
1486
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1487
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1488
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1489
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1490
-     *                                         TRUE, it is assumed that you've already called
1491
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1492
-     *                                         malicious javascript. However, if
1493
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1494
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it, and every other field, before insertion. We provide this parameter because model objects perform their prepare_for_set function on all their values, and so don't need to be called again (and in many cases, shouldn't be called again. Eg: if we escape HTML characters in the prepare_for_set method...)
1495
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1496
-     *                                         in this model's entity map according to $fields_n_values that match
1497
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1498
-     *                                         by setting this to FALSE, but be aware that model objects being used
1499
-     *                                         could get out-of-sync with the database
1500
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1501
-     *             rows affected which *could* include 0 which DOES NOT mean the query was bad)
1502
-     * @throws \EE_Error
1503
-     */
1504
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1505
-    {
1506
-        if ( ! is_array($query_params)) {
1507
-            EE_Error::doing_it_wrong('EEM_Base::update',
1508
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1509
-                    gettype($query_params)), '4.6.0');
1510
-            $query_params = array();
1511
-        }
1512
-        /**
1513
-         * Action called before a model update call has been made.
1514
-         *
1515
-         * @param EEM_Base $model
1516
-         * @param array    $fields_n_values the updated fields and their new values
1517
-         * @param array    $query_params    @see EEM_Base::get_all()
1518
-         */
1519
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1520
-        /**
1521
-         * Filters the fields about to be updated given the query parameters. You can provide the
1522
-         * $query_params to $this->get_all() to find exactly which records will be updated
1523
-         *
1524
-         * @param array    $fields_n_values fields and their new values
1525
-         * @param EEM_Base $model           the model being queried
1526
-         * @param array    $query_params    see EEM_Base::get_all()
1527
-         */
1528
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1529
-            $query_params);
1530
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1531
-        //to do that, for each table, verify that it's PK isn't null.
1532
-        $tables = $this->get_tables();
1533
-        //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
1534
-        //NOTE: we should make this code more efficient by NOT querying twice
1535
-        //before the real update, but that needs to first go through ALPHA testing
1536
-        //as it's dangerous. says Mike August 8 2014
1537
-        //we want to make sure the default_where strategy is ignored
1538
-        $this->_ignore_where_strategy = true;
1539
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1540
-        foreach ($wpdb_select_results as $wpdb_result) {
1541
-            // type cast stdClass as array
1542
-            $wpdb_result = (array)$wpdb_result;
1543
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1544
-            if ($this->has_primary_key_field()) {
1545
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1546
-            } else {
1547
-                //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)
1548
-                $main_table_pk_value = null;
1549
-            }
1550
-            //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
1551
-            //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
1552
-            if (count($tables) > 1) {
1553
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1554
-                //in that table, and so we'll want to insert one
1555
-                foreach ($tables as $table_obj) {
1556
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1557
-                    //if there is no private key for this table on the results, it means there's no entry
1558
-                    //in this table, right? so insert a row in the current table, using any fields available
1559
-                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1560
-                            && $wpdb_result[$this_table_pk_column])
1561
-                    ) {
1562
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1563
-                            $main_table_pk_value);
1564
-                        //if we died here, report the error
1565
-                        if ( ! $success) {
1566
-                            return false;
1567
-                        }
1568
-                    }
1569
-                }
1570
-            }
32
+	//admin posty
33
+	//basic -> grants access to mine -> if they don't have it, select none
34
+	//*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
35
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
36
+	//*_published -> grants access to published -> if they dont have it, select non-published
37
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
38
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
39
+	//frontend posty
40
+	//by default has access to published
41
+	//basic -> grants access to mine that arent published, and all published
42
+	//*_others ->grants access to others that arent private, all mine
43
+	//*_private -> grants full access
44
+	//frontend non-posty
45
+	//like admin posty
46
+	//category-y
47
+	//assign -> grants access to join-table
48
+	//(delete, edit)
49
+	//payment-method-y
50
+	//for each registered payment method,
51
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
52
+	/**
53
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
54
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
55
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
56
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
57
+	 *
58
+	 * @var boolean
59
+	 */
60
+	private $_values_already_prepared_by_model_object = 0;
61
+
62
+	/**
63
+	 * when $_values_already_prepared_by_model_object equals this, we assume
64
+	 * the data is just like form input that needs to have the model fields'
65
+	 * prepare_for_set and prepare_for_use_in_db called on it
66
+	 */
67
+	const not_prepared_by_model_object = 0;
68
+
69
+	/**
70
+	 * when $_values_already_prepared_by_model_object equals this, we
71
+	 * assume this value is coming from a model object and doesn't need to have
72
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
73
+	 */
74
+	const prepared_by_model_object = 1;
75
+
76
+	/**
77
+	 * when $_values_already_prepared_by_model_object equals this, we assume
78
+	 * the values are already to be used in the database (ie no processing is done
79
+	 * on them by the model's fields)
80
+	 */
81
+	const prepared_for_use_in_db = 2;
82
+
83
+
84
+	protected $singular_item = 'Item';
85
+
86
+	protected $plural_item   = 'Items';
87
+
88
+	/**
89
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
90
+	 */
91
+	protected $_tables;
92
+
93
+	/**
94
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
95
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
96
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
97
+	 *
98
+	 * @var \EE_Model_Field_Base[] $_fields
99
+	 */
100
+	protected $_fields;
101
+
102
+	/**
103
+	 * array of different kinds of relations
104
+	 *
105
+	 * @var \EE_Model_Relation_Base[] $_model_relations
106
+	 */
107
+	protected $_model_relations;
108
+
109
+	/**
110
+	 * @var \EE_Index[] $_indexes
111
+	 */
112
+	protected $_indexes = array();
113
+
114
+	/**
115
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
116
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
117
+	 * by setting the same columns as used in these queries in the query yourself.
118
+	 *
119
+	 * @var EE_Default_Where_Conditions
120
+	 */
121
+	protected $_default_where_conditions_strategy;
122
+
123
+	/**
124
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
125
+	 * This is particularly useful when you want something between 'none' and 'default'
126
+	 *
127
+	 * @var EE_Default_Where_Conditions
128
+	 */
129
+	protected $_minimum_where_conditions_strategy;
130
+
131
+	/**
132
+	 * String describing how to find the "owner" of this model's objects.
133
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
134
+	 * But when there isn't, this indicates which related model, or transiently-related model,
135
+	 * has the foreign key to the wp_users table.
136
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
137
+	 * related to events, and events have a foreign key to wp_users.
138
+	 * On EEM_Transaction, this would be 'Transaction.Event'
139
+	 *
140
+	 * @var string
141
+	 */
142
+	protected $_model_chain_to_wp_user = '';
143
+
144
+	/**
145
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
146
+	 * don't need it (particularly CPT models)
147
+	 *
148
+	 * @var bool
149
+	 */
150
+	protected $_ignore_where_strategy = false;
151
+
152
+	/**
153
+	 * String used in caps relating to this model. Eg, if the caps relating to this
154
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
155
+	 *
156
+	 * @var string. If null it hasn't been initialized yet. If false then we
157
+	 * have indicated capabilities don't apply to this
158
+	 */
159
+	protected $_caps_slug = null;
160
+
161
+	/**
162
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
163
+	 * and next-level keys are capability names, and each's value is a
164
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
165
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
166
+	 * and then each capability in the corresponding sub-array that they're missing
167
+	 * adds the where conditions onto the query.
168
+	 *
169
+	 * @var array
170
+	 */
171
+	protected $_cap_restrictions = array(
172
+		self::caps_read       => array(),
173
+		self::caps_read_admin => array(),
174
+		self::caps_edit       => array(),
175
+		self::caps_delete     => array(),
176
+	);
177
+
178
+	/**
179
+	 * Array defining which cap restriction generators to use to create default
180
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
181
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
182
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
183
+	 * automatically set this to false (not just null).
184
+	 *
185
+	 * @var EE_Restriction_Generator_Base[]
186
+	 */
187
+	protected $_cap_restriction_generators = array();
188
+
189
+	/**
190
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
191
+	 */
192
+	const caps_read       = 'read';
193
+
194
+	const caps_read_admin = 'read_admin';
195
+
196
+	const caps_edit       = 'edit';
197
+
198
+	const caps_delete     = 'delete';
199
+
200
+	/**
201
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
202
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
203
+	 * maps to 'read' because when looking for relevant permissions we're going to use
204
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
205
+	 *
206
+	 * @var array
207
+	 */
208
+	protected $_cap_contexts_to_cap_action_map = array(
209
+		self::caps_read       => 'read',
210
+		self::caps_read_admin => 'read',
211
+		self::caps_edit       => 'edit',
212
+		self::caps_delete     => 'delete',
213
+	);
214
+
215
+	/**
216
+	 * Timezone
217
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
218
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
219
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
220
+	 * EE_Datetime_Field data type will have access to it.
221
+	 *
222
+	 * @var string
223
+	 */
224
+	protected $_timezone;
225
+
226
+
227
+	/**
228
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
229
+	 * multisite.
230
+	 *
231
+	 * @var int
232
+	 */
233
+	protected static $_model_query_blog_id;
234
+
235
+	/**
236
+	 * A copy of _fields, except the array keys are the model names pointed to by
237
+	 * the field
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cache_foreign_key_to_fields = array();
242
+
243
+	/**
244
+	 * Cached list of all the fields on the model, indexed by their name
245
+	 *
246
+	 * @var EE_Model_Field_Base[]
247
+	 */
248
+	private $_cached_fields = null;
249
+
250
+	/**
251
+	 * Cached list of all the fields on the model, except those that are
252
+	 * marked as only pertinent to the database
253
+	 *
254
+	 * @var EE_Model_Field_Base[]
255
+	 */
256
+	private $_cached_fields_non_db_only = null;
257
+
258
+	/**
259
+	 * A cached reference to the primary key for quick lookup
260
+	 *
261
+	 * @var EE_Model_Field_Base
262
+	 */
263
+	private $_primary_key_field = null;
264
+
265
+	/**
266
+	 * Flag indicating whether this model has a primary key or not
267
+	 *
268
+	 * @var boolean
269
+	 */
270
+	protected $_has_primary_key_field = null;
271
+
272
+	/**
273
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
274
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
275
+	 *
276
+	 * @var boolean
277
+	 */
278
+	protected $_wp_core_model = false;
279
+
280
+	/**
281
+	 *    List of valid operators that can be used for querying.
282
+	 * The keys are all operators we'll accept, the values are the real SQL
283
+	 * operators used
284
+	 *
285
+	 * @var array
286
+	 */
287
+	protected $_valid_operators = array(
288
+		'='           => '=',
289
+		'<='          => '<=',
290
+		'<'           => '<',
291
+		'>='          => '>=',
292
+		'>'           => '>',
293
+		'!='          => '!=',
294
+		'LIKE'        => 'LIKE',
295
+		'like'        => 'LIKE',
296
+		'NOT_LIKE'    => 'NOT LIKE',
297
+		'not_like'    => 'NOT LIKE',
298
+		'NOT LIKE'    => 'NOT LIKE',
299
+		'not like'    => 'NOT LIKE',
300
+		'IN'          => 'IN',
301
+		'in'          => 'IN',
302
+		'NOT_IN'      => 'NOT IN',
303
+		'not_in'      => 'NOT IN',
304
+		'NOT IN'      => 'NOT IN',
305
+		'not in'      => 'NOT IN',
306
+		'between'     => 'BETWEEN',
307
+		'BETWEEN'     => 'BETWEEN',
308
+		'IS_NOT_NULL' => 'IS NOT NULL',
309
+		'is_not_null' => 'IS NOT NULL',
310
+		'IS NOT NULL' => 'IS NOT NULL',
311
+		'is not null' => 'IS NOT NULL',
312
+		'IS_NULL'     => 'IS NULL',
313
+		'is_null'     => 'IS NULL',
314
+		'IS NULL'     => 'IS NULL',
315
+		'is null'     => 'IS NULL',
316
+		'REGEXP'      => 'REGEXP',
317
+		'regexp'      => 'REGEXP',
318
+		'NOT_REGEXP'  => 'NOT REGEXP',
319
+		'not_regexp'  => 'NOT REGEXP',
320
+		'NOT REGEXP'  => 'NOT REGEXP',
321
+		'not regexp'  => 'NOT REGEXP',
322
+	);
323
+
324
+	/**
325
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
326
+	 *
327
+	 * @var array
328
+	 */
329
+	protected $_in_style_operators = array('IN', 'NOT IN');
330
+
331
+	/**
332
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
333
+	 * '12-31-2012'"
334
+	 *
335
+	 * @var array
336
+	 */
337
+	protected $_between_style_operators = array('BETWEEN');
338
+
339
+	/**
340
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
341
+	 * on a join table.
342
+	 *
343
+	 * @var array
344
+	 */
345
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
346
+
347
+	/**
348
+	 * Allowed values for $query_params['order'] for ordering in queries
349
+	 *
350
+	 * @var array
351
+	 */
352
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
353
+
354
+	/**
355
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
356
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
357
+	 *
358
+	 * @var array
359
+	 */
360
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
361
+
362
+	/**
363
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
364
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
365
+	 *
366
+	 * @var array
367
+	 */
368
+	private $_allowed_query_params = array(
369
+		0,
370
+		'limit',
371
+		'order_by',
372
+		'group_by',
373
+		'having',
374
+		'force_join',
375
+		'order',
376
+		'on_join_limit',
377
+		'default_where_conditions',
378
+		'caps',
379
+	);
380
+
381
+	/**
382
+	 * All the data types that can be used in $wpdb->prepare statements.
383
+	 *
384
+	 * @var array
385
+	 */
386
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
387
+
388
+	/**
389
+	 *    EE_Registry Object
390
+	 *
391
+	 * @var    object
392
+	 * @access    protected
393
+	 */
394
+	protected $EE = null;
395
+
396
+
397
+	/**
398
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
399
+	 *
400
+	 * @var int
401
+	 */
402
+	protected $_show_next_x_db_queries = 0;
403
+
404
+	/**
405
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
406
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
407
+	 *
408
+	 * @var array
409
+	 */
410
+	protected $_custom_selections = array();
411
+
412
+	/**
413
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
414
+	 * caches every model object we've fetched from the DB on this request
415
+	 *
416
+	 * @var array
417
+	 */
418
+	protected $_entity_map;
419
+
420
+	/**
421
+	 * constant used to show EEM_Base has not yet verified the db on this http request
422
+	 */
423
+	const db_verified_none = 0;
424
+
425
+	/**
426
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
427
+	 * but not the addons' dbs
428
+	 */
429
+	const db_verified_core = 1;
430
+
431
+	/**
432
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
433
+	 * the EE core db too)
434
+	 */
435
+	const db_verified_addons = 2;
436
+
437
+	/**
438
+	 * indicates whether an EEM_Base child has already re-verified the DB
439
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
440
+	 * looking like EEM_Base::db_verified_*
441
+	 *
442
+	 * @var int - 0 = none, 1 = core, 2 = addons
443
+	 */
444
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
445
+
446
+
447
+
448
+	/**
449
+	 * About all child constructors:
450
+	 * they should define the _tables, _fields and _model_relations arrays.
451
+	 * Should ALWAYS be called after child constructor.
452
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
453
+	 * finalizes constructing all the object's attributes.
454
+	 * Generally, rather than requiring a child to code
455
+	 * $this->_tables = array(
456
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
457
+	 *        ...);
458
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
459
+	 * each EE_Table has a function to set the table's alias after the constructor, using
460
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
461
+	 * do something similar.
462
+	 *
463
+	 * @param null $timezone
464
+	 * @throws \EE_Error
465
+	 */
466
+	protected function __construct($timezone = null)
467
+	{
468
+		// check that the model has not been loaded too soon
469
+		if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
470
+			throw new EE_Error (
471
+				sprintf(
472
+					__('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.',
473
+						'event_espresso'),
474
+					get_class($this)
475
+				)
476
+			);
477
+		}
478
+		/**
479
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
480
+		 */
481
+		if (empty(EEM_Base::$_model_query_blog_id)) {
482
+			EEM_Base::set_model_query_blog_id();
483
+		}
484
+		/**
485
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
486
+		 * just use EE_Register_Model_Extension
487
+		 *
488
+		 * @var EE_Table_Base[] $_tables
489
+		 */
490
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
491
+		foreach ($this->_tables as $table_alias => $table_obj) {
492
+			/** @var $table_obj EE_Table_Base */
493
+			$table_obj->_construct_finalize_with_alias($table_alias);
494
+			if ($table_obj instanceof EE_Secondary_Table) {
495
+				/** @var $table_obj EE_Secondary_Table */
496
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
497
+			}
498
+		}
499
+		/**
500
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
501
+		 * EE_Register_Model_Extension
502
+		 *
503
+		 * @param EE_Model_Field_Base[] $_fields
504
+		 */
505
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
506
+		$this->_invalidate_field_caches();
507
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
508
+			if ( ! array_key_exists($table_alias, $this->_tables)) {
509
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
510
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
511
+			}
512
+			foreach ($fields_for_table as $field_name => $field_obj) {
513
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
514
+				//primary key field base has a slightly different _construct_finalize
515
+				/** @var $field_obj EE_Model_Field_Base */
516
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
517
+			}
518
+		}
519
+		// everything is related to Extra_Meta
520
+		if (get_class($this) !== 'EEM_Extra_Meta') {
521
+			//make extra meta related to everything, but don't block deleting things just
522
+			//because they have related extra meta info. For now just orphan those extra meta
523
+			//in the future we should automatically delete them
524
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
525
+		}
526
+		//and change logs
527
+		if (get_class($this) !== 'EEM_Change_Log') {
528
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
529
+		}
530
+		/**
531
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
532
+		 * EE_Register_Model_Extension
533
+		 *
534
+		 * @param EE_Model_Relation_Base[] $_model_relations
535
+		 */
536
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
537
+			$this->_model_relations);
538
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
539
+			/** @var $relation_obj EE_Model_Relation_Base */
540
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
541
+		}
542
+		foreach ($this->_indexes as $index_name => $index_obj) {
543
+			/** @var $index_obj EE_Index */
544
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
545
+		}
546
+		$this->set_timezone($timezone);
547
+		//finalize default where condition strategy, or set default
548
+		if ( ! $this->_default_where_conditions_strategy) {
549
+			//nothing was set during child constructor, so set default
550
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
551
+		}
552
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
553
+		if ( ! $this->_minimum_where_conditions_strategy) {
554
+			//nothing was set during child constructor, so set default
555
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
556
+		}
557
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
558
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
559
+		//to indicate to NOT set it, set it to the logical default
560
+		if ($this->_caps_slug === null) {
561
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
562
+		}
563
+		//initialize the standard cap restriction generators if none were specified by the child constructor
564
+		if ($this->_cap_restriction_generators !== false) {
565
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
566
+				if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
567
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
568
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
569
+						new EE_Restriction_Generator_Protected(),
570
+						$cap_context,
571
+						$this
572
+					);
573
+				}
574
+			}
575
+		}
576
+		//if there are cap restriction generators, use them to make the default cap restrictions
577
+		if ($this->_cap_restriction_generators !== false) {
578
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
579
+				if ( ! $generator_object) {
580
+					continue;
581
+				}
582
+				if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
583
+					throw new EE_Error(
584
+						sprintf(
585
+							__('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.',
586
+								'event_espresso'),
587
+							$context,
588
+							$this->get_this_model_name()
589
+						)
590
+					);
591
+				}
592
+				$action = $this->cap_action_for_context($context);
593
+				if ( ! $generator_object->construction_finalized()) {
594
+					$generator_object->_construct_finalize($this, $action);
595
+				}
596
+			}
597
+		}
598
+		do_action('AHEE__' . get_class($this) . '__construct__end');
599
+	}
600
+
601
+
602
+
603
+	/**
604
+	 * Generates the cap restrictions for the given context, or if they were
605
+	 * already generated just gets what's cached
606
+	 *
607
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
608
+	 * @return EE_Default_Where_Conditions[]
609
+	 */
610
+	protected function _generate_cap_restrictions($context)
611
+	{
612
+		if (isset($this->_cap_restriction_generators[$context])
613
+			&& $this->_cap_restriction_generators[$context]
614
+			   instanceof
615
+			   EE_Restriction_Generator_Base
616
+		) {
617
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
618
+		} else {
619
+			return array();
620
+		}
621
+	}
622
+
623
+
624
+
625
+	/**
626
+	 * Used to set the $_model_query_blog_id static property.
627
+	 *
628
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
629
+	 *                      value for get_current_blog_id() will be used.
630
+	 */
631
+	public static function set_model_query_blog_id($blog_id = 0)
632
+	{
633
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
634
+	}
635
+
636
+
637
+
638
+	/**
639
+	 * Returns whatever is set as the internal $model_query_blog_id.
640
+	 *
641
+	 * @return int
642
+	 */
643
+	public static function get_model_query_blog_id()
644
+	{
645
+		return EEM_Base::$_model_query_blog_id;
646
+	}
647
+
648
+
649
+
650
+	/**
651
+	 *        This function is a singleton method used to instantiate the Espresso_model object
652
+	 *
653
+	 * @access public
654
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
655
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
656
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
657
+	 *                         timezone in the 'timezone_string' wp option)
658
+	 * @return static (as in the concrete child class)
659
+	 */
660
+	public static function instance($timezone = null)
661
+	{
662
+		// check if instance of Espresso_model already exists
663
+		if ( ! static::$_instance instanceof static) {
664
+			// instantiate Espresso_model
665
+			static::$_instance = new static($timezone);
666
+		}
667
+		//we might have a timezone set, let set_timezone decide what to do with it
668
+		static::$_instance->set_timezone($timezone);
669
+		// Espresso_model object
670
+		return static::$_instance;
671
+	}
672
+
673
+
674
+
675
+	/**
676
+	 * resets the model and returns it
677
+	 *
678
+	 * @param null | string $timezone
679
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
680
+	 * all its properties reset; if it wasn't instantiated, returns null)
681
+	 */
682
+	public static function reset($timezone = null)
683
+	{
684
+		if (static::$_instance instanceof EEM_Base) {
685
+			//let's try to NOT swap out the current instance for a new one
686
+			//because if someone has a reference to it, we can't remove their reference
687
+			//so it's best to keep using the same reference, but change the original object
688
+			//reset all its properties to their original values as defined in the class
689
+			$r = new ReflectionClass(get_class(static::$_instance));
690
+			$static_properties = $r->getStaticProperties();
691
+			foreach ($r->getDefaultProperties() as $property => $value) {
692
+				//don't set instance to null like it was originally,
693
+				//but it's static anyways, and we're ignoring static properties (for now at least)
694
+				if ( ! isset($static_properties[$property])) {
695
+					static::$_instance->{$property} = $value;
696
+				}
697
+			}
698
+			//and then directly call its constructor again, like we would if we
699
+			//were creating a new one
700
+			static::$_instance->__construct($timezone);
701
+			return self::instance();
702
+		}
703
+		return null;
704
+	}
705
+
706
+
707
+
708
+	/**
709
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
710
+	 *
711
+	 * @param  boolean $translated return localized strings or JUST the array.
712
+	 * @return array
713
+	 * @throws \EE_Error
714
+	 */
715
+	public function status_array($translated = false)
716
+	{
717
+		if ( ! array_key_exists('Status', $this->_model_relations)) {
718
+			return array();
719
+		}
720
+		$model_name = $this->get_this_model_name();
721
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
722
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
723
+		$status_array = array();
724
+		foreach ($stati as $status) {
725
+			$status_array[$status->ID()] = $status->get('STS_code');
726
+		}
727
+		return $translated
728
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
729
+			: $status_array;
730
+	}
731
+
732
+
733
+
734
+	/**
735
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
736
+	 *
737
+	 * @param array $query_params             {
738
+	 * @var array $0 (where) array {
739
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
740
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
741
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
742
+	 *                                        conditions based on related models (and even
743
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
744
+	 *                                        name. Eg,
745
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
746
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
747
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
748
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
749
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE Venue_CPT.ID = 12 Notice that automatically took care of joining Events to Venues (even when each of those models actually consisted of two tables). Also, you may chain the model relations together. Eg instead of just having "Venue.VNU_ID", you could have
750
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
751
+	 *                                        events are related to Registrations, which are related to Attendees). You
752
+	 *                                        can take it even further with
753
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
754
+	 *                                        (from the default of '='), change the value to an numerically-indexed
755
+	 *                                        array, where the first item in the list is the operator. eg: array(
756
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
757
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
758
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
759
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
760
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN (followed by an array with exactly 2 date strings), IS NULL, and IS NOT NULL Values can be a string, int, or float. They can also be arrays IFF the operator is IN. Also, values can actually be field names. To indicate the value is a field, simply provide a third array item (true) to the operator-value array like so: eg: array( 'DTT_reg_limit' => array('>', 'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold" Note: you can also use related model field names like you would any other field name. eg: array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could 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__>' => 345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp = 345678912...". Also, to negate an entire set of conditions, use 'NOT' as an array key. eg: array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND TXN_paid =23) Note: the 'glue' used to join each condition will continue to be what you last specified. IE, "AND"s by default, but if you had previously specified to use ORs to join, ORs will continue to be used. So, if you specify to use an "OR" to join conditions, it will continue to "stick" until you specify an AND. eg array('OR'=>array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >> "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND STS_ID='TIN'" They can be nested indefinitely. eg: 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 >> "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND PAY_timestamp != 1241234123" This can be applied to condition operators too, eg: array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
761
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
762
+	 *      limits of "23", "25,50", and array(23,42) are all valid would become SQL "...LIMIT 23", "...LIMIT 25,50",
763
+	 *      and "...LIMIT 23,42" respectively. Remember when you provide two numbers for the limit, the 1st number is
764
+	 *      the OFFSET, the 2nd is the LIMIT
765
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
766
+	 *      can do paging on one-to-many multi-table-joins. Send an array in the following format array('on_join_limit'
767
+	 *      => array( 'table_alias', array(1,2) ) ).
768
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
769
+	 *      values are either 'ASC' or 'DESC'. 'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
770
+	 *      SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date DESC..." respectively. Like the
771
+	 *      'where' conditions, these fields can be on related models. Eg
772
+	 *      'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is perfectly valid from any model related
773
+	 *      to 'Registration' (like Event, Attendee, Price, Datetime, etc.)
774
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
775
+	 *      'order' specifies whether to order the field specified in 'order_by' in ascending or descending order.
776
+	 *      Acceptable values are 'ASC' or 'DESC'. If, 'order_by' isn't used, but 'order' is, then it is assumed you
777
+	 *      want to order by the primary key. Eg,
778
+	 *      EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC'); //(will join
779
+	 *      with the Datetime model's table(s) and order by its field DTT_EVT_start) or
780
+	 *      EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make SQL "SELECT * FROM
781
+	 *      wp_esp_registration ORDER BY REG_ID ASC"
782
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
783
+	 *      'group_by'=>'VNU_ID', or 'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note: if no
784
+	 *      $group_by is specified, and a limit is set, automatically groups by the model's primary key (or combined
785
+	 *      primary keys). This avoids some weirdness that results when using limits, tons of joins, and no group by,
786
+	 *      see https://events.codebasehq.com/projects/event-espresso/tickets/9389
787
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
788
+	 *      grouped results (whereas WHERE conditions apply to the pre-grouped results)
789
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
790
+	 *      array where values are models to be joined in the query.Eg array('Attendee','Payment','Datetime'). You may
791
+	 *      join with transient models using period, eg "Registration.Transaction.Payment". You will probably only want
792
+	 *      to do this in hopes of increasing efficiency, as related models which belongs to the current model
793
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
794
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
795
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
796
+	 *      set this to 'none' to disable all default where conditions. Eg, usually soft-deleted objects are
797
+	 *      filtered-out if you want to include them, set this query param to 'none'. If you want to ONLY disable THIS
798
+	 *      model's default where conditions set it to 'other_models_only'. If you only want this model's default where
799
+	 *      conditions added to the query, use 'this_model_only'. If you want to use all default where conditions
800
+	 *      (default), set to 'all'.
801
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
802
+	 *      we just NOT apply any capabilities/permissions/restrictions and return everything? Or should we only show
803
+	 *      the current user items they should be able to view on the frontend, backend, edit, or delete? can be set to
804
+	 *      'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
805
+	 *                                        }
806
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
807
+	 *                          from EE_Base_Class[], use _get_all_wpdb_results()and make it public again. Array keys
808
+	 *                          are object IDs (if there is a primary key on the model. if not, numerically indexed)
809
+	 *                          Some full examples: get 10 transactions which have Scottish attendees:
810
+	 *                          EEM_Transaction::instance()->get_all( array( array(
811
+	 *                                        'OR'=>array(
812
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
813
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
814
+	 *                                        )
815
+	 *                                        ),
816
+	 *                                        'limit'=>10,
817
+	 *                                        'group_by'=>'TXN_ID'
818
+	 *                                        ));
819
+	 *                                        get all the answers to the question titled "shirt size" for event with id
820
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
821
+	 *                                        'Question.QST_display_text'=>'shirt size',
822
+	 *                                        'Registration.Event.EVT_ID'=>12
823
+	 *                                        ),
824
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
825
+	 *                                        ));
826
+	 * @throws \EE_Error
827
+	 */
828
+	public function get_all($query_params = array())
829
+	{
830
+		if (isset($query_params['limit'])
831
+			&& ! isset($query_params['group_by'])
832
+		) {
833
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
834
+		}
835
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
836
+	}
837
+
838
+
839
+
840
+	/**
841
+	 * Modifies the query parameters so we only get back model objects
842
+	 * that "belong" to the current user
843
+	 *
844
+	 * @param array $query_params @see EEM_Base::get_all()
845
+	 * @return array like EEM_Base::get_all
846
+	 */
847
+	public function alter_query_params_to_only_include_mine($query_params = array())
848
+	{
849
+		$wp_user_field_name = $this->wp_user_field_name();
850
+		if ($wp_user_field_name) {
851
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
852
+		}
853
+		return $query_params;
854
+	}
855
+
856
+
857
+
858
+	/**
859
+	 * Returns the name of the field's name that points to the WP_User table
860
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
861
+	 * foreign key to the WP_User table)
862
+	 *
863
+	 * @return string|boolean string on success, boolean false when there is no
864
+	 * foreign key to the WP_User table
865
+	 */
866
+	public function wp_user_field_name()
867
+	{
868
+		try {
869
+			if ( ! empty($this->_model_chain_to_wp_user)) {
870
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
871
+				$last_model_name = end($models_to_follow_to_wp_users);
872
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
873
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
874
+			} else {
875
+				$model_with_fk_to_wp_users = $this;
876
+				$model_chain_to_wp_user = '';
877
+			}
878
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
879
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
880
+		} catch (EE_Error $e) {
881
+			return false;
882
+		}
883
+	}
884
+
885
+
886
+
887
+	/**
888
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
889
+	 * (or transiently-related model) has a foreign key to the wp_users table;
890
+	 * useful for finding if model objects of this type are 'owned' by the current user.
891
+	 * This is an empty string when the foreign key is on this model and when it isn't,
892
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
893
+	 * (or transiently-related model)
894
+	 *
895
+	 * @return string
896
+	 */
897
+	public function model_chain_to_wp_user()
898
+	{
899
+		return $this->_model_chain_to_wp_user;
900
+	}
901
+
902
+
903
+
904
+	/**
905
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
906
+	 * like how registrations don't have a foreign key to wp_users, but the
907
+	 * events they are for are), or is unrelated to wp users.
908
+	 * generally available
909
+	 *
910
+	 * @return boolean
911
+	 */
912
+	public function is_owned()
913
+	{
914
+		if ($this->model_chain_to_wp_user()) {
915
+			return true;
916
+		} else {
917
+			try {
918
+				$this->get_foreign_key_to('WP_User');
919
+				return true;
920
+			} catch (EE_Error $e) {
921
+				return false;
922
+			}
923
+		}
924
+	}
925
+
926
+
927
+
928
+	/**
929
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
930
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
931
+	 * the model)
932
+	 *
933
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
934
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
935
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
936
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
937
+	 *                                  override this and set the select to "*", or a specific column name, like
938
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
939
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
940
+	 *                                  the aliases used to refer to this selection, and values are to be
941
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
942
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
943
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
944
+	 * @throws \EE_Error
945
+	 */
946
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
947
+	{
948
+		// remember the custom selections, if any, and type cast as array
949
+		// (unless $columns_to_select is an object, then just set as an empty array)
950
+		// Note: (array) 'some string' === array( 'some string' )
951
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
952
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
953
+		$select_expressions = $columns_to_select !== null
954
+			? $this->_construct_select_from_input($columns_to_select)
955
+			: $this->_construct_default_select_sql($model_query_info);
956
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
957
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
958
+	}
959
+
960
+
961
+
962
+	/**
963
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
964
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
965
+	 * take care of joins, field preparation etc.
966
+	 *
967
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
968
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
969
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
970
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
971
+	 *                                  override this and set the select to "*", or a specific column name, like
972
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
973
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
974
+	 *                                  the aliases used to refer to this selection, and values are to be
975
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
976
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
977
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
978
+	 * @throws \EE_Error
979
+	 */
980
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
981
+	{
982
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
983
+	}
984
+
985
+
986
+
987
+	/**
988
+	 * For creating a custom select statement
989
+	 *
990
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
991
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
992
+	 *                                 SQL, and 1=>is the datatype
993
+	 * @throws EE_Error
994
+	 * @return string
995
+	 */
996
+	private function _construct_select_from_input($columns_to_select)
997
+	{
998
+		if (is_array($columns_to_select)) {
999
+			$select_sql_array = array();
1000
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1001
+				if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1002
+					throw new EE_Error(
1003
+						sprintf(
1004
+							__(
1005
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1006
+								"event_espresso"
1007
+							),
1008
+							$selection_and_datatype,
1009
+							$alias
1010
+						)
1011
+					);
1012
+				}
1013
+				if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1014
+					throw new EE_Error(
1015
+						sprintf(
1016
+							__(
1017
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1018
+								"event_espresso"
1019
+							),
1020
+							$selection_and_datatype[1],
1021
+							$selection_and_datatype[0],
1022
+							$alias,
1023
+							implode(",", $this->_valid_wpdb_data_types)
1024
+						)
1025
+					);
1026
+				}
1027
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1028
+			}
1029
+			$columns_to_select_string = implode(", ", $select_sql_array);
1030
+		} else {
1031
+			$columns_to_select_string = $columns_to_select;
1032
+		}
1033
+		return $columns_to_select_string;
1034
+	}
1035
+
1036
+
1037
+
1038
+	/**
1039
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1040
+	 *
1041
+	 * @return string
1042
+	 * @throws \EE_Error
1043
+	 */
1044
+	public function primary_key_name()
1045
+	{
1046
+		return $this->get_primary_key_field()->get_name();
1047
+	}
1048
+
1049
+
1050
+
1051
+	/**
1052
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1053
+	 * If there is no primary key on this model, $id is treated as primary key string
1054
+	 *
1055
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1056
+	 * @return EE_Base_Class
1057
+	 */
1058
+	public function get_one_by_ID($id)
1059
+	{
1060
+		if ($this->get_from_entity_map($id)) {
1061
+			return $this->get_from_entity_map($id);
1062
+		}
1063
+		return $this->get_one(
1064
+			$this->alter_query_params_to_restrict_by_ID(
1065
+				$id,
1066
+				array('default_where_conditions' => 'minimum')
1067
+			)
1068
+		);
1069
+	}
1070
+
1071
+
1072
+
1073
+	/**
1074
+	 * Alters query parameters to only get items with this ID are returned.
1075
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1076
+	 * or could just be a simple primary key ID
1077
+	 *
1078
+	 * @param int   $id
1079
+	 * @param array $query_params
1080
+	 * @return array of normal query params, @see EEM_Base::get_all
1081
+	 * @throws \EE_Error
1082
+	 */
1083
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1084
+	{
1085
+		if ( ! isset($query_params[0])) {
1086
+			$query_params[0] = array();
1087
+		}
1088
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1089
+		if ($conditions_from_id === null) {
1090
+			$query_params[0][$this->primary_key_name()] = $id;
1091
+		} else {
1092
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1093
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1094
+		}
1095
+		return $query_params;
1096
+	}
1097
+
1098
+
1099
+
1100
+	/**
1101
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1102
+	 * array. If no item is found, null is returned.
1103
+	 *
1104
+	 * @param array $query_params like EEM_Base's $query_params variable.
1105
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1106
+	 * @throws \EE_Error
1107
+	 */
1108
+	public function get_one($query_params = array())
1109
+	{
1110
+		if ( ! is_array($query_params)) {
1111
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1112
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1113
+					gettype($query_params)), '4.6.0');
1114
+			$query_params = array();
1115
+		}
1116
+		$query_params['limit'] = 1;
1117
+		$items = $this->get_all($query_params);
1118
+		if (empty($items)) {
1119
+			return null;
1120
+		} else {
1121
+			return array_shift($items);
1122
+		}
1123
+	}
1124
+
1125
+
1126
+
1127
+	/**
1128
+	 * Returns the next x number of items in sequence from the given value as
1129
+	 * found in the database matching the given query conditions.
1130
+	 *
1131
+	 * @param mixed $current_field_value    Value used for the reference point.
1132
+	 * @param null  $field_to_order_by      What field is used for the
1133
+	 *                                      reference point.
1134
+	 * @param int   $limit                  How many to return.
1135
+	 * @param array $query_params           Extra conditions on the query.
1136
+	 * @param null  $columns_to_select      If left null, then an array of
1137
+	 *                                      EE_Base_Class objects is returned,
1138
+	 *                                      otherwise you can indicate just the
1139
+	 *                                      columns you want returned.
1140
+	 * @return EE_Base_Class[]|array
1141
+	 * @throws \EE_Error
1142
+	 */
1143
+	public function next_x(
1144
+		$current_field_value,
1145
+		$field_to_order_by = null,
1146
+		$limit = 1,
1147
+		$query_params = array(),
1148
+		$columns_to_select = null
1149
+	) {
1150
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1151
+			$columns_to_select);
1152
+	}
1153
+
1154
+
1155
+
1156
+	/**
1157
+	 * Returns the previous x number of items in sequence from the given value
1158
+	 * as found in the database matching the given query conditions.
1159
+	 *
1160
+	 * @param mixed $current_field_value    Value used for the reference point.
1161
+	 * @param null  $field_to_order_by      What field is used for the
1162
+	 *                                      reference point.
1163
+	 * @param int   $limit                  How many to return.
1164
+	 * @param array $query_params           Extra conditions on the query.
1165
+	 * @param null  $columns_to_select      If left null, then an array of
1166
+	 *                                      EE_Base_Class objects is returned,
1167
+	 *                                      otherwise you can indicate just the
1168
+	 *                                      columns you want returned.
1169
+	 * @return EE_Base_Class[]|array
1170
+	 * @throws \EE_Error
1171
+	 */
1172
+	public function previous_x(
1173
+		$current_field_value,
1174
+		$field_to_order_by = null,
1175
+		$limit = 1,
1176
+		$query_params = array(),
1177
+		$columns_to_select = null
1178
+	) {
1179
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1180
+			$columns_to_select);
1181
+	}
1182
+
1183
+
1184
+
1185
+	/**
1186
+	 * Returns the next item in sequence from the given value as found in the
1187
+	 * database matching the given query conditions.
1188
+	 *
1189
+	 * @param mixed $current_field_value    Value used for the reference point.
1190
+	 * @param null  $field_to_order_by      What field is used for the
1191
+	 *                                      reference point.
1192
+	 * @param array $query_params           Extra conditions on the query.
1193
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1194
+	 *                                      object is returned, otherwise you
1195
+	 *                                      can indicate just the columns you
1196
+	 *                                      want and a single array indexed by
1197
+	 *                                      the columns will be returned.
1198
+	 * @return EE_Base_Class|null|array()
1199
+	 * @throws \EE_Error
1200
+	 */
1201
+	public function next(
1202
+		$current_field_value,
1203
+		$field_to_order_by = null,
1204
+		$query_params = array(),
1205
+		$columns_to_select = null
1206
+	) {
1207
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1208
+			$columns_to_select);
1209
+		return empty($results) ? null : reset($results);
1210
+	}
1211
+
1212
+
1213
+
1214
+	/**
1215
+	 * Returns the previous item in sequence from the given value as found in
1216
+	 * the database matching the given query conditions.
1217
+	 *
1218
+	 * @param mixed $current_field_value    Value used for the reference point.
1219
+	 * @param null  $field_to_order_by      What field is used for the
1220
+	 *                                      reference point.
1221
+	 * @param array $query_params           Extra conditions on the query.
1222
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1223
+	 *                                      object is returned, otherwise you
1224
+	 *                                      can indicate just the columns you
1225
+	 *                                      want and a single array indexed by
1226
+	 *                                      the columns will be returned.
1227
+	 * @return EE_Base_Class|null|array()
1228
+	 * @throws EE_Error
1229
+	 */
1230
+	public function previous(
1231
+		$current_field_value,
1232
+		$field_to_order_by = null,
1233
+		$query_params = array(),
1234
+		$columns_to_select = null
1235
+	) {
1236
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1237
+			$columns_to_select);
1238
+		return empty($results) ? null : reset($results);
1239
+	}
1240
+
1241
+
1242
+
1243
+	/**
1244
+	 * Returns the a consecutive number of items in sequence from the given
1245
+	 * value as found in the database matching the given query conditions.
1246
+	 *
1247
+	 * @param mixed  $current_field_value   Value used for the reference point.
1248
+	 * @param string $operand               What operand is used for the sequence.
1249
+	 * @param string $field_to_order_by     What field is used for the reference point.
1250
+	 * @param int    $limit                 How many to return.
1251
+	 * @param array  $query_params          Extra conditions on the query.
1252
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1253
+	 *                                      otherwise you can indicate just the columns you want returned.
1254
+	 * @return EE_Base_Class[]|array
1255
+	 * @throws EE_Error
1256
+	 */
1257
+	protected function _get_consecutive(
1258
+		$current_field_value,
1259
+		$operand = '>',
1260
+		$field_to_order_by = null,
1261
+		$limit = 1,
1262
+		$query_params = array(),
1263
+		$columns_to_select = null
1264
+	) {
1265
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1266
+		if (empty($field_to_order_by)) {
1267
+			if ($this->has_primary_key_field()) {
1268
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1269
+			} else {
1270
+				if (WP_DEBUG) {
1271
+					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).',
1272
+						'event_espresso'));
1273
+				}
1274
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1275
+				return array();
1276
+			}
1277
+		}
1278
+		if ( ! is_array($query_params)) {
1279
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1280
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1281
+					gettype($query_params)), '4.6.0');
1282
+			$query_params = array();
1283
+		}
1284
+		//let's add the where query param for consecutive look up.
1285
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1286
+		$query_params['limit'] = $limit;
1287
+		//set direction
1288
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1289
+		$query_params['order_by'] = $operand === '>'
1290
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1291
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1292
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1293
+		if (empty($columns_to_select)) {
1294
+			return $this->get_all($query_params);
1295
+		} else {
1296
+			//getting just the fields
1297
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1298
+		}
1299
+	}
1300
+
1301
+
1302
+
1303
+	/**
1304
+	 * This sets the _timezone property after model object has been instantiated.
1305
+	 *
1306
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1307
+	 */
1308
+	public function set_timezone($timezone)
1309
+	{
1310
+		if ($timezone !== null) {
1311
+			$this->_timezone = $timezone;
1312
+		}
1313
+		//note we need to loop through relations and set the timezone on those objects as well.
1314
+		foreach ($this->_model_relations as $relation) {
1315
+			$relation->set_timezone($timezone);
1316
+		}
1317
+		//and finally we do the same for any datetime fields
1318
+		foreach ($this->_fields as $field) {
1319
+			if ($field instanceof EE_Datetime_Field) {
1320
+				$field->set_timezone($timezone);
1321
+			}
1322
+		}
1323
+	}
1324
+
1325
+
1326
+
1327
+	/**
1328
+	 * This just returns whatever is set for the current timezone.
1329
+	 *
1330
+	 * @access public
1331
+	 * @return string
1332
+	 */
1333
+	public function get_timezone()
1334
+	{
1335
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1336
+		if (empty($this->_timezone)) {
1337
+			foreach ($this->_fields as $field) {
1338
+				if ($field instanceof EE_Datetime_Field) {
1339
+					$this->set_timezone($field->get_timezone());
1340
+					break;
1341
+				}
1342
+			}
1343
+		}
1344
+		//if timezone STILL empty then return the default timezone for the site.
1345
+		if (empty($this->_timezone)) {
1346
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1347
+		}
1348
+		return $this->_timezone;
1349
+	}
1350
+
1351
+
1352
+
1353
+	/**
1354
+	 * This returns the date formats set for the given field name and also ensures that
1355
+	 * $this->_timezone property is set correctly.
1356
+	 *
1357
+	 * @since 4.6.x
1358
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1359
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1360
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1361
+	 * @return array formats in an array with the date format first, and the time format last.
1362
+	 */
1363
+	public function get_formats_for($field_name, $pretty = false)
1364
+	{
1365
+		$field_settings = $this->field_settings_for($field_name);
1366
+		//if not a valid EE_Datetime_Field then throw error
1367
+		if ( ! $field_settings instanceof EE_Datetime_Field) {
1368
+			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.',
1369
+				'event_espresso'), $field_name));
1370
+		}
1371
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1372
+		//the field.
1373
+		$this->_timezone = $field_settings->get_timezone();
1374
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1375
+	}
1376
+
1377
+
1378
+
1379
+	/**
1380
+	 * This returns the current time in a format setup for a query on this model.
1381
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1382
+	 * it will return:
1383
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1384
+	 *  NOW
1385
+	 *  - or a unix timestamp (equivalent to time())
1386
+	 *
1387
+	 * @since 4.6.x
1388
+	 * @param string $field_name       The field the current time is needed for.
1389
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1390
+	 *                                 formatted string matching the set format for the field in the set timezone will
1391
+	 *                                 be returned.
1392
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1393
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1394
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1395
+	 *                                 exception is triggered.
1396
+	 */
1397
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1398
+	{
1399
+		$formats = $this->get_formats_for($field_name);
1400
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1401
+		if ($timestamp) {
1402
+			return $DateTime->format('U');
1403
+		}
1404
+		//not returning timestamp, so return formatted string in timezone.
1405
+		switch ($what) {
1406
+			case 'time' :
1407
+				return $DateTime->format($formats[1]);
1408
+				break;
1409
+			case 'date' :
1410
+				return $DateTime->format($formats[0]);
1411
+				break;
1412
+			default :
1413
+				return $DateTime->format(implode(' ', $formats));
1414
+				break;
1415
+		}
1416
+	}
1417
+
1418
+
1419
+
1420
+	/**
1421
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1422
+	 * for the model are.  Returns a DateTime object.
1423
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1424
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1425
+	 * ignored.
1426
+	 *
1427
+	 * @param string $field_name      The field being setup.
1428
+	 * @param string $timestring      The date time string being used.
1429
+	 * @param string $incoming_format The format for the time string.
1430
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1431
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1432
+	 *                                format is
1433
+	 *                                'U', this is ignored.
1434
+	 * @return DateTime
1435
+	 * @throws \EE_Error
1436
+	 */
1437
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1438
+	{
1439
+		//just using this to ensure the timezone is set correctly internally
1440
+		$this->get_formats_for($field_name);
1441
+		//load EEH_DTT_Helper
1442
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1443
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1444
+		return $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone));
1445
+	}
1446
+
1447
+
1448
+
1449
+	/**
1450
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1451
+	 *
1452
+	 * @return EE_Table_Base[]
1453
+	 */
1454
+	public function get_tables()
1455
+	{
1456
+		return $this->_tables;
1457
+	}
1458
+
1459
+
1460
+
1461
+	/**
1462
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1463
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1464
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1465
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1466
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1467
+	 * model object with EVT_ID = 1
1468
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1469
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1470
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1471
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1472
+	 * are not specified)
1473
+	 *
1474
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1475
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1476
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1477
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1478
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1479
+	 *                                         ID=34, we'd use this method as follows:
1480
+	 *                                         EEM_Transaction::instance()->update(
1481
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1482
+	 *                                         array(array('TXN_ID'=>34)));
1483
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1484
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1485
+	 *                                         consider updating Question's QST_admin_label field is of type
1486
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1487
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1488
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1489
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1490
+	 *                                         TRUE, it is assumed that you've already called
1491
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1492
+	 *                                         malicious javascript. However, if
1493
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1494
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it, and every other field, before insertion. We provide this parameter because model objects perform their prepare_for_set function on all their values, and so don't need to be called again (and in many cases, shouldn't be called again. Eg: if we escape HTML characters in the prepare_for_set method...)
1495
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1496
+	 *                                         in this model's entity map according to $fields_n_values that match
1497
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1498
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1499
+	 *                                         could get out-of-sync with the database
1500
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1501
+	 *             rows affected which *could* include 0 which DOES NOT mean the query was bad)
1502
+	 * @throws \EE_Error
1503
+	 */
1504
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1505
+	{
1506
+		if ( ! is_array($query_params)) {
1507
+			EE_Error::doing_it_wrong('EEM_Base::update',
1508
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1509
+					gettype($query_params)), '4.6.0');
1510
+			$query_params = array();
1511
+		}
1512
+		/**
1513
+		 * Action called before a model update call has been made.
1514
+		 *
1515
+		 * @param EEM_Base $model
1516
+		 * @param array    $fields_n_values the updated fields and their new values
1517
+		 * @param array    $query_params    @see EEM_Base::get_all()
1518
+		 */
1519
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1520
+		/**
1521
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1522
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1523
+		 *
1524
+		 * @param array    $fields_n_values fields and their new values
1525
+		 * @param EEM_Base $model           the model being queried
1526
+		 * @param array    $query_params    see EEM_Base::get_all()
1527
+		 */
1528
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1529
+			$query_params);
1530
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1531
+		//to do that, for each table, verify that it's PK isn't null.
1532
+		$tables = $this->get_tables();
1533
+		//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
1534
+		//NOTE: we should make this code more efficient by NOT querying twice
1535
+		//before the real update, but that needs to first go through ALPHA testing
1536
+		//as it's dangerous. says Mike August 8 2014
1537
+		//we want to make sure the default_where strategy is ignored
1538
+		$this->_ignore_where_strategy = true;
1539
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1540
+		foreach ($wpdb_select_results as $wpdb_result) {
1541
+			// type cast stdClass as array
1542
+			$wpdb_result = (array)$wpdb_result;
1543
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1544
+			if ($this->has_primary_key_field()) {
1545
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1546
+			} else {
1547
+				//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)
1548
+				$main_table_pk_value = null;
1549
+			}
1550
+			//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
1551
+			//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
1552
+			if (count($tables) > 1) {
1553
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1554
+				//in that table, and so we'll want to insert one
1555
+				foreach ($tables as $table_obj) {
1556
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1557
+					//if there is no private key for this table on the results, it means there's no entry
1558
+					//in this table, right? so insert a row in the current table, using any fields available
1559
+					if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1560
+							&& $wpdb_result[$this_table_pk_column])
1561
+					) {
1562
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1563
+							$main_table_pk_value);
1564
+						//if we died here, report the error
1565
+						if ( ! $success) {
1566
+							return false;
1567
+						}
1568
+					}
1569
+				}
1570
+			}
1571 1571
 //				//and now check that if we have cached any models by that ID on the model, that
1572 1572
 //				//they also get updated properly
1573 1573
 //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1574 1574
 //				if( $model_object ){
1575 1575
 //					foreach( $fields_n_values as $field => $value ){
1576 1576
 //						$model_object->set($field, $value);
1577
-            //let's make sure default_where strategy is followed now
1578
-            $this->_ignore_where_strategy = false;
1579
-        }
1580
-        //if we want to keep model objects in sync, AND
1581
-        //if this wasn't called from a model object (to update itself)
1582
-        //then we want to make sure we keep all the existing
1583
-        //model objects in sync with the db
1584
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1585
-            if ($this->has_primary_key_field()) {
1586
-                $model_objs_affected_ids = $this->get_col($query_params);
1587
-            } else {
1588
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1589
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1590
-                $model_objs_affected_ids = array();
1591
-                foreach ($models_affected_key_columns as $row) {
1592
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1593
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1594
-                }
1595
-            }
1596
-            if ( ! $model_objs_affected_ids) {
1597
-                //wait wait wait- if nothing was affected let's stop here
1598
-                return 0;
1599
-            }
1600
-            foreach ($model_objs_affected_ids as $id) {
1601
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1602
-                if ($model_obj_in_entity_map) {
1603
-                    foreach ($fields_n_values as $field => $new_value) {
1604
-                        $model_obj_in_entity_map->set($field, $new_value);
1605
-                    }
1606
-                }
1607
-            }
1608
-            //if there is a primary key on this model, we can now do a slight optimization
1609
-            if ($this->has_primary_key_field()) {
1610
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1611
-                $query_params = array(
1612
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1613
-                    'limit'                    => count($model_objs_affected_ids),
1614
-                    'default_where_conditions' => 'none',
1615
-                );
1616
-            }
1617
-        }
1618
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1619
-        $SQL = "UPDATE "
1620
-               . $model_query_info->get_full_join_sql()
1621
-               . " SET "
1622
-               . $this->_construct_update_sql($fields_n_values)
1623
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1624
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1625
-        /**
1626
-         * Action called after a model update call has been made.
1627
-         *
1628
-         * @param EEM_Base $model
1629
-         * @param array    $fields_n_values the updated fields and their new values
1630
-         * @param array    $query_params    @see EEM_Base::get_all()
1631
-         * @param int      $rows_affected
1632
-         */
1633
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1634
-        return $rows_affected;//how many supposedly got updated
1635
-    }
1636
-
1637
-
1638
-
1639
-    /**
1640
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1641
-     * are teh values of the field specified (or by default the primary key field)
1642
-     * that matched the query params. Note that you should pass the name of the
1643
-     * model FIELD, not the database table's column name.
1644
-     *
1645
-     * @param array  $query_params @see EEM_Base::get_all()
1646
-     * @param string $field_to_select
1647
-     * @return array just like $wpdb->get_col()
1648
-     * @throws \EE_Error
1649
-     */
1650
-    public function get_col($query_params = array(), $field_to_select = null)
1651
-    {
1652
-        if ($field_to_select) {
1653
-            $field = $this->field_settings_for($field_to_select);
1654
-        } elseif ($this->has_primary_key_field()) {
1655
-            $field = $this->get_primary_key_field();
1656
-        } else {
1657
-            //no primary key, just grab the first column
1658
-            $field = reset($this->field_settings());
1659
-        }
1660
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1661
-        $select_expressions = $field->get_qualified_column();
1662
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1663
-        return $this->_do_wpdb_query('get_col', array($SQL));
1664
-    }
1665
-
1666
-
1667
-
1668
-    /**
1669
-     * Returns a single column value for a single row from the database
1670
-     *
1671
-     * @param array  $query_params    @see EEM_Base::get_all()
1672
-     * @param string $field_to_select @see EEM_Base::get_col()
1673
-     * @return string
1674
-     * @throws \EE_Error
1675
-     */
1676
-    public function get_var($query_params = array(), $field_to_select = null)
1677
-    {
1678
-        $query_params['limit'] = 1;
1679
-        $col = $this->get_col($query_params, $field_to_select);
1680
-        if ( ! empty($col)) {
1681
-            return reset($col);
1682
-        } else {
1683
-            return null;
1684
-        }
1685
-    }
1686
-
1687
-
1688
-
1689
-    /**
1690
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1691
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1692
-     * injection, but currently no further filtering is done
1693
-     *
1694
-     * @global      $wpdb
1695
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1696
-     *                               be updated to in the DB
1697
-     * @return string of SQL
1698
-     * @throws \EE_Error
1699
-     */
1700
-    public function _construct_update_sql($fields_n_values)
1701
-    {
1702
-        /** @type WPDB $wpdb */
1703
-        global $wpdb;
1704
-        $cols_n_values = array();
1705
-        foreach ($fields_n_values as $field_name => $value) {
1706
-            $field_obj = $this->field_settings_for($field_name);
1707
-            //if the value is NULL, we want to assign the value to that.
1708
-            //wpdb->prepare doesn't really handle that properly
1709
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1710
-            $value_sql = $prepared_value === null ? 'NULL'
1711
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1712
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1713
-        }
1714
-        return implode(",", $cols_n_values);
1715
-    }
1716
-
1717
-
1718
-
1719
-    /**
1720
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1721
-     * Performs a HARD delete, meaning the database row should always be removed,
1722
-     * not just have a flag field on it switched
1723
-     * Wrapper for EEM_Base::delete_permanently()
1724
-     *
1725
-     * @param mixed $id
1726
-     * @return boolean whether the row got deleted or not
1727
-     * @throws \EE_Error
1728
-     */
1729
-    public function delete_permanently_by_ID($id)
1730
-    {
1731
-        return $this->delete_permanently(
1732
-            array(
1733
-                array($this->get_primary_key_field()->get_name() => $id),
1734
-                'limit' => 1,
1735
-            )
1736
-        );
1737
-    }
1738
-
1739
-
1740
-
1741
-    /**
1742
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1743
-     * Wrapper for EEM_Base::delete()
1744
-     *
1745
-     * @param mixed $id
1746
-     * @return boolean whether the row got deleted or not
1747
-     * @throws \EE_Error
1748
-     */
1749
-    public function delete_by_ID($id)
1750
-    {
1751
-        return $this->delete(
1752
-            array(
1753
-                array($this->get_primary_key_field()->get_name() => $id),
1754
-                'limit' => 1,
1755
-            )
1756
-        );
1757
-    }
1758
-
1759
-
1760
-
1761
-    /**
1762
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1763
-     * meaning if the model has a field that indicates its been "trashed" or
1764
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1765
-     *
1766
-     * @see EEM_Base::delete_permanently
1767
-     * @param array   $query_params
1768
-     * @param boolean $allow_blocking
1769
-     * @return int how many rows got deleted
1770
-     * @throws \EE_Error
1771
-     */
1772
-    public function delete($query_params, $allow_blocking = true)
1773
-    {
1774
-        return $this->delete_permanently($query_params, $allow_blocking);
1775
-    }
1776
-
1777
-
1778
-
1779
-    /**
1780
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1781
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1782
-     * as archived, not actually deleted
1783
-     *
1784
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1785
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1786
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1787
-     *                                deletes regardless of other objects which may depend on it. Its generally
1788
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1789
-     *                                DB
1790
-     * @return int how many rows got deleted
1791
-     * @throws \EE_Error
1792
-     */
1793
-    public function delete_permanently($query_params, $allow_blocking = true)
1794
-    {
1795
-        /**
1796
-         * Action called just before performing a real deletion query. You can use the
1797
-         * model and its $query_params to find exactly which items will be deleted
1798
-         *
1799
-         * @param EEM_Base $model
1800
-         * @param array    $query_params   @see EEM_Base::get_all()
1801
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1802
-         *                                 to block (prevent) this deletion
1803
-         */
1804
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1805
-        //some MySQL databases may be running safe mode, which may restrict
1806
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1807
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1808
-        //to delete them
1809
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1810
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1811
-        if ($deletion_where) {
1812
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1813
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1814
-            $table_aliases = array_keys($this->_tables);
1815
-            $SQL = "DELETE "
1816
-                   . implode(", ", $table_aliases)
1817
-                   . " FROM "
1818
-                   . $model_query_info->get_full_join_sql()
1819
-                   . " WHERE "
1820
-                   . $deletion_where;
1821
-            //		/echo "delete sql:$SQL";
1822
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1823
-        } else {
1824
-            $rows_deleted = 0;
1825
-        }
1826
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1827
-        if ($this->has_primary_key_field()) {
1828
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1829
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1830
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1831
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1832
-                }
1833
-            }
1834
-        }
1835
-        /**
1836
-         * Action called just after performing a real deletion query. Although at this point the
1837
-         * items should have been deleted
1838
-         *
1839
-         * @param EEM_Base $model
1840
-         * @param array    $query_params @see EEM_Base::get_all()
1841
-         * @param int      $rows_deleted
1842
-         */
1843
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1844
-        return $rows_deleted;//how many supposedly got deleted
1845
-    }
1846
-
1847
-
1848
-
1849
-    /**
1850
-     * Checks all the relations that throw error messages when there are blocking related objects
1851
-     * for related model objects. If there are any related model objects on those relations,
1852
-     * adds an EE_Error, and return true
1853
-     *
1854
-     * @param EE_Base_Class|int $this_model_obj_or_id
1855
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1856
-     *                                                 should be ignored when determining whether there are related
1857
-     *                                                 model objects which block this model object's deletion. Useful
1858
-     *                                                 if you know A is related to B and are considering deleting A,
1859
-     *                                                 but want to see if A has any other objects blocking its deletion
1860
-     *                                                 before removing the relation between A and B
1861
-     * @return boolean
1862
-     * @throws \EE_Error
1863
-     */
1864
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1865
-    {
1866
-        //first, if $ignore_this_model_obj was supplied, get its model
1867
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1868
-            $ignored_model = $ignore_this_model_obj->get_model();
1869
-        } else {
1870
-            $ignored_model = null;
1871
-        }
1872
-        //now check all the relations of $this_model_obj_or_id and see if there
1873
-        //are any related model objects blocking it?
1874
-        $is_blocked = false;
1875
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
1876
-            if ($relation_obj->block_delete_if_related_models_exist()) {
1877
-                //if $ignore_this_model_obj was supplied, then for the query
1878
-                //on that model needs to be told to ignore $ignore_this_model_obj
1879
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1880
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1881
-                        array(
1882
-                            $ignored_model->get_primary_key_field()->get_name() => array(
1883
-                                '!=',
1884
-                                $ignore_this_model_obj->ID(),
1885
-                            ),
1886
-                        ),
1887
-                    ));
1888
-                } else {
1889
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1890
-                }
1891
-                if ($related_model_objects) {
1892
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1893
-                    $is_blocked = true;
1894
-                }
1895
-            }
1896
-        }
1897
-        return $is_blocked;
1898
-    }
1899
-
1900
-
1901
-
1902
-    /**
1903
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
1904
-     * well.
1905
-     *
1906
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1907
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
1908
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
1909
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
1910
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
1911
-     *                                      easily corrupt your DB
1912
-     * @throws EE_Error
1913
-     * @return string    everything that comes after the WHERE statement.
1914
-     */
1915
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
1916
-    {
1917
-        if ($this->has_primary_key_field()) {
1918
-            $primary_table = $this->_get_main_table();
1919
-            $other_tables = $this->_get_other_tables();
1920
-            $deletes = $query = array();
1921
-            foreach ($objects_for_deletion as $delete_object) {
1922
-                //before we mark this object for deletion,
1923
-                //make sure there's no related objects blocking its deletion (if we're checking)
1924
-                if (
1925
-                    $allow_blocking
1926
-                    && $this->delete_is_blocked_by_related_models(
1927
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
1928
-                    )
1929
-                ) {
1930
-                    continue;
1931
-                }
1932
-                //primary table deletes
1933
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
1934
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
1935
-                }
1936
-                //other tables
1937
-                if ( ! empty($other_tables)) {
1938
-                    foreach ($other_tables as $ot) {
1939
-                        //first check if we've got the foreign key column here.
1940
-                        if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
1941
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
1942
-                        }
1943
-                        // wait! it's entirely possible that we'll have a the primary key
1944
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
1945
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
1946
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1947
-                        }
1948
-                        // finally, it is possible that the fk for this table is found
1949
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
1950
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
1951
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1952
-                        }
1953
-                    }
1954
-                }
1955
-            }
1956
-            //we should have deletes now, so let's just go through and setup the where statement
1957
-            foreach ($deletes as $column => $values) {
1958
-                //make sure we have unique $values;
1959
-                $values = array_unique($values);
1960
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
1961
-            }
1962
-            return ! empty($query) ? implode(' AND ', $query) : '';
1963
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
1964
-            $ways_to_identify_a_row = array();
1965
-            $fields = $this->get_combined_primary_key_fields();
1966
-            //note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
1967
-            foreach ($objects_for_deletion as $delete_object) {
1968
-                $values_for_each_cpk_for_a_row = array();
1969
-                foreach ($fields as $cpk_field) {
1970
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
1971
-                        $values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
1972
-                                                           . "="
1973
-                                                           . $delete_object[$cpk_field->get_qualified_column()];
1974
-                    }
1975
-                }
1976
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
1977
-            }
1978
-            return implode(" OR ", $ways_to_identify_a_row);
1979
-        } else {
1980
-            //so there's no primary key and no combined key...
1981
-            //sorry, can't help you
1982
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
1983
-                "event_espresso"), get_class($this)));
1984
-        }
1985
-    }
1986
-
1987
-
1988
-
1989
-    /**
1990
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
1991
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
1992
-     * column
1993
-     *
1994
-     * @param array  $query_params   like EEM_Base::get_all's
1995
-     * @param string $field_to_count field on model to count by (not column name)
1996
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
1997
-     *                               that by the setting $distinct to TRUE;
1998
-     * @return int
1999
-     * @throws \EE_Error
2000
-     */
2001
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2002
-    {
2003
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2004
-        if ($field_to_count) {
2005
-            $field_obj = $this->field_settings_for($field_to_count);
2006
-            $column_to_count = $field_obj->get_qualified_column();
2007
-        } elseif ($this->has_primary_key_field()) {
2008
-            $pk_field_obj = $this->get_primary_key_field();
2009
-            $column_to_count = $pk_field_obj->get_qualified_column();
2010
-        } else {
2011
-            //there's no primary key
2012
-            //if we're counting distinct items, and there's no primary key,
2013
-            //we need to list out the columns for distinction;
2014
-            //otherwise we can just use star
2015
-            if ($distinct) {
2016
-                $columns_to_use = array();
2017
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2018
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2019
-                }
2020
-                $column_to_count = implode(',', $columns_to_use);
2021
-            } else {
2022
-                $column_to_count = '*';
2023
-            }
2024
-        }
2025
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2026
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2027
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2028
-    }
2029
-
2030
-
2031
-
2032
-    /**
2033
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2034
-     *
2035
-     * @param array  $query_params like EEM_Base::get_all
2036
-     * @param string $field_to_sum name of field (array key in $_fields array)
2037
-     * @return float
2038
-     * @throws \EE_Error
2039
-     */
2040
-    public function sum($query_params, $field_to_sum = null)
2041
-    {
2042
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2043
-        if ($field_to_sum) {
2044
-            $field_obj = $this->field_settings_for($field_to_sum);
2045
-        } else {
2046
-            $field_obj = $this->get_primary_key_field();
2047
-        }
2048
-        $column_to_count = $field_obj->get_qualified_column();
2049
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2050
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2051
-        $data_type = $field_obj->get_wpdb_data_type();
2052
-        if ($data_type === '%d' || $data_type === '%s') {
2053
-            return (float)$return_value;
2054
-        } else {//must be %f
2055
-            return (float)$return_value;
2056
-        }
2057
-    }
2058
-
2059
-
2060
-
2061
-    /**
2062
-     * Just calls the specified method on $wpdb with the given arguments
2063
-     * Consolidates a little extra error handling code
2064
-     *
2065
-     * @param string $wpdb_method
2066
-     * @param array  $arguments_to_provide
2067
-     * @throws EE_Error
2068
-     * @global wpdb  $wpdb
2069
-     * @return mixed
2070
-     */
2071
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2072
-    {
2073
-        //if we're in maintenance mode level 2, DON'T run any queries
2074
-        //because level 2 indicates the database needs updating and
2075
-        //is probably out of sync with the code
2076
-        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2077
-            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.",
2078
-                "event_espresso")));
2079
-        }
2080
-        /** @type WPDB $wpdb */
2081
-        global $wpdb;
2082
-        if ( ! method_exists($wpdb, $wpdb_method)) {
2083
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2084
-                'event_espresso'), $wpdb_method));
2085
-        }
2086
-        if (WP_DEBUG) {
2087
-            $old_show_errors_value = $wpdb->show_errors;
2088
-            $wpdb->show_errors(false);
2089
-        }
2090
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2091
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2092
-        if (WP_DEBUG) {
2093
-            $wpdb->show_errors($old_show_errors_value);
2094
-            if ( ! empty($wpdb->last_error)) {
2095
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2096
-            } elseif ($result === false) {
2097
-                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"',
2098
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2099
-            }
2100
-        } elseif ($result === false) {
2101
-            EE_Error::add_error(
2102
-                sprintf(
2103
-                    __('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"',
2104
-                        'event_espresso'),
2105
-                    $wpdb_method,
2106
-                    var_export($arguments_to_provide, true),
2107
-                    $wpdb->last_error
2108
-                ),
2109
-                __FILE__,
2110
-                __FUNCTION__,
2111
-                __LINE__
2112
-            );
2113
-        }
2114
-        return $result;
2115
-    }
2116
-
2117
-
2118
-
2119
-    /**
2120
-     * Attempts to run the indicated WPDB method with the provided arguments,
2121
-     * and if there's an error tries to verify the DB is correct. Uses
2122
-     * the static property EEM_Base::$_db_verification_level to determine whether
2123
-     * we should try to fix the EE core db, the addons, or just give up
2124
-     *
2125
-     * @param string $wpdb_method
2126
-     * @param array  $arguments_to_provide
2127
-     * @return mixed
2128
-     */
2129
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2130
-    {
2131
-        /** @type WPDB $wpdb */
2132
-        global $wpdb;
2133
-        $wpdb->last_error = null;
2134
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2135
-        // was there an error running the query? but we don't care on new activations
2136
-        // (we're going to setup the DB anyway on new activations)
2137
-        if (($result === false || ! empty($wpdb->last_error))
2138
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2139
-        ) {
2140
-            switch (EEM_Base::$_db_verification_level) {
2141
-                case EEM_Base::db_verified_none :
2142
-                    // let's double-check core's DB
2143
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2144
-                    break;
2145
-                case EEM_Base::db_verified_core :
2146
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2147
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2148
-                    break;
2149
-                case EEM_Base::db_verified_addons :
2150
-                    // ummmm... you in trouble
2151
-                    return $result;
2152
-                    break;
2153
-            }
2154
-            if ( ! empty($error_message)) {
2155
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2156
-                trigger_error($error_message);
2157
-            }
2158
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2159
-        }
2160
-        return $result;
2161
-    }
2162
-
2163
-
2164
-
2165
-    /**
2166
-     * Verifies the EE core database is up-to-date and records that we've done it on
2167
-     * EEM_Base::$_db_verification_level
2168
-     *
2169
-     * @param string $wpdb_method
2170
-     * @param array  $arguments_to_provide
2171
-     * @return string
2172
-     */
2173
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2174
-    {
2175
-        /** @type WPDB $wpdb */
2176
-        global $wpdb;
2177
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2178
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2179
-        $error_message = sprintf(
2180
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2181
-                'event_espresso'),
2182
-            $wpdb->last_error,
2183
-            $wpdb_method,
2184
-            json_encode($arguments_to_provide)
2185
-        );
2186
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2187
-        return $error_message;
2188
-    }
2189
-
2190
-
2191
-
2192
-    /**
2193
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2194
-     * EEM_Base::$_db_verification_level
2195
-     *
2196
-     * @param $wpdb_method
2197
-     * @param $arguments_to_provide
2198
-     * @return string
2199
-     */
2200
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2201
-    {
2202
-        /** @type WPDB $wpdb */
2203
-        global $wpdb;
2204
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2205
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2206
-        $error_message = sprintf(
2207
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2208
-                'event_espresso'),
2209
-            $wpdb->last_error,
2210
-            $wpdb_method,
2211
-            json_encode($arguments_to_provide)
2212
-        );
2213
-        EE_System::instance()->initialize_addons();
2214
-        return $error_message;
2215
-    }
2216
-
2217
-
2218
-
2219
-    /**
2220
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2221
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2222
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2223
-     * ..."
2224
-     *
2225
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2226
-     * @return string
2227
-     */
2228
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2229
-    {
2230
-        return " FROM " . $model_query_info->get_full_join_sql() .
2231
-               $model_query_info->get_where_sql() .
2232
-               $model_query_info->get_group_by_sql() .
2233
-               $model_query_info->get_having_sql() .
2234
-               $model_query_info->get_order_by_sql() .
2235
-               $model_query_info->get_limit_sql();
2236
-    }
2237
-
2238
-
2239
-
2240
-    /**
2241
-     * Set to easily debug the next X queries ran from this model.
2242
-     *
2243
-     * @param int $count
2244
-     */
2245
-    public function show_next_x_db_queries($count = 1)
2246
-    {
2247
-        $this->_show_next_x_db_queries = $count;
2248
-    }
2249
-
2250
-
2251
-
2252
-    /**
2253
-     * @param $sql_query
2254
-     */
2255
-    public function show_db_query_if_previously_requested($sql_query)
2256
-    {
2257
-        if ($this->_show_next_x_db_queries > 0) {
2258
-            echo $sql_query;
2259
-            $this->_show_next_x_db_queries--;
2260
-        }
2261
-    }
2262
-
2263
-
2264
-
2265
-    /**
2266
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2267
-     * There are the 3 cases:
2268
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2269
-     * $otherModelObject has no ID, it is first saved.
2270
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2271
-     * has no ID, it is first saved.
2272
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2273
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2274
-     * join table
2275
-     *
2276
-     * @param        EE_Base_Class                     /int $thisModelObject
2277
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2278
-     * @param string $relationName                     , key in EEM_Base::_relations
2279
-     *                                                 an attendee to a group, you also want to specify which role they
2280
-     *                                                 will have in that group. So you would use this parameter to
2281
-     *                                                 specify array('role-column-name'=>'role-id')
2282
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2283
-     *                                                 to for relation to methods that allow you to further specify
2284
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2285
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2286
-     *                                                 because these will be inserted in any new rows created as well.
2287
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2288
-     * @throws \EE_Error
2289
-     */
2290
-    public function add_relationship_to(
2291
-        $id_or_obj,
2292
-        $other_model_id_or_obj,
2293
-        $relationName,
2294
-        $extra_join_model_fields_n_values = array()
2295
-    ) {
2296
-        $relation_obj = $this->related_settings_for($relationName);
2297
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2298
-    }
2299
-
2300
-
2301
-
2302
-    /**
2303
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2304
-     * There are the 3 cases:
2305
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2306
-     * error
2307
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2308
-     * an error
2309
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2310
-     *
2311
-     * @param        EE_Base_Class /int $id_or_obj
2312
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2313
-     * @param string $relationName key in EEM_Base::_relations
2314
-     * @return boolean of success
2315
-     * @throws \EE_Error
2316
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2317
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2318
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2319
-     *                             because these will be inserted in any new rows created as well.
2320
-     */
2321
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2322
-    {
2323
-        $relation_obj = $this->related_settings_for($relationName);
2324
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2325
-    }
2326
-
2327
-
2328
-
2329
-    /**
2330
-     * @param mixed           $id_or_obj
2331
-     * @param string          $relationName
2332
-     * @param array           $where_query_params
2333
-     * @param EE_Base_Class[] objects to which relations were removed
2334
-     * @return \EE_Base_Class[]
2335
-     * @throws \EE_Error
2336
-     */
2337
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2338
-    {
2339
-        $relation_obj = $this->related_settings_for($relationName);
2340
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2341
-    }
2342
-
2343
-
2344
-
2345
-    /**
2346
-     * Gets all the related items of the specified $model_name, using $query_params.
2347
-     * Note: by default, we remove the "default query params"
2348
-     * because we want to get even deleted items etc.
2349
-     *
2350
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2351
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2352
-     * @param array  $query_params like EEM_Base::get_all
2353
-     * @return EE_Base_Class[]
2354
-     * @throws \EE_Error
2355
-     */
2356
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2357
-    {
2358
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2359
-        $relation_settings = $this->related_settings_for($model_name);
2360
-        return $relation_settings->get_all_related($model_obj, $query_params);
2361
-    }
2362
-
2363
-
2364
-
2365
-    /**
2366
-     * Deletes all the model objects across the relation indicated by $model_name
2367
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2368
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2369
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2370
-     *
2371
-     * @param EE_Base_Class|int|string $id_or_obj
2372
-     * @param string                   $model_name
2373
-     * @param array                    $query_params
2374
-     * @return int how many deleted
2375
-     * @throws \EE_Error
2376
-     */
2377
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2378
-    {
2379
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2380
-        $relation_settings = $this->related_settings_for($model_name);
2381
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2382
-    }
2383
-
2384
-
2385
-
2386
-    /**
2387
-     * Hard deletes all the model objects across the relation indicated by $model_name
2388
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2389
-     * the model objects can't be hard deleted because of blocking related model objects,
2390
-     * just does a soft-delete on them instead.
2391
-     *
2392
-     * @param EE_Base_Class|int|string $id_or_obj
2393
-     * @param string                   $model_name
2394
-     * @param array                    $query_params
2395
-     * @return int how many deleted
2396
-     * @throws \EE_Error
2397
-     */
2398
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2399
-    {
2400
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2401
-        $relation_settings = $this->related_settings_for($model_name);
2402
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2403
-    }
2404
-
2405
-
2406
-
2407
-    /**
2408
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2409
-     * unless otherwise specified in the $query_params
2410
-     *
2411
-     * @param        int             /EE_Base_Class $id_or_obj
2412
-     * @param string $model_name     like 'Event', or 'Registration'
2413
-     * @param array  $query_params   like EEM_Base::get_all's
2414
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2415
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2416
-     *                               that by the setting $distinct to TRUE;
2417
-     * @return int
2418
-     * @throws \EE_Error
2419
-     */
2420
-    public function count_related(
2421
-        $id_or_obj,
2422
-        $model_name,
2423
-        $query_params = array(),
2424
-        $field_to_count = null,
2425
-        $distinct = false
2426
-    ) {
2427
-        $related_model = $this->get_related_model_obj($model_name);
2428
-        //we're just going to use the query params on the related model's normal get_all query,
2429
-        //except add a condition to say to match the current mod
2430
-        if ( ! isset($query_params['default_where_conditions'])) {
2431
-            $query_params['default_where_conditions'] = 'none';
2432
-        }
2433
-        $this_model_name = $this->get_this_model_name();
2434
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2435
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2436
-        return $related_model->count($query_params, $field_to_count, $distinct);
2437
-    }
2438
-
2439
-
2440
-
2441
-    /**
2442
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2443
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2444
-     *
2445
-     * @param        int           /EE_Base_Class $id_or_obj
2446
-     * @param string $model_name   like 'Event', or 'Registration'
2447
-     * @param array  $query_params like EEM_Base::get_all's
2448
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2449
-     * @return float
2450
-     * @throws \EE_Error
2451
-     */
2452
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2453
-    {
2454
-        $related_model = $this->get_related_model_obj($model_name);
2455
-        if ( ! is_array($query_params)) {
2456
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2457
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2458
-                    gettype($query_params)), '4.6.0');
2459
-            $query_params = array();
2460
-        }
2461
-        //we're just going to use the query params on the related model's normal get_all query,
2462
-        //except add a condition to say to match the current mod
2463
-        if ( ! isset($query_params['default_where_conditions'])) {
2464
-            $query_params['default_where_conditions'] = 'none';
2465
-        }
2466
-        $this_model_name = $this->get_this_model_name();
2467
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2468
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2469
-        return $related_model->sum($query_params, $field_to_sum);
2470
-    }
2471
-
2472
-
2473
-
2474
-    /**
2475
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2476
-     * $modelObject
2477
-     *
2478
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2479
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2480
-     * @param array               $query_params     like EEM_Base::get_all's
2481
-     * @return EE_Base_Class
2482
-     * @throws \EE_Error
2483
-     */
2484
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2485
-    {
2486
-        $query_params['limit'] = 1;
2487
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2488
-        if ($results) {
2489
-            return array_shift($results);
2490
-        } else {
2491
-            return null;
2492
-        }
2493
-    }
2494
-
2495
-
2496
-
2497
-    /**
2498
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2499
-     *
2500
-     * @return string
2501
-     */
2502
-    public function get_this_model_name()
2503
-    {
2504
-        return str_replace("EEM_", "", get_class($this));
2505
-    }
2506
-
2507
-
2508
-
2509
-    /**
2510
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2511
-     *
2512
-     * @return EE_Any_Foreign_Model_Name_Field
2513
-     * @throws EE_Error
2514
-     */
2515
-    public function get_field_containing_related_model_name()
2516
-    {
2517
-        foreach ($this->field_settings(true) as $field) {
2518
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2519
-                $field_with_model_name = $field;
2520
-            }
2521
-        }
2522
-        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2523
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2524
-                $this->get_this_model_name()));
2525
-        }
2526
-        return $field_with_model_name;
2527
-    }
2528
-
2529
-
2530
-
2531
-    /**
2532
-     * Inserts a new entry into the database, for each table.
2533
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2534
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2535
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2536
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2537
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2538
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2539
-     *
2540
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2541
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2542
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2543
-     *                              of EEM_Base)
2544
-     * @return int new primary key on main table that got inserted
2545
-     * @throws EE_Error
2546
-     */
2547
-    public function insert($field_n_values)
2548
-    {
2549
-        /**
2550
-         * Filters the fields and their values before inserting an item using the models
2551
-         *
2552
-         * @param array    $fields_n_values keys are the fields and values are their new values
2553
-         * @param EEM_Base $model           the model used
2554
-         */
2555
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2556
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2557
-            $main_table = $this->_get_main_table();
2558
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2559
-            if ($new_id !== false) {
2560
-                foreach ($this->_get_other_tables() as $other_table) {
2561
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2562
-                }
2563
-            }
2564
-            /**
2565
-             * Done just after attempting to insert a new model object
2566
-             *
2567
-             * @param EEM_Base   $model           used
2568
-             * @param array      $fields_n_values fields and their values
2569
-             * @param int|string the              ID of the newly-inserted model object
2570
-             */
2571
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2572
-            return $new_id;
2573
-        } else {
2574
-            return false;
2575
-        }
2576
-    }
2577
-
2578
-
2579
-
2580
-    /**
2581
-     * Checks that the result would satisfy the unique indexes on this model
2582
-     *
2583
-     * @param array  $field_n_values
2584
-     * @param string $action
2585
-     * @return boolean
2586
-     * @throws \EE_Error
2587
-     */
2588
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2589
-    {
2590
-        foreach ($this->unique_indexes() as $index_name => $index) {
2591
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2592
-            if ($this->exists(array($uniqueness_where_params))) {
2593
-                EE_Error::add_error(
2594
-                    sprintf(
2595
-                        __(
2596
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2597
-                            "event_espresso"
2598
-                        ),
2599
-                        $action,
2600
-                        $this->_get_class_name(),
2601
-                        $index_name,
2602
-                        implode(",", $index->field_names()),
2603
-                        http_build_query($uniqueness_where_params)
2604
-                    ),
2605
-                    __FILE__,
2606
-                    __FUNCTION__,
2607
-                    __LINE__
2608
-                );
2609
-                return false;
2610
-            }
2611
-        }
2612
-        return true;
2613
-    }
2614
-
2615
-
2616
-
2617
-    /**
2618
-     * Checks the database for an item that conflicts (ie, if this item were
2619
-     * saved to the DB would break some uniqueness requirement, like a primary key
2620
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2621
-     * can be either an EE_Base_Class or an array of fields n values
2622
-     *
2623
-     * @param EE_Base_Class|array $obj_or_fields_array
2624
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2625
-     *                                                 when looking for conflicts
2626
-     *                                                 (ie, if false, we ignore the model object's primary key
2627
-     *                                                 when finding "conflicts". If true, it's also considered).
2628
-     *                                                 Only works for INT primary key,
2629
-     *                                                 STRING primary keys cannot be ignored
2630
-     * @throws EE_Error
2631
-     * @return EE_Base_Class|array
2632
-     */
2633
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2634
-    {
2635
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2636
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2637
-        } elseif (is_array($obj_or_fields_array)) {
2638
-            $fields_n_values = $obj_or_fields_array;
2639
-        } else {
2640
-            throw new EE_Error(
2641
-                sprintf(
2642
-                    __(
2643
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2644
-                        "event_espresso"
2645
-                    ),
2646
-                    get_class($this),
2647
-                    $obj_or_fields_array
2648
-                )
2649
-            );
2650
-        }
2651
-        $query_params = array();
2652
-        if ($this->has_primary_key_field()
2653
-            && ($include_primary_key
2654
-                || $this->get_primary_key_field()
2655
-                   instanceof
2656
-                   EE_Primary_Key_String_Field)
2657
-            && isset($fields_n_values[$this->primary_key_name()])
2658
-        ) {
2659
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2660
-        }
2661
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2662
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2663
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2664
-        }
2665
-        //if there is nothing to base this search on, then we shouldn't find anything
2666
-        if (empty($query_params)) {
2667
-            return array();
2668
-        } else {
2669
-            return $this->get_one($query_params);
2670
-        }
2671
-    }
2672
-
2673
-
2674
-
2675
-    /**
2676
-     * Like count, but is optimized and returns a boolean instead of an int
2677
-     *
2678
-     * @param array $query_params
2679
-     * @return boolean
2680
-     * @throws \EE_Error
2681
-     */
2682
-    public function exists($query_params)
2683
-    {
2684
-        $query_params['limit'] = 1;
2685
-        return $this->count($query_params) > 0;
2686
-    }
2687
-
2688
-
2689
-
2690
-    /**
2691
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2692
-     *
2693
-     * @param int|string $id
2694
-     * @return boolean
2695
-     * @throws \EE_Error
2696
-     */
2697
-    public function exists_by_ID($id)
2698
-    {
2699
-        return $this->exists(array('default_where_conditions' => 'none', array($this->primary_key_name() => $id)));
2700
-    }
2701
-
2702
-
2703
-
2704
-    /**
2705
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2706
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2707
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2708
-     * on the main table)
2709
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2710
-     * cases where we want to call it directly rather than via insert().
2711
-     *
2712
-     * @access   protected
2713
-     * @param EE_Table_Base $table
2714
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2715
-     *                                       float
2716
-     * @param int           $new_id          for now we assume only int keys
2717
-     * @throws EE_Error
2718
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2719
-     * @return int ID of new row inserted, or FALSE on failure
2720
-     */
2721
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2722
-    {
2723
-        global $wpdb;
2724
-        $insertion_col_n_values = array();
2725
-        $format_for_insertion = array();
2726
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2727
-        foreach ($fields_on_table as $field_name => $field_obj) {
2728
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2729
-            if ($field_obj->is_auto_increment()) {
2730
-                continue;
2731
-            }
2732
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2733
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2734
-            if ($prepared_value !== null) {
2735
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2736
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2737
-            }
2738
-        }
2739
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2740
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2741
-            //so add the fk to the main table as a column
2742
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2743
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2744
-        }
2745
-        //insert the new entry
2746
-        $result = $this->_do_wpdb_query('insert',
2747
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2748
-        if ($result === false) {
2749
-            return false;
2750
-        }
2751
-        //ok, now what do we return for the ID of the newly-inserted thing?
2752
-        if ($this->has_primary_key_field()) {
2753
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2754
-                return $wpdb->insert_id;
2755
-            } else {
2756
-                //it's not an auto-increment primary key, so
2757
-                //it must have been supplied
2758
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2759
-            }
2760
-        } else {
2761
-            //we can't return a  primary key because there is none. instead return
2762
-            //a unique string indicating this model
2763
-            return $this->get_index_primary_key_string($fields_n_values);
2764
-        }
2765
-    }
2766
-
2767
-
2768
-
2769
-    /**
2770
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2771
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2772
-     * and there is no default, we pass it along. WPDB will take care of it)
2773
-     *
2774
-     * @param EE_Model_Field_Base $field_obj
2775
-     * @param array               $fields_n_values
2776
-     * @return mixed string|int|float depending on what the table column will be expecting
2777
-     * @throws \EE_Error
2778
-     */
2779
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2780
-    {
2781
-        //if this field doesn't allow nullable, don't allow it
2782
-        if ( ! $field_obj->is_nullable()
2783
-             && (
2784
-                 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2785
-        ) {
2786
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2787
-        }
2788
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2789
-            : null;
2790
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2791
-    }
2792
-
2793
-
2794
-
2795
-    /**
2796
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2797
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2798
-     * the field's prepare_for_set() method.
2799
-     *
2800
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2801
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2802
-     *                                   top of file)
2803
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2804
-     *                                   $value is a custom selection
2805
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2806
-     */
2807
-    private function _prepare_value_for_use_in_db($value, $field)
2808
-    {
2809
-        if ($field && $field instanceof EE_Model_Field_Base) {
2810
-            switch ($this->_values_already_prepared_by_model_object) {
2811
-                /** @noinspection PhpMissingBreakStatementInspection */
2812
-                case self::not_prepared_by_model_object:
2813
-                    $value = $field->prepare_for_set($value);
2814
-                //purposefully left out "return"
2815
-                case self::prepared_by_model_object:
2816
-                    $value = $field->prepare_for_use_in_db($value);
2817
-                case self::prepared_for_use_in_db:
2818
-                    //leave the value alone
2819
-            }
2820
-            return $value;
2821
-        } else {
2822
-            return $value;
2823
-        }
2824
-    }
2825
-
2826
-
2827
-
2828
-    /**
2829
-     * Returns the main table on this model
2830
-     *
2831
-     * @return EE_Primary_Table
2832
-     * @throws EE_Error
2833
-     */
2834
-    protected function _get_main_table()
2835
-    {
2836
-        foreach ($this->_tables as $table) {
2837
-            if ($table instanceof EE_Primary_Table) {
2838
-                return $table;
2839
-            }
2840
-        }
2841
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2842
-            'event_espresso'), get_class($this)));
2843
-    }
2844
-
2845
-
2846
-
2847
-    /**
2848
-     * table
2849
-     * returns EE_Primary_Table table name
2850
-     *
2851
-     * @return string
2852
-     * @throws \EE_Error
2853
-     */
2854
-    public function table()
2855
-    {
2856
-        return $this->_get_main_table()->get_table_name();
2857
-    }
2858
-
2859
-
2860
-
2861
-    /**
2862
-     * table
2863
-     * returns first EE_Secondary_Table table name
2864
-     *
2865
-     * @return string
2866
-     */
2867
-    public function second_table()
2868
-    {
2869
-        // grab second table from tables array
2870
-        $second_table = end($this->_tables);
2871
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2872
-    }
2873
-
2874
-
2875
-
2876
-    /**
2877
-     * get_table_obj_by_alias
2878
-     * returns table name given it's alias
2879
-     *
2880
-     * @param string $table_alias
2881
-     * @return EE_Primary_Table | EE_Secondary_Table
2882
-     */
2883
-    public function get_table_obj_by_alias($table_alias = '')
2884
-    {
2885
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
2886
-    }
2887
-
2888
-
2889
-
2890
-    /**
2891
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
2892
-     *
2893
-     * @return EE_Secondary_Table[]
2894
-     */
2895
-    protected function _get_other_tables()
2896
-    {
2897
-        $other_tables = array();
2898
-        foreach ($this->_tables as $table_alias => $table) {
2899
-            if ($table instanceof EE_Secondary_Table) {
2900
-                $other_tables[$table_alias] = $table;
2901
-            }
2902
-        }
2903
-        return $other_tables;
2904
-    }
2905
-
2906
-
2907
-
2908
-    /**
2909
-     * Finds all the fields that correspond to the given table
2910
-     *
2911
-     * @param string $table_alias , array key in EEM_Base::_tables
2912
-     * @return EE_Model_Field_Base[]
2913
-     */
2914
-    public function _get_fields_for_table($table_alias)
2915
-    {
2916
-        return $this->_fields[$table_alias];
2917
-    }
2918
-
2919
-
2920
-
2921
-    /**
2922
-     * Recurses through all the where parameters, and finds all the related models we'll need
2923
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
2924
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
2925
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
2926
-     * related Registration, Transaction, and Payment models.
2927
-     *
2928
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
2929
-     * @return EE_Model_Query_Info_Carrier
2930
-     * @throws \EE_Error
2931
-     */
2932
-    public function _extract_related_models_from_query($query_params)
2933
-    {
2934
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
2935
-        if (array_key_exists(0, $query_params)) {
2936
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
2937
-        }
2938
-        if (array_key_exists('group_by', $query_params)) {
2939
-            if (is_array($query_params['group_by'])) {
2940
-                $this->_extract_related_models_from_sub_params_array_values(
2941
-                    $query_params['group_by'],
2942
-                    $query_info_carrier,
2943
-                    'group_by'
2944
-                );
2945
-            } elseif ( ! empty ($query_params['group_by'])) {
2946
-                $this->_extract_related_model_info_from_query_param(
2947
-                    $query_params['group_by'],
2948
-                    $query_info_carrier,
2949
-                    'group_by'
2950
-                );
2951
-            }
2952
-        }
2953
-        if (array_key_exists('having', $query_params)) {
2954
-            $this->_extract_related_models_from_sub_params_array_keys(
2955
-                $query_params[0],
2956
-                $query_info_carrier,
2957
-                'having'
2958
-            );
2959
-        }
2960
-        if (array_key_exists('order_by', $query_params)) {
2961
-            if (is_array($query_params['order_by'])) {
2962
-                $this->_extract_related_models_from_sub_params_array_keys(
2963
-                    $query_params['order_by'],
2964
-                    $query_info_carrier,
2965
-                    'order_by'
2966
-                );
2967
-            } elseif ( ! empty($query_params['order_by'])) {
2968
-                $this->_extract_related_model_info_from_query_param(
2969
-                    $query_params['order_by'],
2970
-                    $query_info_carrier,
2971
-                    'order_by'
2972
-                );
2973
-            }
2974
-        }
2975
-        if (array_key_exists('force_join', $query_params)) {
2976
-            $this->_extract_related_models_from_sub_params_array_values(
2977
-                $query_params['force_join'],
2978
-                $query_info_carrier,
2979
-                'force_join'
2980
-            );
2981
-        }
2982
-        return $query_info_carrier;
2983
-    }
2984
-
2985
-
2986
-
2987
-    /**
2988
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
2989
-     *
2990
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
2991
-     *                                                      $query_params['having']
2992
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
2993
-     * @param string                      $query_param_type one of $this->_allowed_query_params
2994
-     * @throws EE_Error
2995
-     * @return \EE_Model_Query_Info_Carrier
2996
-     */
2997
-    private function _extract_related_models_from_sub_params_array_keys(
2998
-        $sub_query_params,
2999
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3000
-        $query_param_type
3001
-    ) {
3002
-        if ( ! empty($sub_query_params)) {
3003
-            $sub_query_params = (array)$sub_query_params;
3004
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3005
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3006
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3007
-                    $query_param_type);
3008
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3009
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3010
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3011
-                //of array('Registration.TXN_ID'=>23)
3012
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3013
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3014
-                    if ( ! is_array($possibly_array_of_params)) {
3015
-                        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'))",
3016
-                            "event_espresso"),
3017
-                            $param, $possibly_array_of_params));
3018
-                    } else {
3019
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3020
-                            $model_query_info_carrier, $query_param_type);
3021
-                    }
3022
-                } elseif ($query_param_type === 0 //ie WHERE
3023
-                          && is_array($possibly_array_of_params)
3024
-                          && isset($possibly_array_of_params[2])
3025
-                          && $possibly_array_of_params[2] == true
3026
-                ) {
3027
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3028
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3029
-                    //from which we should extract query parameters!
3030
-                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3031
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3032
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3033
-                    }
3034
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3035
-                        $model_query_info_carrier, $query_param_type);
3036
-                }
3037
-            }
3038
-        }
3039
-        return $model_query_info_carrier;
3040
-    }
3041
-
3042
-
3043
-
3044
-    /**
3045
-     * For extracting related models from forced_joins, where the array values contain the info about what
3046
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3047
-     *
3048
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3049
-     *                                                      $query_params['having']
3050
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3051
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3052
-     * @throws EE_Error
3053
-     * @return \EE_Model_Query_Info_Carrier
3054
-     */
3055
-    private function _extract_related_models_from_sub_params_array_values(
3056
-        $sub_query_params,
3057
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3058
-        $query_param_type
3059
-    ) {
3060
-        if ( ! empty($sub_query_params)) {
3061
-            if ( ! is_array($sub_query_params)) {
3062
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3063
-                    $sub_query_params));
3064
-            }
3065
-            foreach ($sub_query_params as $param) {
3066
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3067
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3068
-                    $query_param_type);
3069
-            }
3070
-        }
3071
-        return $model_query_info_carrier;
3072
-    }
3073
-
3074
-
3075
-
3076
-    /**
3077
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3078
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3079
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3080
-     * but use them in a different order. Eg, we need to know what models we are querying
3081
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3082
-     * other models before we can finalize the where clause SQL.
3083
-     *
3084
-     * @param array $query_params
3085
-     * @throws EE_Error
3086
-     * @return EE_Model_Query_Info_Carrier
3087
-     */
3088
-    public function _create_model_query_info_carrier($query_params)
3089
-    {
3090
-        if ( ! is_array($query_params)) {
3091
-            EE_Error::doing_it_wrong(
3092
-                'EEM_Base::_create_model_query_info_carrier',
3093
-                sprintf(
3094
-                    __(
3095
-                        '$query_params should be an array, you passed a variable of type %s',
3096
-                        'event_espresso'
3097
-                    ),
3098
-                    gettype($query_params)
3099
-                ),
3100
-                '4.6.0'
3101
-            );
3102
-            $query_params = array();
3103
-        }
3104
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3105
-        //first check if we should alter the query to account for caps or not
3106
-        //because the caps might require us to do extra joins
3107
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3108
-            $query_params[0] = $where_query_params = array_replace_recursive(
3109
-                $where_query_params,
3110
-                $this->caps_where_conditions(
3111
-                    $query_params['caps']
3112
-                )
3113
-            );
3114
-        }
3115
-        $query_object = $this->_extract_related_models_from_query($query_params);
3116
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3117
-        foreach ($where_query_params as $key => $value) {
3118
-            if (is_int($key)) {
3119
-                throw new EE_Error(
3120
-                    sprintf(
3121
-                        __(
3122
-                            "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.",
3123
-                            "event_espresso"
3124
-                        ),
3125
-                        $key,
3126
-                        var_export($value, true),
3127
-                        var_export($query_params, true),
3128
-                        get_class($this)
3129
-                    )
3130
-                );
3131
-            }
3132
-        }
3133
-        if (
3134
-            array_key_exists('default_where_conditions', $query_params)
3135
-            && ! empty($query_params['default_where_conditions'])
3136
-        ) {
3137
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3138
-        } else {
3139
-            $use_default_where_conditions = 'all';
3140
-        }
3141
-        $where_query_params = array_merge(
3142
-            $this->_get_default_where_conditions_for_models_in_query(
3143
-                $query_object,
3144
-                $use_default_where_conditions,
3145
-                $where_query_params
3146
-            ),
3147
-            $where_query_params
3148
-        );
3149
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3150
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3151
-        // So we need to setup a subquery and use that for the main join.
3152
-        // Note for now this only works on the primary table for the model.
3153
-        // So for instance, you could set the limit array like this:
3154
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3155
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3156
-            $query_object->set_main_model_join_sql(
3157
-                $this->_construct_limit_join_select(
3158
-                    $query_params['on_join_limit'][0],
3159
-                    $query_params['on_join_limit'][1]
3160
-                )
3161
-            );
3162
-        }
3163
-        //set limit
3164
-        if (array_key_exists('limit', $query_params)) {
3165
-            if (is_array($query_params['limit'])) {
3166
-                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3167
-                    $e = sprintf(
3168
-                        __(
3169
-                            "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)",
3170
-                            "event_espresso"
3171
-                        ),
3172
-                        http_build_query($query_params['limit'])
3173
-                    );
3174
-                    throw new EE_Error($e . "|" . $e);
3175
-                }
3176
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3177
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3178
-            } elseif ( ! empty ($query_params['limit'])) {
3179
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3180
-            }
3181
-        }
3182
-        //set order by
3183
-        if (array_key_exists('order_by', $query_params)) {
3184
-            if (is_array($query_params['order_by'])) {
3185
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3186
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3187
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3188
-                if (array_key_exists('order', $query_params)) {
3189
-                    throw new EE_Error(
3190
-                        sprintf(
3191
-                            __(
3192
-                                "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 ",
3193
-                                "event_espresso"
3194
-                            ),
3195
-                            get_class($this),
3196
-                            implode(", ", array_keys($query_params['order_by'])),
3197
-                            implode(", ", $query_params['order_by']),
3198
-                            $query_params['order']
3199
-                        )
3200
-                    );
3201
-                }
3202
-                $this->_extract_related_models_from_sub_params_array_keys(
3203
-                    $query_params['order_by'],
3204
-                    $query_object,
3205
-                    'order_by'
3206
-                );
3207
-                //assume it's an array of fields to order by
3208
-                $order_array = array();
3209
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3210
-                    $order = $this->_extract_order($order);
3211
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3212
-                }
3213
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3214
-            } elseif ( ! empty ($query_params['order_by'])) {
3215
-                $this->_extract_related_model_info_from_query_param(
3216
-                    $query_params['order_by'],
3217
-                    $query_object,
3218
-                    'order',
3219
-                    $query_params['order_by']
3220
-                );
3221
-                $order = isset($query_params['order'])
3222
-                    ? $this->_extract_order($query_params['order'])
3223
-                    : 'DESC';
3224
-                $query_object->set_order_by_sql(
3225
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3226
-                );
3227
-            }
3228
-        }
3229
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3230
-        if ( ! array_key_exists('order_by', $query_params)
3231
-             && array_key_exists('order', $query_params)
3232
-             && ! empty($query_params['order'])
3233
-        ) {
3234
-            $pk_field = $this->get_primary_key_field();
3235
-            $order = $this->_extract_order($query_params['order']);
3236
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3237
-        }
3238
-        //set group by
3239
-        if (array_key_exists('group_by', $query_params)) {
3240
-            if (is_array($query_params['group_by'])) {
3241
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3242
-                $group_by_array = array();
3243
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3244
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3245
-                }
3246
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3247
-            } elseif ( ! empty ($query_params['group_by'])) {
3248
-                $query_object->set_group_by_sql(
3249
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3250
-                );
3251
-            }
3252
-        }
3253
-        //set having
3254
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3255
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3256
-        }
3257
-        //now, just verify they didn't pass anything wack
3258
-        foreach ($query_params as $query_key => $query_value) {
3259
-            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3260
-                throw new EE_Error(
3261
-                    sprintf(
3262
-                        __(
3263
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3264
-                            'event_espresso'
3265
-                        ),
3266
-                        $query_key,
3267
-                        get_class($this),
1577
+			//let's make sure default_where strategy is followed now
1578
+			$this->_ignore_where_strategy = false;
1579
+		}
1580
+		//if we want to keep model objects in sync, AND
1581
+		//if this wasn't called from a model object (to update itself)
1582
+		//then we want to make sure we keep all the existing
1583
+		//model objects in sync with the db
1584
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1585
+			if ($this->has_primary_key_field()) {
1586
+				$model_objs_affected_ids = $this->get_col($query_params);
1587
+			} else {
1588
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1589
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1590
+				$model_objs_affected_ids = array();
1591
+				foreach ($models_affected_key_columns as $row) {
1592
+					$combined_index_key = $this->get_index_primary_key_string($row);
1593
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1594
+				}
1595
+			}
1596
+			if ( ! $model_objs_affected_ids) {
1597
+				//wait wait wait- if nothing was affected let's stop here
1598
+				return 0;
1599
+			}
1600
+			foreach ($model_objs_affected_ids as $id) {
1601
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1602
+				if ($model_obj_in_entity_map) {
1603
+					foreach ($fields_n_values as $field => $new_value) {
1604
+						$model_obj_in_entity_map->set($field, $new_value);
1605
+					}
1606
+				}
1607
+			}
1608
+			//if there is a primary key on this model, we can now do a slight optimization
1609
+			if ($this->has_primary_key_field()) {
1610
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1611
+				$query_params = array(
1612
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1613
+					'limit'                    => count($model_objs_affected_ids),
1614
+					'default_where_conditions' => 'none',
1615
+				);
1616
+			}
1617
+		}
1618
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1619
+		$SQL = "UPDATE "
1620
+			   . $model_query_info->get_full_join_sql()
1621
+			   . " SET "
1622
+			   . $this->_construct_update_sql($fields_n_values)
1623
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1624
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1625
+		/**
1626
+		 * Action called after a model update call has been made.
1627
+		 *
1628
+		 * @param EEM_Base $model
1629
+		 * @param array    $fields_n_values the updated fields and their new values
1630
+		 * @param array    $query_params    @see EEM_Base::get_all()
1631
+		 * @param int      $rows_affected
1632
+		 */
1633
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1634
+		return $rows_affected;//how many supposedly got updated
1635
+	}
1636
+
1637
+
1638
+
1639
+	/**
1640
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1641
+	 * are teh values of the field specified (or by default the primary key field)
1642
+	 * that matched the query params. Note that you should pass the name of the
1643
+	 * model FIELD, not the database table's column name.
1644
+	 *
1645
+	 * @param array  $query_params @see EEM_Base::get_all()
1646
+	 * @param string $field_to_select
1647
+	 * @return array just like $wpdb->get_col()
1648
+	 * @throws \EE_Error
1649
+	 */
1650
+	public function get_col($query_params = array(), $field_to_select = null)
1651
+	{
1652
+		if ($field_to_select) {
1653
+			$field = $this->field_settings_for($field_to_select);
1654
+		} elseif ($this->has_primary_key_field()) {
1655
+			$field = $this->get_primary_key_field();
1656
+		} else {
1657
+			//no primary key, just grab the first column
1658
+			$field = reset($this->field_settings());
1659
+		}
1660
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1661
+		$select_expressions = $field->get_qualified_column();
1662
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1663
+		return $this->_do_wpdb_query('get_col', array($SQL));
1664
+	}
1665
+
1666
+
1667
+
1668
+	/**
1669
+	 * Returns a single column value for a single row from the database
1670
+	 *
1671
+	 * @param array  $query_params    @see EEM_Base::get_all()
1672
+	 * @param string $field_to_select @see EEM_Base::get_col()
1673
+	 * @return string
1674
+	 * @throws \EE_Error
1675
+	 */
1676
+	public function get_var($query_params = array(), $field_to_select = null)
1677
+	{
1678
+		$query_params['limit'] = 1;
1679
+		$col = $this->get_col($query_params, $field_to_select);
1680
+		if ( ! empty($col)) {
1681
+			return reset($col);
1682
+		} else {
1683
+			return null;
1684
+		}
1685
+	}
1686
+
1687
+
1688
+
1689
+	/**
1690
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1691
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1692
+	 * injection, but currently no further filtering is done
1693
+	 *
1694
+	 * @global      $wpdb
1695
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1696
+	 *                               be updated to in the DB
1697
+	 * @return string of SQL
1698
+	 * @throws \EE_Error
1699
+	 */
1700
+	public function _construct_update_sql($fields_n_values)
1701
+	{
1702
+		/** @type WPDB $wpdb */
1703
+		global $wpdb;
1704
+		$cols_n_values = array();
1705
+		foreach ($fields_n_values as $field_name => $value) {
1706
+			$field_obj = $this->field_settings_for($field_name);
1707
+			//if the value is NULL, we want to assign the value to that.
1708
+			//wpdb->prepare doesn't really handle that properly
1709
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1710
+			$value_sql = $prepared_value === null ? 'NULL'
1711
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1712
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1713
+		}
1714
+		return implode(",", $cols_n_values);
1715
+	}
1716
+
1717
+
1718
+
1719
+	/**
1720
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1721
+	 * Performs a HARD delete, meaning the database row should always be removed,
1722
+	 * not just have a flag field on it switched
1723
+	 * Wrapper for EEM_Base::delete_permanently()
1724
+	 *
1725
+	 * @param mixed $id
1726
+	 * @return boolean whether the row got deleted or not
1727
+	 * @throws \EE_Error
1728
+	 */
1729
+	public function delete_permanently_by_ID($id)
1730
+	{
1731
+		return $this->delete_permanently(
1732
+			array(
1733
+				array($this->get_primary_key_field()->get_name() => $id),
1734
+				'limit' => 1,
1735
+			)
1736
+		);
1737
+	}
1738
+
1739
+
1740
+
1741
+	/**
1742
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1743
+	 * Wrapper for EEM_Base::delete()
1744
+	 *
1745
+	 * @param mixed $id
1746
+	 * @return boolean whether the row got deleted or not
1747
+	 * @throws \EE_Error
1748
+	 */
1749
+	public function delete_by_ID($id)
1750
+	{
1751
+		return $this->delete(
1752
+			array(
1753
+				array($this->get_primary_key_field()->get_name() => $id),
1754
+				'limit' => 1,
1755
+			)
1756
+		);
1757
+	}
1758
+
1759
+
1760
+
1761
+	/**
1762
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1763
+	 * meaning if the model has a field that indicates its been "trashed" or
1764
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1765
+	 *
1766
+	 * @see EEM_Base::delete_permanently
1767
+	 * @param array   $query_params
1768
+	 * @param boolean $allow_blocking
1769
+	 * @return int how many rows got deleted
1770
+	 * @throws \EE_Error
1771
+	 */
1772
+	public function delete($query_params, $allow_blocking = true)
1773
+	{
1774
+		return $this->delete_permanently($query_params, $allow_blocking);
1775
+	}
1776
+
1777
+
1778
+
1779
+	/**
1780
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1781
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1782
+	 * as archived, not actually deleted
1783
+	 *
1784
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1785
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1786
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1787
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1788
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1789
+	 *                                DB
1790
+	 * @return int how many rows got deleted
1791
+	 * @throws \EE_Error
1792
+	 */
1793
+	public function delete_permanently($query_params, $allow_blocking = true)
1794
+	{
1795
+		/**
1796
+		 * Action called just before performing a real deletion query. You can use the
1797
+		 * model and its $query_params to find exactly which items will be deleted
1798
+		 *
1799
+		 * @param EEM_Base $model
1800
+		 * @param array    $query_params   @see EEM_Base::get_all()
1801
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1802
+		 *                                 to block (prevent) this deletion
1803
+		 */
1804
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1805
+		//some MySQL databases may be running safe mode, which may restrict
1806
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1807
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1808
+		//to delete them
1809
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1810
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1811
+		if ($deletion_where) {
1812
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1813
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1814
+			$table_aliases = array_keys($this->_tables);
1815
+			$SQL = "DELETE "
1816
+				   . implode(", ", $table_aliases)
1817
+				   . " FROM "
1818
+				   . $model_query_info->get_full_join_sql()
1819
+				   . " WHERE "
1820
+				   . $deletion_where;
1821
+			//		/echo "delete sql:$SQL";
1822
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1823
+		} else {
1824
+			$rows_deleted = 0;
1825
+		}
1826
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1827
+		if ($this->has_primary_key_field()) {
1828
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1829
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1830
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1831
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1832
+				}
1833
+			}
1834
+		}
1835
+		/**
1836
+		 * Action called just after performing a real deletion query. Although at this point the
1837
+		 * items should have been deleted
1838
+		 *
1839
+		 * @param EEM_Base $model
1840
+		 * @param array    $query_params @see EEM_Base::get_all()
1841
+		 * @param int      $rows_deleted
1842
+		 */
1843
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1844
+		return $rows_deleted;//how many supposedly got deleted
1845
+	}
1846
+
1847
+
1848
+
1849
+	/**
1850
+	 * Checks all the relations that throw error messages when there are blocking related objects
1851
+	 * for related model objects. If there are any related model objects on those relations,
1852
+	 * adds an EE_Error, and return true
1853
+	 *
1854
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1855
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1856
+	 *                                                 should be ignored when determining whether there are related
1857
+	 *                                                 model objects which block this model object's deletion. Useful
1858
+	 *                                                 if you know A is related to B and are considering deleting A,
1859
+	 *                                                 but want to see if A has any other objects blocking its deletion
1860
+	 *                                                 before removing the relation between A and B
1861
+	 * @return boolean
1862
+	 * @throws \EE_Error
1863
+	 */
1864
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1865
+	{
1866
+		//first, if $ignore_this_model_obj was supplied, get its model
1867
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1868
+			$ignored_model = $ignore_this_model_obj->get_model();
1869
+		} else {
1870
+			$ignored_model = null;
1871
+		}
1872
+		//now check all the relations of $this_model_obj_or_id and see if there
1873
+		//are any related model objects blocking it?
1874
+		$is_blocked = false;
1875
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
1876
+			if ($relation_obj->block_delete_if_related_models_exist()) {
1877
+				//if $ignore_this_model_obj was supplied, then for the query
1878
+				//on that model needs to be told to ignore $ignore_this_model_obj
1879
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1880
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1881
+						array(
1882
+							$ignored_model->get_primary_key_field()->get_name() => array(
1883
+								'!=',
1884
+								$ignore_this_model_obj->ID(),
1885
+							),
1886
+						),
1887
+					));
1888
+				} else {
1889
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1890
+				}
1891
+				if ($related_model_objects) {
1892
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1893
+					$is_blocked = true;
1894
+				}
1895
+			}
1896
+		}
1897
+		return $is_blocked;
1898
+	}
1899
+
1900
+
1901
+
1902
+	/**
1903
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
1904
+	 * well.
1905
+	 *
1906
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1907
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
1908
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
1909
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
1910
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
1911
+	 *                                      easily corrupt your DB
1912
+	 * @throws EE_Error
1913
+	 * @return string    everything that comes after the WHERE statement.
1914
+	 */
1915
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
1916
+	{
1917
+		if ($this->has_primary_key_field()) {
1918
+			$primary_table = $this->_get_main_table();
1919
+			$other_tables = $this->_get_other_tables();
1920
+			$deletes = $query = array();
1921
+			foreach ($objects_for_deletion as $delete_object) {
1922
+				//before we mark this object for deletion,
1923
+				//make sure there's no related objects blocking its deletion (if we're checking)
1924
+				if (
1925
+					$allow_blocking
1926
+					&& $this->delete_is_blocked_by_related_models(
1927
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
1928
+					)
1929
+				) {
1930
+					continue;
1931
+				}
1932
+				//primary table deletes
1933
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
1934
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
1935
+				}
1936
+				//other tables
1937
+				if ( ! empty($other_tables)) {
1938
+					foreach ($other_tables as $ot) {
1939
+						//first check if we've got the foreign key column here.
1940
+						if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
1941
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
1942
+						}
1943
+						// wait! it's entirely possible that we'll have a the primary key
1944
+						// for this table in here, if it's a foreign key for one of the other secondary tables
1945
+						if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
1946
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1947
+						}
1948
+						// finally, it is possible that the fk for this table is found
1949
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
1950
+						if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
1951
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1952
+						}
1953
+					}
1954
+				}
1955
+			}
1956
+			//we should have deletes now, so let's just go through and setup the where statement
1957
+			foreach ($deletes as $column => $values) {
1958
+				//make sure we have unique $values;
1959
+				$values = array_unique($values);
1960
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
1961
+			}
1962
+			return ! empty($query) ? implode(' AND ', $query) : '';
1963
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
1964
+			$ways_to_identify_a_row = array();
1965
+			$fields = $this->get_combined_primary_key_fields();
1966
+			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
1967
+			foreach ($objects_for_deletion as $delete_object) {
1968
+				$values_for_each_cpk_for_a_row = array();
1969
+				foreach ($fields as $cpk_field) {
1970
+					if ($cpk_field instanceof EE_Model_Field_Base) {
1971
+						$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
1972
+														   . "="
1973
+														   . $delete_object[$cpk_field->get_qualified_column()];
1974
+					}
1975
+				}
1976
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
1977
+			}
1978
+			return implode(" OR ", $ways_to_identify_a_row);
1979
+		} else {
1980
+			//so there's no primary key and no combined key...
1981
+			//sorry, can't help you
1982
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
1983
+				"event_espresso"), get_class($this)));
1984
+		}
1985
+	}
1986
+
1987
+
1988
+
1989
+	/**
1990
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
1991
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
1992
+	 * column
1993
+	 *
1994
+	 * @param array  $query_params   like EEM_Base::get_all's
1995
+	 * @param string $field_to_count field on model to count by (not column name)
1996
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
1997
+	 *                               that by the setting $distinct to TRUE;
1998
+	 * @return int
1999
+	 * @throws \EE_Error
2000
+	 */
2001
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2002
+	{
2003
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2004
+		if ($field_to_count) {
2005
+			$field_obj = $this->field_settings_for($field_to_count);
2006
+			$column_to_count = $field_obj->get_qualified_column();
2007
+		} elseif ($this->has_primary_key_field()) {
2008
+			$pk_field_obj = $this->get_primary_key_field();
2009
+			$column_to_count = $pk_field_obj->get_qualified_column();
2010
+		} else {
2011
+			//there's no primary key
2012
+			//if we're counting distinct items, and there's no primary key,
2013
+			//we need to list out the columns for distinction;
2014
+			//otherwise we can just use star
2015
+			if ($distinct) {
2016
+				$columns_to_use = array();
2017
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2018
+					$columns_to_use[] = $field_obj->get_qualified_column();
2019
+				}
2020
+				$column_to_count = implode(',', $columns_to_use);
2021
+			} else {
2022
+				$column_to_count = '*';
2023
+			}
2024
+		}
2025
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2026
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2027
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2028
+	}
2029
+
2030
+
2031
+
2032
+	/**
2033
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2034
+	 *
2035
+	 * @param array  $query_params like EEM_Base::get_all
2036
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2037
+	 * @return float
2038
+	 * @throws \EE_Error
2039
+	 */
2040
+	public function sum($query_params, $field_to_sum = null)
2041
+	{
2042
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2043
+		if ($field_to_sum) {
2044
+			$field_obj = $this->field_settings_for($field_to_sum);
2045
+		} else {
2046
+			$field_obj = $this->get_primary_key_field();
2047
+		}
2048
+		$column_to_count = $field_obj->get_qualified_column();
2049
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2050
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2051
+		$data_type = $field_obj->get_wpdb_data_type();
2052
+		if ($data_type === '%d' || $data_type === '%s') {
2053
+			return (float)$return_value;
2054
+		} else {//must be %f
2055
+			return (float)$return_value;
2056
+		}
2057
+	}
2058
+
2059
+
2060
+
2061
+	/**
2062
+	 * Just calls the specified method on $wpdb with the given arguments
2063
+	 * Consolidates a little extra error handling code
2064
+	 *
2065
+	 * @param string $wpdb_method
2066
+	 * @param array  $arguments_to_provide
2067
+	 * @throws EE_Error
2068
+	 * @global wpdb  $wpdb
2069
+	 * @return mixed
2070
+	 */
2071
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2072
+	{
2073
+		//if we're in maintenance mode level 2, DON'T run any queries
2074
+		//because level 2 indicates the database needs updating and
2075
+		//is probably out of sync with the code
2076
+		if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2077
+			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.",
2078
+				"event_espresso")));
2079
+		}
2080
+		/** @type WPDB $wpdb */
2081
+		global $wpdb;
2082
+		if ( ! method_exists($wpdb, $wpdb_method)) {
2083
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2084
+				'event_espresso'), $wpdb_method));
2085
+		}
2086
+		if (WP_DEBUG) {
2087
+			$old_show_errors_value = $wpdb->show_errors;
2088
+			$wpdb->show_errors(false);
2089
+		}
2090
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2091
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2092
+		if (WP_DEBUG) {
2093
+			$wpdb->show_errors($old_show_errors_value);
2094
+			if ( ! empty($wpdb->last_error)) {
2095
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2096
+			} elseif ($result === false) {
2097
+				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"',
2098
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2099
+			}
2100
+		} elseif ($result === false) {
2101
+			EE_Error::add_error(
2102
+				sprintf(
2103
+					__('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"',
2104
+						'event_espresso'),
2105
+					$wpdb_method,
2106
+					var_export($arguments_to_provide, true),
2107
+					$wpdb->last_error
2108
+				),
2109
+				__FILE__,
2110
+				__FUNCTION__,
2111
+				__LINE__
2112
+			);
2113
+		}
2114
+		return $result;
2115
+	}
2116
+
2117
+
2118
+
2119
+	/**
2120
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2121
+	 * and if there's an error tries to verify the DB is correct. Uses
2122
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2123
+	 * we should try to fix the EE core db, the addons, or just give up
2124
+	 *
2125
+	 * @param string $wpdb_method
2126
+	 * @param array  $arguments_to_provide
2127
+	 * @return mixed
2128
+	 */
2129
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2130
+	{
2131
+		/** @type WPDB $wpdb */
2132
+		global $wpdb;
2133
+		$wpdb->last_error = null;
2134
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2135
+		// was there an error running the query? but we don't care on new activations
2136
+		// (we're going to setup the DB anyway on new activations)
2137
+		if (($result === false || ! empty($wpdb->last_error))
2138
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2139
+		) {
2140
+			switch (EEM_Base::$_db_verification_level) {
2141
+				case EEM_Base::db_verified_none :
2142
+					// let's double-check core's DB
2143
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2144
+					break;
2145
+				case EEM_Base::db_verified_core :
2146
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2147
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2148
+					break;
2149
+				case EEM_Base::db_verified_addons :
2150
+					// ummmm... you in trouble
2151
+					return $result;
2152
+					break;
2153
+			}
2154
+			if ( ! empty($error_message)) {
2155
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2156
+				trigger_error($error_message);
2157
+			}
2158
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2159
+		}
2160
+		return $result;
2161
+	}
2162
+
2163
+
2164
+
2165
+	/**
2166
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2167
+	 * EEM_Base::$_db_verification_level
2168
+	 *
2169
+	 * @param string $wpdb_method
2170
+	 * @param array  $arguments_to_provide
2171
+	 * @return string
2172
+	 */
2173
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2174
+	{
2175
+		/** @type WPDB $wpdb */
2176
+		global $wpdb;
2177
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2178
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2179
+		$error_message = sprintf(
2180
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2181
+				'event_espresso'),
2182
+			$wpdb->last_error,
2183
+			$wpdb_method,
2184
+			json_encode($arguments_to_provide)
2185
+		);
2186
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2187
+		return $error_message;
2188
+	}
2189
+
2190
+
2191
+
2192
+	/**
2193
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2194
+	 * EEM_Base::$_db_verification_level
2195
+	 *
2196
+	 * @param $wpdb_method
2197
+	 * @param $arguments_to_provide
2198
+	 * @return string
2199
+	 */
2200
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2201
+	{
2202
+		/** @type WPDB $wpdb */
2203
+		global $wpdb;
2204
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2205
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2206
+		$error_message = sprintf(
2207
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2208
+				'event_espresso'),
2209
+			$wpdb->last_error,
2210
+			$wpdb_method,
2211
+			json_encode($arguments_to_provide)
2212
+		);
2213
+		EE_System::instance()->initialize_addons();
2214
+		return $error_message;
2215
+	}
2216
+
2217
+
2218
+
2219
+	/**
2220
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2221
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2222
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2223
+	 * ..."
2224
+	 *
2225
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2226
+	 * @return string
2227
+	 */
2228
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2229
+	{
2230
+		return " FROM " . $model_query_info->get_full_join_sql() .
2231
+			   $model_query_info->get_where_sql() .
2232
+			   $model_query_info->get_group_by_sql() .
2233
+			   $model_query_info->get_having_sql() .
2234
+			   $model_query_info->get_order_by_sql() .
2235
+			   $model_query_info->get_limit_sql();
2236
+	}
2237
+
2238
+
2239
+
2240
+	/**
2241
+	 * Set to easily debug the next X queries ran from this model.
2242
+	 *
2243
+	 * @param int $count
2244
+	 */
2245
+	public function show_next_x_db_queries($count = 1)
2246
+	{
2247
+		$this->_show_next_x_db_queries = $count;
2248
+	}
2249
+
2250
+
2251
+
2252
+	/**
2253
+	 * @param $sql_query
2254
+	 */
2255
+	public function show_db_query_if_previously_requested($sql_query)
2256
+	{
2257
+		if ($this->_show_next_x_db_queries > 0) {
2258
+			echo $sql_query;
2259
+			$this->_show_next_x_db_queries--;
2260
+		}
2261
+	}
2262
+
2263
+
2264
+
2265
+	/**
2266
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2267
+	 * There are the 3 cases:
2268
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2269
+	 * $otherModelObject has no ID, it is first saved.
2270
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2271
+	 * has no ID, it is first saved.
2272
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2273
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2274
+	 * join table
2275
+	 *
2276
+	 * @param        EE_Base_Class                     /int $thisModelObject
2277
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2278
+	 * @param string $relationName                     , key in EEM_Base::_relations
2279
+	 *                                                 an attendee to a group, you also want to specify which role they
2280
+	 *                                                 will have in that group. So you would use this parameter to
2281
+	 *                                                 specify array('role-column-name'=>'role-id')
2282
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2283
+	 *                                                 to for relation to methods that allow you to further specify
2284
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2285
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2286
+	 *                                                 because these will be inserted in any new rows created as well.
2287
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2288
+	 * @throws \EE_Error
2289
+	 */
2290
+	public function add_relationship_to(
2291
+		$id_or_obj,
2292
+		$other_model_id_or_obj,
2293
+		$relationName,
2294
+		$extra_join_model_fields_n_values = array()
2295
+	) {
2296
+		$relation_obj = $this->related_settings_for($relationName);
2297
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2298
+	}
2299
+
2300
+
2301
+
2302
+	/**
2303
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2304
+	 * There are the 3 cases:
2305
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2306
+	 * error
2307
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2308
+	 * an error
2309
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2310
+	 *
2311
+	 * @param        EE_Base_Class /int $id_or_obj
2312
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2313
+	 * @param string $relationName key in EEM_Base::_relations
2314
+	 * @return boolean of success
2315
+	 * @throws \EE_Error
2316
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2317
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2318
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2319
+	 *                             because these will be inserted in any new rows created as well.
2320
+	 */
2321
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2322
+	{
2323
+		$relation_obj = $this->related_settings_for($relationName);
2324
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2325
+	}
2326
+
2327
+
2328
+
2329
+	/**
2330
+	 * @param mixed           $id_or_obj
2331
+	 * @param string          $relationName
2332
+	 * @param array           $where_query_params
2333
+	 * @param EE_Base_Class[] objects to which relations were removed
2334
+	 * @return \EE_Base_Class[]
2335
+	 * @throws \EE_Error
2336
+	 */
2337
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2338
+	{
2339
+		$relation_obj = $this->related_settings_for($relationName);
2340
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2341
+	}
2342
+
2343
+
2344
+
2345
+	/**
2346
+	 * Gets all the related items of the specified $model_name, using $query_params.
2347
+	 * Note: by default, we remove the "default query params"
2348
+	 * because we want to get even deleted items etc.
2349
+	 *
2350
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2351
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2352
+	 * @param array  $query_params like EEM_Base::get_all
2353
+	 * @return EE_Base_Class[]
2354
+	 * @throws \EE_Error
2355
+	 */
2356
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2357
+	{
2358
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2359
+		$relation_settings = $this->related_settings_for($model_name);
2360
+		return $relation_settings->get_all_related($model_obj, $query_params);
2361
+	}
2362
+
2363
+
2364
+
2365
+	/**
2366
+	 * Deletes all the model objects across the relation indicated by $model_name
2367
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2368
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2369
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2370
+	 *
2371
+	 * @param EE_Base_Class|int|string $id_or_obj
2372
+	 * @param string                   $model_name
2373
+	 * @param array                    $query_params
2374
+	 * @return int how many deleted
2375
+	 * @throws \EE_Error
2376
+	 */
2377
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2378
+	{
2379
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2380
+		$relation_settings = $this->related_settings_for($model_name);
2381
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2382
+	}
2383
+
2384
+
2385
+
2386
+	/**
2387
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2388
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2389
+	 * the model objects can't be hard deleted because of blocking related model objects,
2390
+	 * just does a soft-delete on them instead.
2391
+	 *
2392
+	 * @param EE_Base_Class|int|string $id_or_obj
2393
+	 * @param string                   $model_name
2394
+	 * @param array                    $query_params
2395
+	 * @return int how many deleted
2396
+	 * @throws \EE_Error
2397
+	 */
2398
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2399
+	{
2400
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2401
+		$relation_settings = $this->related_settings_for($model_name);
2402
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2403
+	}
2404
+
2405
+
2406
+
2407
+	/**
2408
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2409
+	 * unless otherwise specified in the $query_params
2410
+	 *
2411
+	 * @param        int             /EE_Base_Class $id_or_obj
2412
+	 * @param string $model_name     like 'Event', or 'Registration'
2413
+	 * @param array  $query_params   like EEM_Base::get_all's
2414
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2415
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2416
+	 *                               that by the setting $distinct to TRUE;
2417
+	 * @return int
2418
+	 * @throws \EE_Error
2419
+	 */
2420
+	public function count_related(
2421
+		$id_or_obj,
2422
+		$model_name,
2423
+		$query_params = array(),
2424
+		$field_to_count = null,
2425
+		$distinct = false
2426
+	) {
2427
+		$related_model = $this->get_related_model_obj($model_name);
2428
+		//we're just going to use the query params on the related model's normal get_all query,
2429
+		//except add a condition to say to match the current mod
2430
+		if ( ! isset($query_params['default_where_conditions'])) {
2431
+			$query_params['default_where_conditions'] = 'none';
2432
+		}
2433
+		$this_model_name = $this->get_this_model_name();
2434
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2435
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2436
+		return $related_model->count($query_params, $field_to_count, $distinct);
2437
+	}
2438
+
2439
+
2440
+
2441
+	/**
2442
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2443
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2444
+	 *
2445
+	 * @param        int           /EE_Base_Class $id_or_obj
2446
+	 * @param string $model_name   like 'Event', or 'Registration'
2447
+	 * @param array  $query_params like EEM_Base::get_all's
2448
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2449
+	 * @return float
2450
+	 * @throws \EE_Error
2451
+	 */
2452
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2453
+	{
2454
+		$related_model = $this->get_related_model_obj($model_name);
2455
+		if ( ! is_array($query_params)) {
2456
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2457
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2458
+					gettype($query_params)), '4.6.0');
2459
+			$query_params = array();
2460
+		}
2461
+		//we're just going to use the query params on the related model's normal get_all query,
2462
+		//except add a condition to say to match the current mod
2463
+		if ( ! isset($query_params['default_where_conditions'])) {
2464
+			$query_params['default_where_conditions'] = 'none';
2465
+		}
2466
+		$this_model_name = $this->get_this_model_name();
2467
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2468
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2469
+		return $related_model->sum($query_params, $field_to_sum);
2470
+	}
2471
+
2472
+
2473
+
2474
+	/**
2475
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2476
+	 * $modelObject
2477
+	 *
2478
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2479
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2480
+	 * @param array               $query_params     like EEM_Base::get_all's
2481
+	 * @return EE_Base_Class
2482
+	 * @throws \EE_Error
2483
+	 */
2484
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2485
+	{
2486
+		$query_params['limit'] = 1;
2487
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2488
+		if ($results) {
2489
+			return array_shift($results);
2490
+		} else {
2491
+			return null;
2492
+		}
2493
+	}
2494
+
2495
+
2496
+
2497
+	/**
2498
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2499
+	 *
2500
+	 * @return string
2501
+	 */
2502
+	public function get_this_model_name()
2503
+	{
2504
+		return str_replace("EEM_", "", get_class($this));
2505
+	}
2506
+
2507
+
2508
+
2509
+	/**
2510
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2511
+	 *
2512
+	 * @return EE_Any_Foreign_Model_Name_Field
2513
+	 * @throws EE_Error
2514
+	 */
2515
+	public function get_field_containing_related_model_name()
2516
+	{
2517
+		foreach ($this->field_settings(true) as $field) {
2518
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2519
+				$field_with_model_name = $field;
2520
+			}
2521
+		}
2522
+		if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2523
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2524
+				$this->get_this_model_name()));
2525
+		}
2526
+		return $field_with_model_name;
2527
+	}
2528
+
2529
+
2530
+
2531
+	/**
2532
+	 * Inserts a new entry into the database, for each table.
2533
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2534
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2535
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2536
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2537
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2538
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2539
+	 *
2540
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2541
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2542
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2543
+	 *                              of EEM_Base)
2544
+	 * @return int new primary key on main table that got inserted
2545
+	 * @throws EE_Error
2546
+	 */
2547
+	public function insert($field_n_values)
2548
+	{
2549
+		/**
2550
+		 * Filters the fields and their values before inserting an item using the models
2551
+		 *
2552
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2553
+		 * @param EEM_Base $model           the model used
2554
+		 */
2555
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2556
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2557
+			$main_table = $this->_get_main_table();
2558
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2559
+			if ($new_id !== false) {
2560
+				foreach ($this->_get_other_tables() as $other_table) {
2561
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2562
+				}
2563
+			}
2564
+			/**
2565
+			 * Done just after attempting to insert a new model object
2566
+			 *
2567
+			 * @param EEM_Base   $model           used
2568
+			 * @param array      $fields_n_values fields and their values
2569
+			 * @param int|string the              ID of the newly-inserted model object
2570
+			 */
2571
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2572
+			return $new_id;
2573
+		} else {
2574
+			return false;
2575
+		}
2576
+	}
2577
+
2578
+
2579
+
2580
+	/**
2581
+	 * Checks that the result would satisfy the unique indexes on this model
2582
+	 *
2583
+	 * @param array  $field_n_values
2584
+	 * @param string $action
2585
+	 * @return boolean
2586
+	 * @throws \EE_Error
2587
+	 */
2588
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2589
+	{
2590
+		foreach ($this->unique_indexes() as $index_name => $index) {
2591
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2592
+			if ($this->exists(array($uniqueness_where_params))) {
2593
+				EE_Error::add_error(
2594
+					sprintf(
2595
+						__(
2596
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2597
+							"event_espresso"
2598
+						),
2599
+						$action,
2600
+						$this->_get_class_name(),
2601
+						$index_name,
2602
+						implode(",", $index->field_names()),
2603
+						http_build_query($uniqueness_where_params)
2604
+					),
2605
+					__FILE__,
2606
+					__FUNCTION__,
2607
+					__LINE__
2608
+				);
2609
+				return false;
2610
+			}
2611
+		}
2612
+		return true;
2613
+	}
2614
+
2615
+
2616
+
2617
+	/**
2618
+	 * Checks the database for an item that conflicts (ie, if this item were
2619
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2620
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2621
+	 * can be either an EE_Base_Class or an array of fields n values
2622
+	 *
2623
+	 * @param EE_Base_Class|array $obj_or_fields_array
2624
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2625
+	 *                                                 when looking for conflicts
2626
+	 *                                                 (ie, if false, we ignore the model object's primary key
2627
+	 *                                                 when finding "conflicts". If true, it's also considered).
2628
+	 *                                                 Only works for INT primary key,
2629
+	 *                                                 STRING primary keys cannot be ignored
2630
+	 * @throws EE_Error
2631
+	 * @return EE_Base_Class|array
2632
+	 */
2633
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2634
+	{
2635
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2636
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2637
+		} elseif (is_array($obj_or_fields_array)) {
2638
+			$fields_n_values = $obj_or_fields_array;
2639
+		} else {
2640
+			throw new EE_Error(
2641
+				sprintf(
2642
+					__(
2643
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2644
+						"event_espresso"
2645
+					),
2646
+					get_class($this),
2647
+					$obj_or_fields_array
2648
+				)
2649
+			);
2650
+		}
2651
+		$query_params = array();
2652
+		if ($this->has_primary_key_field()
2653
+			&& ($include_primary_key
2654
+				|| $this->get_primary_key_field()
2655
+				   instanceof
2656
+				   EE_Primary_Key_String_Field)
2657
+			&& isset($fields_n_values[$this->primary_key_name()])
2658
+		) {
2659
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2660
+		}
2661
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2662
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2663
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2664
+		}
2665
+		//if there is nothing to base this search on, then we shouldn't find anything
2666
+		if (empty($query_params)) {
2667
+			return array();
2668
+		} else {
2669
+			return $this->get_one($query_params);
2670
+		}
2671
+	}
2672
+
2673
+
2674
+
2675
+	/**
2676
+	 * Like count, but is optimized and returns a boolean instead of an int
2677
+	 *
2678
+	 * @param array $query_params
2679
+	 * @return boolean
2680
+	 * @throws \EE_Error
2681
+	 */
2682
+	public function exists($query_params)
2683
+	{
2684
+		$query_params['limit'] = 1;
2685
+		return $this->count($query_params) > 0;
2686
+	}
2687
+
2688
+
2689
+
2690
+	/**
2691
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2692
+	 *
2693
+	 * @param int|string $id
2694
+	 * @return boolean
2695
+	 * @throws \EE_Error
2696
+	 */
2697
+	public function exists_by_ID($id)
2698
+	{
2699
+		return $this->exists(array('default_where_conditions' => 'none', array($this->primary_key_name() => $id)));
2700
+	}
2701
+
2702
+
2703
+
2704
+	/**
2705
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2706
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2707
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2708
+	 * on the main table)
2709
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2710
+	 * cases where we want to call it directly rather than via insert().
2711
+	 *
2712
+	 * @access   protected
2713
+	 * @param EE_Table_Base $table
2714
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2715
+	 *                                       float
2716
+	 * @param int           $new_id          for now we assume only int keys
2717
+	 * @throws EE_Error
2718
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2719
+	 * @return int ID of new row inserted, or FALSE on failure
2720
+	 */
2721
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2722
+	{
2723
+		global $wpdb;
2724
+		$insertion_col_n_values = array();
2725
+		$format_for_insertion = array();
2726
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2727
+		foreach ($fields_on_table as $field_name => $field_obj) {
2728
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2729
+			if ($field_obj->is_auto_increment()) {
2730
+				continue;
2731
+			}
2732
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2733
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2734
+			if ($prepared_value !== null) {
2735
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2736
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2737
+			}
2738
+		}
2739
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2740
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2741
+			//so add the fk to the main table as a column
2742
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2743
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2744
+		}
2745
+		//insert the new entry
2746
+		$result = $this->_do_wpdb_query('insert',
2747
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2748
+		if ($result === false) {
2749
+			return false;
2750
+		}
2751
+		//ok, now what do we return for the ID of the newly-inserted thing?
2752
+		if ($this->has_primary_key_field()) {
2753
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2754
+				return $wpdb->insert_id;
2755
+			} else {
2756
+				//it's not an auto-increment primary key, so
2757
+				//it must have been supplied
2758
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2759
+			}
2760
+		} else {
2761
+			//we can't return a  primary key because there is none. instead return
2762
+			//a unique string indicating this model
2763
+			return $this->get_index_primary_key_string($fields_n_values);
2764
+		}
2765
+	}
2766
+
2767
+
2768
+
2769
+	/**
2770
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2771
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2772
+	 * and there is no default, we pass it along. WPDB will take care of it)
2773
+	 *
2774
+	 * @param EE_Model_Field_Base $field_obj
2775
+	 * @param array               $fields_n_values
2776
+	 * @return mixed string|int|float depending on what the table column will be expecting
2777
+	 * @throws \EE_Error
2778
+	 */
2779
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2780
+	{
2781
+		//if this field doesn't allow nullable, don't allow it
2782
+		if ( ! $field_obj->is_nullable()
2783
+			 && (
2784
+				 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2785
+		) {
2786
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2787
+		}
2788
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2789
+			: null;
2790
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2791
+	}
2792
+
2793
+
2794
+
2795
+	/**
2796
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2797
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2798
+	 * the field's prepare_for_set() method.
2799
+	 *
2800
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2801
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2802
+	 *                                   top of file)
2803
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2804
+	 *                                   $value is a custom selection
2805
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2806
+	 */
2807
+	private function _prepare_value_for_use_in_db($value, $field)
2808
+	{
2809
+		if ($field && $field instanceof EE_Model_Field_Base) {
2810
+			switch ($this->_values_already_prepared_by_model_object) {
2811
+				/** @noinspection PhpMissingBreakStatementInspection */
2812
+				case self::not_prepared_by_model_object:
2813
+					$value = $field->prepare_for_set($value);
2814
+				//purposefully left out "return"
2815
+				case self::prepared_by_model_object:
2816
+					$value = $field->prepare_for_use_in_db($value);
2817
+				case self::prepared_for_use_in_db:
2818
+					//leave the value alone
2819
+			}
2820
+			return $value;
2821
+		} else {
2822
+			return $value;
2823
+		}
2824
+	}
2825
+
2826
+
2827
+
2828
+	/**
2829
+	 * Returns the main table on this model
2830
+	 *
2831
+	 * @return EE_Primary_Table
2832
+	 * @throws EE_Error
2833
+	 */
2834
+	protected function _get_main_table()
2835
+	{
2836
+		foreach ($this->_tables as $table) {
2837
+			if ($table instanceof EE_Primary_Table) {
2838
+				return $table;
2839
+			}
2840
+		}
2841
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2842
+			'event_espresso'), get_class($this)));
2843
+	}
2844
+
2845
+
2846
+
2847
+	/**
2848
+	 * table
2849
+	 * returns EE_Primary_Table table name
2850
+	 *
2851
+	 * @return string
2852
+	 * @throws \EE_Error
2853
+	 */
2854
+	public function table()
2855
+	{
2856
+		return $this->_get_main_table()->get_table_name();
2857
+	}
2858
+
2859
+
2860
+
2861
+	/**
2862
+	 * table
2863
+	 * returns first EE_Secondary_Table table name
2864
+	 *
2865
+	 * @return string
2866
+	 */
2867
+	public function second_table()
2868
+	{
2869
+		// grab second table from tables array
2870
+		$second_table = end($this->_tables);
2871
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2872
+	}
2873
+
2874
+
2875
+
2876
+	/**
2877
+	 * get_table_obj_by_alias
2878
+	 * returns table name given it's alias
2879
+	 *
2880
+	 * @param string $table_alias
2881
+	 * @return EE_Primary_Table | EE_Secondary_Table
2882
+	 */
2883
+	public function get_table_obj_by_alias($table_alias = '')
2884
+	{
2885
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
2886
+	}
2887
+
2888
+
2889
+
2890
+	/**
2891
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
2892
+	 *
2893
+	 * @return EE_Secondary_Table[]
2894
+	 */
2895
+	protected function _get_other_tables()
2896
+	{
2897
+		$other_tables = array();
2898
+		foreach ($this->_tables as $table_alias => $table) {
2899
+			if ($table instanceof EE_Secondary_Table) {
2900
+				$other_tables[$table_alias] = $table;
2901
+			}
2902
+		}
2903
+		return $other_tables;
2904
+	}
2905
+
2906
+
2907
+
2908
+	/**
2909
+	 * Finds all the fields that correspond to the given table
2910
+	 *
2911
+	 * @param string $table_alias , array key in EEM_Base::_tables
2912
+	 * @return EE_Model_Field_Base[]
2913
+	 */
2914
+	public function _get_fields_for_table($table_alias)
2915
+	{
2916
+		return $this->_fields[$table_alias];
2917
+	}
2918
+
2919
+
2920
+
2921
+	/**
2922
+	 * Recurses through all the where parameters, and finds all the related models we'll need
2923
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
2924
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
2925
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
2926
+	 * related Registration, Transaction, and Payment models.
2927
+	 *
2928
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
2929
+	 * @return EE_Model_Query_Info_Carrier
2930
+	 * @throws \EE_Error
2931
+	 */
2932
+	public function _extract_related_models_from_query($query_params)
2933
+	{
2934
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
2935
+		if (array_key_exists(0, $query_params)) {
2936
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
2937
+		}
2938
+		if (array_key_exists('group_by', $query_params)) {
2939
+			if (is_array($query_params['group_by'])) {
2940
+				$this->_extract_related_models_from_sub_params_array_values(
2941
+					$query_params['group_by'],
2942
+					$query_info_carrier,
2943
+					'group_by'
2944
+				);
2945
+			} elseif ( ! empty ($query_params['group_by'])) {
2946
+				$this->_extract_related_model_info_from_query_param(
2947
+					$query_params['group_by'],
2948
+					$query_info_carrier,
2949
+					'group_by'
2950
+				);
2951
+			}
2952
+		}
2953
+		if (array_key_exists('having', $query_params)) {
2954
+			$this->_extract_related_models_from_sub_params_array_keys(
2955
+				$query_params[0],
2956
+				$query_info_carrier,
2957
+				'having'
2958
+			);
2959
+		}
2960
+		if (array_key_exists('order_by', $query_params)) {
2961
+			if (is_array($query_params['order_by'])) {
2962
+				$this->_extract_related_models_from_sub_params_array_keys(
2963
+					$query_params['order_by'],
2964
+					$query_info_carrier,
2965
+					'order_by'
2966
+				);
2967
+			} elseif ( ! empty($query_params['order_by'])) {
2968
+				$this->_extract_related_model_info_from_query_param(
2969
+					$query_params['order_by'],
2970
+					$query_info_carrier,
2971
+					'order_by'
2972
+				);
2973
+			}
2974
+		}
2975
+		if (array_key_exists('force_join', $query_params)) {
2976
+			$this->_extract_related_models_from_sub_params_array_values(
2977
+				$query_params['force_join'],
2978
+				$query_info_carrier,
2979
+				'force_join'
2980
+			);
2981
+		}
2982
+		return $query_info_carrier;
2983
+	}
2984
+
2985
+
2986
+
2987
+	/**
2988
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
2989
+	 *
2990
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
2991
+	 *                                                      $query_params['having']
2992
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
2993
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
2994
+	 * @throws EE_Error
2995
+	 * @return \EE_Model_Query_Info_Carrier
2996
+	 */
2997
+	private function _extract_related_models_from_sub_params_array_keys(
2998
+		$sub_query_params,
2999
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3000
+		$query_param_type
3001
+	) {
3002
+		if ( ! empty($sub_query_params)) {
3003
+			$sub_query_params = (array)$sub_query_params;
3004
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3005
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3006
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3007
+					$query_param_type);
3008
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3009
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3010
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3011
+				//of array('Registration.TXN_ID'=>23)
3012
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3013
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3014
+					if ( ! is_array($possibly_array_of_params)) {
3015
+						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'))",
3016
+							"event_espresso"),
3017
+							$param, $possibly_array_of_params));
3018
+					} else {
3019
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3020
+							$model_query_info_carrier, $query_param_type);
3021
+					}
3022
+				} elseif ($query_param_type === 0 //ie WHERE
3023
+						  && is_array($possibly_array_of_params)
3024
+						  && isset($possibly_array_of_params[2])
3025
+						  && $possibly_array_of_params[2] == true
3026
+				) {
3027
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3028
+					//indicating that $possible_array_of_params[1] is actually a field name,
3029
+					//from which we should extract query parameters!
3030
+					if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3031
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3032
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3033
+					}
3034
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3035
+						$model_query_info_carrier, $query_param_type);
3036
+				}
3037
+			}
3038
+		}
3039
+		return $model_query_info_carrier;
3040
+	}
3041
+
3042
+
3043
+
3044
+	/**
3045
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3046
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3047
+	 *
3048
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3049
+	 *                                                      $query_params['having']
3050
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3051
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3052
+	 * @throws EE_Error
3053
+	 * @return \EE_Model_Query_Info_Carrier
3054
+	 */
3055
+	private function _extract_related_models_from_sub_params_array_values(
3056
+		$sub_query_params,
3057
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3058
+		$query_param_type
3059
+	) {
3060
+		if ( ! empty($sub_query_params)) {
3061
+			if ( ! is_array($sub_query_params)) {
3062
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3063
+					$sub_query_params));
3064
+			}
3065
+			foreach ($sub_query_params as $param) {
3066
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3067
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3068
+					$query_param_type);
3069
+			}
3070
+		}
3071
+		return $model_query_info_carrier;
3072
+	}
3073
+
3074
+
3075
+
3076
+	/**
3077
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3078
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3079
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3080
+	 * but use them in a different order. Eg, we need to know what models we are querying
3081
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3082
+	 * other models before we can finalize the where clause SQL.
3083
+	 *
3084
+	 * @param array $query_params
3085
+	 * @throws EE_Error
3086
+	 * @return EE_Model_Query_Info_Carrier
3087
+	 */
3088
+	public function _create_model_query_info_carrier($query_params)
3089
+	{
3090
+		if ( ! is_array($query_params)) {
3091
+			EE_Error::doing_it_wrong(
3092
+				'EEM_Base::_create_model_query_info_carrier',
3093
+				sprintf(
3094
+					__(
3095
+						'$query_params should be an array, you passed a variable of type %s',
3096
+						'event_espresso'
3097
+					),
3098
+					gettype($query_params)
3099
+				),
3100
+				'4.6.0'
3101
+			);
3102
+			$query_params = array();
3103
+		}
3104
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3105
+		//first check if we should alter the query to account for caps or not
3106
+		//because the caps might require us to do extra joins
3107
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3108
+			$query_params[0] = $where_query_params = array_replace_recursive(
3109
+				$where_query_params,
3110
+				$this->caps_where_conditions(
3111
+					$query_params['caps']
3112
+				)
3113
+			);
3114
+		}
3115
+		$query_object = $this->_extract_related_models_from_query($query_params);
3116
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3117
+		foreach ($where_query_params as $key => $value) {
3118
+			if (is_int($key)) {
3119
+				throw new EE_Error(
3120
+					sprintf(
3121
+						__(
3122
+							"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.",
3123
+							"event_espresso"
3124
+						),
3125
+						$key,
3126
+						var_export($value, true),
3127
+						var_export($query_params, true),
3128
+						get_class($this)
3129
+					)
3130
+				);
3131
+			}
3132
+		}
3133
+		if (
3134
+			array_key_exists('default_where_conditions', $query_params)
3135
+			&& ! empty($query_params['default_where_conditions'])
3136
+		) {
3137
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3138
+		} else {
3139
+			$use_default_where_conditions = 'all';
3140
+		}
3141
+		$where_query_params = array_merge(
3142
+			$this->_get_default_where_conditions_for_models_in_query(
3143
+				$query_object,
3144
+				$use_default_where_conditions,
3145
+				$where_query_params
3146
+			),
3147
+			$where_query_params
3148
+		);
3149
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3150
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3151
+		// So we need to setup a subquery and use that for the main join.
3152
+		// Note for now this only works on the primary table for the model.
3153
+		// So for instance, you could set the limit array like this:
3154
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3155
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3156
+			$query_object->set_main_model_join_sql(
3157
+				$this->_construct_limit_join_select(
3158
+					$query_params['on_join_limit'][0],
3159
+					$query_params['on_join_limit'][1]
3160
+				)
3161
+			);
3162
+		}
3163
+		//set limit
3164
+		if (array_key_exists('limit', $query_params)) {
3165
+			if (is_array($query_params['limit'])) {
3166
+				if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3167
+					$e = sprintf(
3168
+						__(
3169
+							"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)",
3170
+							"event_espresso"
3171
+						),
3172
+						http_build_query($query_params['limit'])
3173
+					);
3174
+					throw new EE_Error($e . "|" . $e);
3175
+				}
3176
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3177
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3178
+			} elseif ( ! empty ($query_params['limit'])) {
3179
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3180
+			}
3181
+		}
3182
+		//set order by
3183
+		if (array_key_exists('order_by', $query_params)) {
3184
+			if (is_array($query_params['order_by'])) {
3185
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3186
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3187
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3188
+				if (array_key_exists('order', $query_params)) {
3189
+					throw new EE_Error(
3190
+						sprintf(
3191
+							__(
3192
+								"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 ",
3193
+								"event_espresso"
3194
+							),
3195
+							get_class($this),
3196
+							implode(", ", array_keys($query_params['order_by'])),
3197
+							implode(", ", $query_params['order_by']),
3198
+							$query_params['order']
3199
+						)
3200
+					);
3201
+				}
3202
+				$this->_extract_related_models_from_sub_params_array_keys(
3203
+					$query_params['order_by'],
3204
+					$query_object,
3205
+					'order_by'
3206
+				);
3207
+				//assume it's an array of fields to order by
3208
+				$order_array = array();
3209
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3210
+					$order = $this->_extract_order($order);
3211
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3212
+				}
3213
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3214
+			} elseif ( ! empty ($query_params['order_by'])) {
3215
+				$this->_extract_related_model_info_from_query_param(
3216
+					$query_params['order_by'],
3217
+					$query_object,
3218
+					'order',
3219
+					$query_params['order_by']
3220
+				);
3221
+				$order = isset($query_params['order'])
3222
+					? $this->_extract_order($query_params['order'])
3223
+					: 'DESC';
3224
+				$query_object->set_order_by_sql(
3225
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3226
+				);
3227
+			}
3228
+		}
3229
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3230
+		if ( ! array_key_exists('order_by', $query_params)
3231
+			 && array_key_exists('order', $query_params)
3232
+			 && ! empty($query_params['order'])
3233
+		) {
3234
+			$pk_field = $this->get_primary_key_field();
3235
+			$order = $this->_extract_order($query_params['order']);
3236
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3237
+		}
3238
+		//set group by
3239
+		if (array_key_exists('group_by', $query_params)) {
3240
+			if (is_array($query_params['group_by'])) {
3241
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3242
+				$group_by_array = array();
3243
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3244
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3245
+				}
3246
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3247
+			} elseif ( ! empty ($query_params['group_by'])) {
3248
+				$query_object->set_group_by_sql(
3249
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3250
+				);
3251
+			}
3252
+		}
3253
+		//set having
3254
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3255
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3256
+		}
3257
+		//now, just verify they didn't pass anything wack
3258
+		foreach ($query_params as $query_key => $query_value) {
3259
+			if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3260
+				throw new EE_Error(
3261
+					sprintf(
3262
+						__(
3263
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3264
+							'event_espresso'
3265
+						),
3266
+						$query_key,
3267
+						get_class($this),
3268 3268
 //						print_r( $this->_allowed_query_params, TRUE )
3269
-                        implode(',', $this->_allowed_query_params)
3270
-                    )
3271
-                );
3272
-            }
3273
-        }
3274
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3275
-        if (empty($main_model_join_sql)) {
3276
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3277
-        }
3278
-        return $query_object;
3279
-    }
3280
-
3281
-
3282
-
3283
-    /**
3284
-     * Gets the where conditions that should be imposed on the query based on the
3285
-     * context (eg reading frontend, backend, edit or delete).
3286
-     *
3287
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3288
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3289
-     * @throws \EE_Error
3290
-     */
3291
-    public function caps_where_conditions($context = self::caps_read)
3292
-    {
3293
-        EEM_Base::verify_is_valid_cap_context($context);
3294
-        $cap_where_conditions = array();
3295
-        $cap_restrictions = $this->caps_missing($context);
3296
-        /**
3297
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3298
-         */
3299
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3300
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3301
-                $restriction_if_no_cap->get_default_where_conditions());
3302
-        }
3303
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3304
-            $cap_restrictions);
3305
-    }
3306
-
3307
-
3308
-
3309
-    /**
3310
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3311
-     * otherwise throws an exception
3312
-     *
3313
-     * @param string $should_be_order_string
3314
-     * @return string either ASC, asc, DESC or desc
3315
-     * @throws EE_Error
3316
-     */
3317
-    private function _extract_order($should_be_order_string)
3318
-    {
3319
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3320
-            return $should_be_order_string;
3321
-        } else {
3322
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3323
-                "event_espresso"), get_class($this), $should_be_order_string));
3324
-        }
3325
-    }
3326
-
3327
-
3328
-
3329
-    /**
3330
-     * Looks at all the models which are included in this query, and asks each
3331
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3332
-     * so they can be merged
3333
-     *
3334
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3335
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3336
-     *                                                                  'none' means NO default where conditions will
3337
-     *                                                                  be used AT ALL during this query.
3338
-     *                                                                  'other_models_only' means default where
3339
-     *                                                                  conditions from other models will be used, but
3340
-     *                                                                  not for this primary model. 'all', the default,
3341
-     *                                                                  means default where conditions will apply as
3342
-     *                                                                  normal
3343
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3344
-     * @throws EE_Error
3345
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3346
-     */
3347
-    private function _get_default_where_conditions_for_models_in_query(
3348
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3349
-        $use_default_where_conditions = 'all',
3350
-        $where_query_params = array()
3351
-    ) {
3352
-        $allowed_used_default_where_conditions_values = array(
3353
-            'all',
3354
-            'this_model_only',
3355
-            'other_models_only',
3356
-            'minimum',
3357
-            'none',
3358
-        );
3359
-        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3360
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3361
-                "event_espresso"), $use_default_where_conditions,
3362
-                implode(", ", $allowed_used_default_where_conditions_values)));
3363
-        }
3364
-        $universal_query_params = array();
3365
-        if ($use_default_where_conditions === 'all' || $use_default_where_conditions === 'this_model_only') {
3366
-            $universal_query_params = $this->_get_default_where_conditions();
3367
-        } else if ($use_default_where_conditions === 'minimum') {
3368
-            $universal_query_params = $this->_get_minimum_where_conditions();
3369
-        }
3370
-        if (in_array($use_default_where_conditions, array('all', 'other_models_only'))) {
3371
-            foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3372
-                $related_model = $this->get_related_model_obj($model_name);
3373
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3374
-                $overrides = $this->_override_defaults_or_make_null_friendly(
3375
-                    $related_model_universal_where_params,
3376
-                    $where_query_params,
3377
-                    $related_model,
3378
-                    $model_relation_path
3379
-                );
3380
-                $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3381
-                    $universal_query_params,
3382
-                    $overrides
3383
-                );
3384
-            }
3385
-        }
3386
-        return $universal_query_params;
3387
-    }
3388
-
3389
-
3390
-
3391
-    /**
3392
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3393
-     * then we also add a special where condition which allows for that model's primary key
3394
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3395
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3396
-     *
3397
-     * @param array    $default_where_conditions
3398
-     * @param array    $provided_where_conditions
3399
-     * @param EEM_Base $model
3400
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3401
-     * @return array like EEM_Base::get_all's $query_params[0]
3402
-     * @throws \EE_Error
3403
-     */
3404
-    private function _override_defaults_or_make_null_friendly(
3405
-        $default_where_conditions,
3406
-        $provided_where_conditions,
3407
-        $model,
3408
-        $model_relation_path
3409
-    ) {
3410
-        $null_friendly_where_conditions = array();
3411
-        $none_overridden = true;
3412
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3413
-        foreach ($default_where_conditions as $key => $val) {
3414
-            if (isset($provided_where_conditions[$key])) {
3415
-                $none_overridden = false;
3416
-            } else {
3417
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3418
-            }
3419
-        }
3420
-        if ($none_overridden && $default_where_conditions) {
3421
-            if ($model->has_primary_key_field()) {
3422
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3423
-                                                                                . "."
3424
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3425
-            }/*else{
3269
+						implode(',', $this->_allowed_query_params)
3270
+					)
3271
+				);
3272
+			}
3273
+		}
3274
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3275
+		if (empty($main_model_join_sql)) {
3276
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3277
+		}
3278
+		return $query_object;
3279
+	}
3280
+
3281
+
3282
+
3283
+	/**
3284
+	 * Gets the where conditions that should be imposed on the query based on the
3285
+	 * context (eg reading frontend, backend, edit or delete).
3286
+	 *
3287
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3288
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3289
+	 * @throws \EE_Error
3290
+	 */
3291
+	public function caps_where_conditions($context = self::caps_read)
3292
+	{
3293
+		EEM_Base::verify_is_valid_cap_context($context);
3294
+		$cap_where_conditions = array();
3295
+		$cap_restrictions = $this->caps_missing($context);
3296
+		/**
3297
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3298
+		 */
3299
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3300
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3301
+				$restriction_if_no_cap->get_default_where_conditions());
3302
+		}
3303
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3304
+			$cap_restrictions);
3305
+	}
3306
+
3307
+
3308
+
3309
+	/**
3310
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3311
+	 * otherwise throws an exception
3312
+	 *
3313
+	 * @param string $should_be_order_string
3314
+	 * @return string either ASC, asc, DESC or desc
3315
+	 * @throws EE_Error
3316
+	 */
3317
+	private function _extract_order($should_be_order_string)
3318
+	{
3319
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3320
+			return $should_be_order_string;
3321
+		} else {
3322
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3323
+				"event_espresso"), get_class($this), $should_be_order_string));
3324
+		}
3325
+	}
3326
+
3327
+
3328
+
3329
+	/**
3330
+	 * Looks at all the models which are included in this query, and asks each
3331
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3332
+	 * so they can be merged
3333
+	 *
3334
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3335
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3336
+	 *                                                                  'none' means NO default where conditions will
3337
+	 *                                                                  be used AT ALL during this query.
3338
+	 *                                                                  'other_models_only' means default where
3339
+	 *                                                                  conditions from other models will be used, but
3340
+	 *                                                                  not for this primary model. 'all', the default,
3341
+	 *                                                                  means default where conditions will apply as
3342
+	 *                                                                  normal
3343
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3344
+	 * @throws EE_Error
3345
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3346
+	 */
3347
+	private function _get_default_where_conditions_for_models_in_query(
3348
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3349
+		$use_default_where_conditions = 'all',
3350
+		$where_query_params = array()
3351
+	) {
3352
+		$allowed_used_default_where_conditions_values = array(
3353
+			'all',
3354
+			'this_model_only',
3355
+			'other_models_only',
3356
+			'minimum',
3357
+			'none',
3358
+		);
3359
+		if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3360
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3361
+				"event_espresso"), $use_default_where_conditions,
3362
+				implode(", ", $allowed_used_default_where_conditions_values)));
3363
+		}
3364
+		$universal_query_params = array();
3365
+		if ($use_default_where_conditions === 'all' || $use_default_where_conditions === 'this_model_only') {
3366
+			$universal_query_params = $this->_get_default_where_conditions();
3367
+		} else if ($use_default_where_conditions === 'minimum') {
3368
+			$universal_query_params = $this->_get_minimum_where_conditions();
3369
+		}
3370
+		if (in_array($use_default_where_conditions, array('all', 'other_models_only'))) {
3371
+			foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3372
+				$related_model = $this->get_related_model_obj($model_name);
3373
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3374
+				$overrides = $this->_override_defaults_or_make_null_friendly(
3375
+					$related_model_universal_where_params,
3376
+					$where_query_params,
3377
+					$related_model,
3378
+					$model_relation_path
3379
+				);
3380
+				$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3381
+					$universal_query_params,
3382
+					$overrides
3383
+				);
3384
+			}
3385
+		}
3386
+		return $universal_query_params;
3387
+	}
3388
+
3389
+
3390
+
3391
+	/**
3392
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3393
+	 * then we also add a special where condition which allows for that model's primary key
3394
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3395
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3396
+	 *
3397
+	 * @param array    $default_where_conditions
3398
+	 * @param array    $provided_where_conditions
3399
+	 * @param EEM_Base $model
3400
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3401
+	 * @return array like EEM_Base::get_all's $query_params[0]
3402
+	 * @throws \EE_Error
3403
+	 */
3404
+	private function _override_defaults_or_make_null_friendly(
3405
+		$default_where_conditions,
3406
+		$provided_where_conditions,
3407
+		$model,
3408
+		$model_relation_path
3409
+	) {
3410
+		$null_friendly_where_conditions = array();
3411
+		$none_overridden = true;
3412
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3413
+		foreach ($default_where_conditions as $key => $val) {
3414
+			if (isset($provided_where_conditions[$key])) {
3415
+				$none_overridden = false;
3416
+			} else {
3417
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3418
+			}
3419
+		}
3420
+		if ($none_overridden && $default_where_conditions) {
3421
+			if ($model->has_primary_key_field()) {
3422
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3423
+																				. "."
3424
+																				. $model->primary_key_name()] = array('IS NULL');
3425
+			}/*else{
3426 3426
 				//@todo NO PK, use other defaults
3427 3427
 			}*/
3428
-        }
3429
-        return $null_friendly_where_conditions;
3430
-    }
3431
-
3432
-
3433
-
3434
-    /**
3435
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3436
-     * default where conditions on all get_all, update, and delete queries done by this model.
3437
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3438
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3439
-     *
3440
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3441
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3442
-     */
3443
-    private function _get_default_where_conditions($model_relation_path = null)
3444
-    {
3445
-        if ($this->_ignore_where_strategy) {
3446
-            return array();
3447
-        }
3448
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3449
-    }
3450
-
3451
-
3452
-
3453
-    /**
3454
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3455
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3456
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3457
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3458
-     * Similar to _get_default_where_conditions
3459
-     *
3460
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3461
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3462
-     */
3463
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3464
-    {
3465
-        if ($this->_ignore_where_strategy) {
3466
-            return array();
3467
-        }
3468
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3469
-    }
3470
-
3471
-
3472
-
3473
-    /**
3474
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3475
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3476
-     *
3477
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3478
-     * @return string
3479
-     * @throws \EE_Error
3480
-     */
3481
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3482
-    {
3483
-        $selects = $this->_get_columns_to_select_for_this_model();
3484
-        foreach (
3485
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3486
-            $name_of_other_model_included
3487
-        ) {
3488
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3489
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3490
-            foreach ($other_model_selects as $key => $value) {
3491
-                $selects[] = $value;
3492
-            }
3493
-        }
3494
-        return implode(", ", $selects);
3495
-    }
3496
-
3497
-
3498
-
3499
-    /**
3500
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3501
-     * So that's going to be the columns for all the fields on the model
3502
-     *
3503
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3504
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3505
-     */
3506
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3507
-    {
3508
-        $fields = $this->field_settings();
3509
-        $selects = array();
3510
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3511
-            $this->get_this_model_name());
3512
-        foreach ($fields as $field_obj) {
3513
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3514
-                         . $field_obj->get_table_alias()
3515
-                         . "."
3516
-                         . $field_obj->get_table_column()
3517
-                         . " AS '"
3518
-                         . $table_alias_with_model_relation_chain_prefix
3519
-                         . $field_obj->get_table_alias()
3520
-                         . "."
3521
-                         . $field_obj->get_table_column()
3522
-                         . "'";
3523
-        }
3524
-        //make sure we are also getting the PKs of each table
3525
-        $tables = $this->get_tables();
3526
-        if (count($tables) > 1) {
3527
-            foreach ($tables as $table_obj) {
3528
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3529
-                                       . $table_obj->get_fully_qualified_pk_column();
3530
-                if ( ! in_array($qualified_pk_column, $selects)) {
3531
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3532
-                }
3533
-            }
3534
-        }
3535
-        return $selects;
3536
-    }
3537
-
3538
-
3539
-
3540
-    /**
3541
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3542
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3543
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3544
-     * SQL for joining, and the data types
3545
-     *
3546
-     * @param null|string                 $original_query_param
3547
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3548
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3549
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3550
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3551
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3552
-     *                                                          or 'Registration's
3553
-     * @param string                      $original_query_param what it originally was (eg
3554
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3555
-     *                                                          matches $query_param
3556
-     * @throws EE_Error
3557
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3558
-     */
3559
-    private function _extract_related_model_info_from_query_param(
3560
-        $query_param,
3561
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3562
-        $query_param_type,
3563
-        $original_query_param = null
3564
-    ) {
3565
-        if ($original_query_param === null) {
3566
-            $original_query_param = $query_param;
3567
-        }
3568
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3569
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3570
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3571
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3572
-        //check to see if we have a field on this model
3573
-        $this_model_fields = $this->field_settings(true);
3574
-        if (array_key_exists($query_param, $this_model_fields)) {
3575
-            if ($allow_fields) {
3576
-                return;
3577
-            } else {
3578
-                throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3579
-                    "event_espresso"),
3580
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3581
-            }
3582
-        } //check if this is a special logic query param
3583
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3584
-            if ($allow_logic_query_params) {
3585
-                return;
3586
-            } else {
3587
-                throw new EE_Error(
3588
-                    sprintf(
3589
-                        __('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',
3590
-                            'event_espresso'),
3591
-                        implode('", "', $this->_logic_query_param_keys),
3592
-                        $query_param,
3593
-                        get_class($this),
3594
-                        '<br />',
3595
-                        "\t"
3596
-                        . ' $passed_in_query_info = <pre>'
3597
-                        . print_r($passed_in_query_info, true)
3598
-                        . '</pre>'
3599
-                        . "\n\t"
3600
-                        . ' $query_param_type = '
3601
-                        . $query_param_type
3602
-                        . "\n\t"
3603
-                        . ' $original_query_param = '
3604
-                        . $original_query_param
3605
-                    )
3606
-                );
3607
-            }
3608
-        } //check if it's a custom selection
3609
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3610
-            return;
3611
-        }
3612
-        //check if has a model name at the beginning
3613
-        //and
3614
-        //check if it's a field on a related model
3615
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3616
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3617
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3618
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3619
-                if ($query_param === '') {
3620
-                    //nothing left to $query_param
3621
-                    //we should actually end in a field name, not a model like this!
3622
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3623
-                        "event_espresso"),
3624
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3625
-                } else {
3626
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3627
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3628
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3629
-                    return;
3630
-                }
3631
-            } elseif ($query_param === $valid_related_model_name) {
3632
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3633
-                return;
3634
-            }
3635
-        }
3636
-        //ok so $query_param didn't start with a model name
3637
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3638
-        //it's wack, that's what it is
3639
-        throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3640
-            "event_espresso"),
3641
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3642
-    }
3643
-
3644
-
3645
-
3646
-    /**
3647
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3648
-     * and store it on $passed_in_query_info
3649
-     *
3650
-     * @param string                      $model_name
3651
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3652
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3653
-     *                                                          model and $model_name. Eg, if we are querying Event,
3654
-     *                                                          and are adding a join to 'Payment' with the original
3655
-     *                                                          query param key
3656
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3657
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3658
-     *                                                          Payment wants to add default query params so that it
3659
-     *                                                          will know what models to prepend onto its default query
3660
-     *                                                          params or in case it wants to rename tables (in case
3661
-     *                                                          there are multiple joins to the same table)
3662
-     * @return void
3663
-     * @throws \EE_Error
3664
-     */
3665
-    private function _add_join_to_model(
3666
-        $model_name,
3667
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3668
-        $original_query_param
3669
-    ) {
3670
-        $relation_obj = $this->related_settings_for($model_name);
3671
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3672
-        //check if the relation is HABTM, because then we're essentially doing two joins
3673
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3674
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3675
-            $join_model_obj = $relation_obj->get_join_model();
3676
-            //replace the model specified with the join model for this relation chain, whi
3677
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3678
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3679
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3680
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3681
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3682
-            $passed_in_query_info->merge($new_query_info);
3683
-        }
3684
-        //now just join to the other table pointed to by the relation object, and add its data types
3685
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3686
-            array($model_relation_chain => $model_name),
3687
-            $relation_obj->get_join_statement($model_relation_chain));
3688
-        $passed_in_query_info->merge($new_query_info);
3689
-    }
3690
-
3691
-
3692
-
3693
-    /**
3694
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3695
-     *
3696
-     * @param array $where_params like EEM_Base::get_all
3697
-     * @return string of SQL
3698
-     * @throws \EE_Error
3699
-     */
3700
-    private function _construct_where_clause($where_params)
3701
-    {
3702
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3703
-        if ($SQL) {
3704
-            return " WHERE " . $SQL;
3705
-        } else {
3706
-            return '';
3707
-        }
3708
-    }
3709
-
3710
-
3711
-
3712
-    /**
3713
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3714
-     * and should be passed HAVING parameters, not WHERE parameters
3715
-     *
3716
-     * @param array $having_params
3717
-     * @return string
3718
-     * @throws \EE_Error
3719
-     */
3720
-    private function _construct_having_clause($having_params)
3721
-    {
3722
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3723
-        if ($SQL) {
3724
-            return " HAVING " . $SQL;
3725
-        } else {
3726
-            return '';
3727
-        }
3728
-    }
3729
-
3730
-
3731
-
3732
-    /**
3733
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3734
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3735
-     * EEM_Attendee.
3736
-     *
3737
-     * @param string $field_name
3738
-     * @param string $model_name
3739
-     * @return EE_Model_Field_Base
3740
-     * @throws EE_Error
3741
-     */
3742
-    protected function _get_field_on_model($field_name, $model_name)
3743
-    {
3744
-        $model_class = 'EEM_' . $model_name;
3745
-        $model_filepath = $model_class . ".model.php";
3746
-        if (is_readable($model_filepath)) {
3747
-            require_once($model_filepath);
3748
-            $model_instance = call_user_func($model_name . "::instance");
3749
-            /* @var $model_instance EEM_Base */
3750
-            return $model_instance->field_settings_for($field_name);
3751
-        } else {
3752
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3753
-                'event_espresso'), $model_name, $model_class, $model_filepath));
3754
-        }
3755
-    }
3756
-
3757
-
3758
-
3759
-    /**
3760
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3761
-     * Event_Meta.meta_value = 'foo'))"
3762
-     *
3763
-     * @param array  $where_params see EEM_Base::get_all for documentation
3764
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3765
-     * @throws EE_Error
3766
-     * @return string of SQL
3767
-     */
3768
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3769
-    {
3770
-        $where_clauses = array();
3771
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3772
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3773
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3774
-                switch ($query_param) {
3775
-                    case 'not':
3776
-                    case 'NOT':
3777
-                        $where_clauses[] = "! ("
3778
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3779
-                                $glue)
3780
-                                           . ")";
3781
-                        break;
3782
-                    case 'and':
3783
-                    case 'AND':
3784
-                        $where_clauses[] = " ("
3785
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3786
-                                ' AND ')
3787
-                                           . ")";
3788
-                        break;
3789
-                    case 'or':
3790
-                    case 'OR':
3791
-                        $where_clauses[] = " ("
3792
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3793
-                                ' OR ')
3794
-                                           . ")";
3795
-                        break;
3796
-                }
3797
-            } else {
3798
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3799
-                //if it's not a normal field, maybe it's a custom selection?
3800
-                if ( ! $field_obj) {
3801
-                    if (isset($this->_custom_selections[$query_param][1])) {
3802
-                        $field_obj = $this->_custom_selections[$query_param][1];
3803
-                    } else {
3804
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3805
-                            "event_espresso"), $query_param));
3806
-                    }
3807
-                }
3808
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3809
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3810
-            }
3811
-        }
3812
-        return $where_clauses ? implode($glue, $where_clauses) : '';
3813
-    }
3814
-
3815
-
3816
-
3817
-    /**
3818
-     * Takes the input parameter and extract the table name (alias) and column name
3819
-     *
3820
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3821
-     * @throws EE_Error
3822
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3823
-     */
3824
-    private function _deduce_column_name_from_query_param($query_param)
3825
-    {
3826
-        $field = $this->_deduce_field_from_query_param($query_param);
3827
-        if ($field) {
3828
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
3829
-                $query_param);
3830
-            return $table_alias_prefix . $field->get_qualified_column();
3831
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
3832
-            //maybe it's custom selection item?
3833
-            //if so, just use it as the "column name"
3834
-            return $query_param;
3835
-        } else {
3836
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
3837
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
3838
-        }
3839
-    }
3840
-
3841
-
3842
-
3843
-    /**
3844
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
3845
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
3846
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
3847
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
3848
-     *
3849
-     * @param string $condition_query_param_key
3850
-     * @return string
3851
-     */
3852
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
3853
-    {
3854
-        $pos_of_star = strpos($condition_query_param_key, '*');
3855
-        if ($pos_of_star === false) {
3856
-            return $condition_query_param_key;
3857
-        } else {
3858
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
3859
-            return $condition_query_param_sans_star;
3860
-        }
3861
-    }
3862
-
3863
-
3864
-
3865
-    /**
3866
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
3867
-     *
3868
-     * @param                            mixed      array | string    $op_and_value
3869
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
3870
-     * @throws EE_Error
3871
-     * @return string
3872
-     */
3873
-    private function _construct_op_and_value($op_and_value, $field_obj)
3874
-    {
3875
-        if (is_array($op_and_value)) {
3876
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
3877
-            if ( ! $operator) {
3878
-                $php_array_like_string = array();
3879
-                foreach ($op_and_value as $key => $value) {
3880
-                    $php_array_like_string[] = "$key=>$value";
3881
-                }
3882
-                throw new EE_Error(
3883
-                    sprintf(
3884
-                        __(
3885
-                            "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))",
3886
-                            "event_espresso"
3887
-                        ),
3888
-                        implode(",", $php_array_like_string)
3889
-                    )
3890
-                );
3891
-            }
3892
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
3893
-        } else {
3894
-            $operator = '=';
3895
-            $value = $op_and_value;
3896
-        }
3897
-        //check to see if the value is actually another field
3898
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
3899
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
3900
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
3901
-            //in this case, the value should be an array, or at least a comma-separated list
3902
-            //it will need to handle a little differently
3903
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
3904
-            //note: $cleaned_value has already been run through $wpdb->prepare()
3905
-            return $operator . SP . $cleaned_value;
3906
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
3907
-            //the value should be an array with count of two.
3908
-            if (count($value) !== 2) {
3909
-                throw new EE_Error(
3910
-                    sprintf(
3911
-                        __(
3912
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
3913
-                            'event_espresso'
3914
-                        ),
3915
-                        "BETWEEN"
3916
-                    )
3917
-                );
3918
-            }
3919
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
3920
-            return $operator . SP . $cleaned_value;
3921
-        } elseif (in_array($operator, $this->_null_style_operators)) {
3922
-            if ($value !== null) {
3923
-                throw new EE_Error(
3924
-                    sprintf(
3925
-                        __(
3926
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
3927
-                            "event_espresso"
3928
-                        ),
3929
-                        $value,
3930
-                        $operator
3931
-                    )
3932
-                );
3933
-            }
3934
-            return $operator;
3935
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
3936
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
3937
-            //remove other junk. So just treat it as a string.
3938
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
3939
-        } elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3940
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
3941
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3942
-            throw new EE_Error(
3943
-                sprintf(
3944
-                    __(
3945
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
3946
-                        'event_espresso'
3947
-                    ),
3948
-                    $operator,
3949
-                    $operator
3950
-                )
3951
-            );
3952
-        } elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
3953
-            throw new EE_Error(
3954
-                sprintf(
3955
-                    __(
3956
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
3957
-                        'event_espresso'
3958
-                    ),
3959
-                    $operator,
3960
-                    $operator
3961
-                )
3962
-            );
3963
-        } else {
3964
-            throw new EE_Error(
3965
-                sprintf(
3966
-                    __(
3967
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
3968
-                        "event_espresso"
3969
-                    ),
3970
-                    http_build_query($op_and_value)
3971
-                )
3972
-            );
3973
-        }
3974
-    }
3975
-
3976
-
3977
-
3978
-    /**
3979
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
3980
-     *
3981
-     * @param array                      $values
3982
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
3983
-     *                                              '%s'
3984
-     * @return string
3985
-     * @throws \EE_Error
3986
-     */
3987
-    public function _construct_between_value($values, $field_obj)
3988
-    {
3989
-        $cleaned_values = array();
3990
-        foreach ($values as $value) {
3991
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
3992
-        }
3993
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
3994
-    }
3995
-
3996
-
3997
-
3998
-    /**
3999
-     * Takes an array or a comma-separated list of $values and cleans them
4000
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4001
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4002
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4003
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4004
-     *
4005
-     * @param mixed                      $values    array or comma-separated string
4006
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4007
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4008
-     * @throws \EE_Error
4009
-     */
4010
-    public function _construct_in_value($values, $field_obj)
4011
-    {
4012
-        //check if the value is a CSV list
4013
-        if (is_string($values)) {
4014
-            //in which case, turn it into an array
4015
-            $values = explode(",", $values);
4016
-        }
4017
-        $cleaned_values = array();
4018
-        foreach ($values as $value) {
4019
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4020
-        }
4021
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4022
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4023
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4024
-        if (empty($cleaned_values)) {
4025
-            $all_fields = $this->field_settings();
4026
-            $a_field = array_shift($all_fields);
4027
-            $main_table = $this->_get_main_table();
4028
-            $cleaned_values[] = "SELECT "
4029
-                                . $a_field->get_table_column()
4030
-                                . " FROM "
4031
-                                . $main_table->get_table_name()
4032
-                                . " WHERE FALSE";
4033
-        }
4034
-        return "(" . implode(",", $cleaned_values) . ")";
4035
-    }
4036
-
4037
-
4038
-
4039
-    /**
4040
-     * @param mixed                      $value
4041
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4042
-     * @throws EE_Error
4043
-     * @return false|null|string
4044
-     */
4045
-    private function _wpdb_prepare_using_field($value, $field_obj)
4046
-    {
4047
-        /** @type WPDB $wpdb */
4048
-        global $wpdb;
4049
-        if ($field_obj instanceof EE_Model_Field_Base) {
4050
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4051
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4052
-        } else {//$field_obj should really just be a data type
4053
-            if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4054
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4055
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4056
-            }
4057
-            return $wpdb->prepare($field_obj, $value);
4058
-        }
4059
-    }
4060
-
4061
-
4062
-
4063
-    /**
4064
-     * Takes the input parameter and finds the model field that it indicates.
4065
-     *
4066
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4067
-     * @throws EE_Error
4068
-     * @return EE_Model_Field_Base
4069
-     */
4070
-    protected function _deduce_field_from_query_param($query_param_name)
4071
-    {
4072
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4073
-        //which will help us find the database table and column
4074
-        $query_param_parts = explode(".", $query_param_name);
4075
-        if (empty($query_param_parts)) {
4076
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4077
-                'event_espresso'), $query_param_name));
4078
-        }
4079
-        $number_of_parts = count($query_param_parts);
4080
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4081
-        if ($number_of_parts === 1) {
4082
-            $field_name = $last_query_param_part;
4083
-            $model_obj = $this;
4084
-        } else {// $number_of_parts >= 2
4085
-            //the last part is the column name, and there are only 2parts. therefore...
4086
-            $field_name = $last_query_param_part;
4087
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4088
-        }
4089
-        try {
4090
-            return $model_obj->field_settings_for($field_name);
4091
-        } catch (EE_Error $e) {
4092
-            return null;
4093
-        }
4094
-    }
4095
-
4096
-
4097
-
4098
-    /**
4099
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4100
-     * alias and column which corresponds to it
4101
-     *
4102
-     * @param string $field_name
4103
-     * @throws EE_Error
4104
-     * @return string
4105
-     */
4106
-    public function _get_qualified_column_for_field($field_name)
4107
-    {
4108
-        $all_fields = $this->field_settings();
4109
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4110
-        if ($field) {
4111
-            return $field->get_qualified_column();
4112
-        } else {
4113
-            throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4114
-                'event_espresso'), $field_name, get_class($this)));
4115
-        }
4116
-    }
4117
-
4118
-
4119
-
4120
-    /**
4121
-     * constructs the select use on special limit joins
4122
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4123
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4124
-     * (as that is typically where the limits would be set).
4125
-     *
4126
-     * @param  string       $table_alias The table the select is being built for
4127
-     * @param  mixed|string $limit       The limit for this select
4128
-     * @return string                The final select join element for the query.
4129
-     */
4130
-    public function _construct_limit_join_select($table_alias, $limit)
4131
-    {
4132
-        $SQL = '';
4133
-        foreach ($this->_tables as $table_obj) {
4134
-            if ($table_obj instanceof EE_Primary_Table) {
4135
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4136
-                    ? $table_obj->get_select_join_limit($limit)
4137
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4138
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4139
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4140
-                    ? $table_obj->get_select_join_limit_join($limit)
4141
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4142
-            }
4143
-        }
4144
-        return $SQL;
4145
-    }
4146
-
4147
-
4148
-
4149
-    /**
4150
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4151
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4152
-     *
4153
-     * @return string SQL
4154
-     * @throws \EE_Error
4155
-     */
4156
-    public function _construct_internal_join()
4157
-    {
4158
-        $SQL = $this->_get_main_table()->get_table_sql();
4159
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4160
-        return $SQL;
4161
-    }
4162
-
4163
-
4164
-
4165
-    /**
4166
-     * Constructs the SQL for joining all the tables on this model.
4167
-     * Normally $alias should be the primary table's alias, but in cases where
4168
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4169
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4170
-     * alias, this will construct SQL like:
4171
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4172
-     * With $alias being a secondary table's alias, this will construct SQL like:
4173
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4174
-     *
4175
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4176
-     * @return string
4177
-     */
4178
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4179
-    {
4180
-        $SQL = '';
4181
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4182
-        foreach ($this->_tables as $table_obj) {
4183
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4184
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4185
-                    //so we're joining to this table, meaning the table is already in
4186
-                    //the FROM statement, BUT the primary table isn't. So we want
4187
-                    //to add the inverse join sql
4188
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4189
-                } else {
4190
-                    //just add a regular JOIN to this table from the primary table
4191
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4192
-                }
4193
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4194
-        }
4195
-        return $SQL;
4196
-    }
4197
-
4198
-
4199
-
4200
-    /**
4201
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4202
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4203
-     * their data type (eg, '%s', '%d', etc)
4204
-     *
4205
-     * @return array
4206
-     */
4207
-    public function _get_data_types()
4208
-    {
4209
-        $data_types = array();
4210
-        foreach ($this->field_settings() as $field_obj) {
4211
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4212
-            /** @var $field_obj EE_Model_Field_Base */
4213
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4214
-        }
4215
-        return $data_types;
4216
-    }
4217
-
4218
-
4219
-
4220
-    /**
4221
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4222
-     *
4223
-     * @param string $model_name
4224
-     * @throws EE_Error
4225
-     * @return EEM_Base
4226
-     */
4227
-    public function get_related_model_obj($model_name)
4228
-    {
4229
-        $model_classname = "EEM_" . $model_name;
4230
-        if ( ! class_exists($model_classname)) {
4231
-            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",
4232
-                'event_espresso'), $model_name, $model_classname));
4233
-        }
4234
-        return call_user_func($model_classname . "::instance");
4235
-    }
4236
-
4237
-
4238
-
4239
-    /**
4240
-     * Returns the array of EE_ModelRelations for this model.
4241
-     *
4242
-     * @return EE_Model_Relation_Base[]
4243
-     */
4244
-    public function relation_settings()
4245
-    {
4246
-        return $this->_model_relations;
4247
-    }
4248
-
4249
-
4250
-
4251
-    /**
4252
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4253
-     * because without THOSE models, this model probably doesn't have much purpose.
4254
-     * (Eg, without an event, datetimes have little purpose.)
4255
-     *
4256
-     * @return EE_Belongs_To_Relation[]
4257
-     */
4258
-    public function belongs_to_relations()
4259
-    {
4260
-        $belongs_to_relations = array();
4261
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4262
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4263
-                $belongs_to_relations[$model_name] = $relation_obj;
4264
-            }
4265
-        }
4266
-        return $belongs_to_relations;
4267
-    }
4268
-
4269
-
4270
-
4271
-    /**
4272
-     * Returns the specified EE_Model_Relation, or throws an exception
4273
-     *
4274
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4275
-     * @throws EE_Error
4276
-     * @return EE_Model_Relation_Base
4277
-     */
4278
-    public function related_settings_for($relation_name)
4279
-    {
4280
-        $relatedModels = $this->relation_settings();
4281
-        if ( ! array_key_exists($relation_name, $relatedModels)) {
4282
-            throw new EE_Error(
4283
-                sprintf(
4284
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4285
-                        'event_espresso'),
4286
-                    $relation_name,
4287
-                    $this->_get_class_name(),
4288
-                    implode(', ', array_keys($relatedModels))
4289
-                )
4290
-            );
4291
-        }
4292
-        return $relatedModels[$relation_name];
4293
-    }
4294
-
4295
-
4296
-
4297
-    /**
4298
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4299
-     * fields
4300
-     *
4301
-     * @param string $fieldName
4302
-     * @throws EE_Error
4303
-     * @return EE_Model_Field_Base
4304
-     */
4305
-    public function field_settings_for($fieldName)
4306
-    {
4307
-        $fieldSettings = $this->field_settings(true);
4308
-        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4309
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4310
-                get_class($this)));
4311
-        }
4312
-        return $fieldSettings[$fieldName];
4313
-    }
4314
-
4315
-
4316
-
4317
-    /**
4318
-     * Checks if this field exists on this model
4319
-     *
4320
-     * @param string $fieldName a key in the model's _field_settings array
4321
-     * @return boolean
4322
-     */
4323
-    public function has_field($fieldName)
4324
-    {
4325
-        $fieldSettings = $this->field_settings(true);
4326
-        if (isset($fieldSettings[$fieldName])) {
4327
-            return true;
4328
-        } else {
4329
-            return false;
4330
-        }
4331
-    }
4332
-
4333
-
4334
-
4335
-    /**
4336
-     * Returns whether or not this model has a relation to the specified model
4337
-     *
4338
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4339
-     * @return boolean
4340
-     */
4341
-    public function has_relation($relation_name)
4342
-    {
4343
-        $relations = $this->relation_settings();
4344
-        if (isset($relations[$relation_name])) {
4345
-            return true;
4346
-        } else {
4347
-            return false;
4348
-        }
4349
-    }
4350
-
4351
-
4352
-
4353
-    /**
4354
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4355
-     * Eg, on EE_Answer that would be ANS_ID field object
4356
-     *
4357
-     * @param $field_obj
4358
-     * @return boolean
4359
-     */
4360
-    public function is_primary_key_field($field_obj)
4361
-    {
4362
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4363
-    }
4364
-
4365
-
4366
-
4367
-    /**
4368
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4369
-     * Eg, on EE_Answer that would be ANS_ID field object
4370
-     *
4371
-     * @return EE_Model_Field_Base
4372
-     * @throws EE_Error
4373
-     */
4374
-    public function get_primary_key_field()
4375
-    {
4376
-        if ($this->_primary_key_field === null) {
4377
-            foreach ($this->field_settings(true) as $field_obj) {
4378
-                if ($this->is_primary_key_field($field_obj)) {
4379
-                    $this->_primary_key_field = $field_obj;
4380
-                    break;
4381
-                }
4382
-            }
4383
-            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4384
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4385
-                    get_class($this)));
4386
-            }
4387
-        }
4388
-        return $this->_primary_key_field;
4389
-    }
4390
-
4391
-
4392
-
4393
-    /**
4394
-     * Returns whether or not not there is a primary key on this model.
4395
-     * Internally does some caching.
4396
-     *
4397
-     * @return boolean
4398
-     */
4399
-    public function has_primary_key_field()
4400
-    {
4401
-        if ($this->_has_primary_key_field === null) {
4402
-            try {
4403
-                $this->get_primary_key_field();
4404
-                $this->_has_primary_key_field = true;
4405
-            } catch (EE_Error $e) {
4406
-                $this->_has_primary_key_field = false;
4407
-            }
4408
-        }
4409
-        return $this->_has_primary_key_field;
4410
-    }
4411
-
4412
-
4413
-
4414
-    /**
4415
-     * Finds the first field of type $field_class_name.
4416
-     *
4417
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4418
-     *                                 EE_Foreign_Key_Field, etc
4419
-     * @return EE_Model_Field_Base or null if none is found
4420
-     */
4421
-    public function get_a_field_of_type($field_class_name)
4422
-    {
4423
-        foreach ($this->field_settings() as $field) {
4424
-            if ($field instanceof $field_class_name) {
4425
-                return $field;
4426
-            }
4427
-        }
4428
-        return null;
4429
-    }
4430
-
4431
-
4432
-
4433
-    /**
4434
-     * Gets a foreign key field pointing to model.
4435
-     *
4436
-     * @param string $model_name eg Event, Registration, not EEM_Event
4437
-     * @return EE_Foreign_Key_Field_Base
4438
-     * @throws EE_Error
4439
-     */
4440
-    public function get_foreign_key_to($model_name)
4441
-    {
4442
-        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4443
-            foreach ($this->field_settings() as $field) {
4444
-                if (
4445
-                    $field instanceof EE_Foreign_Key_Field_Base
4446
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4447
-                ) {
4448
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4449
-                    break;
4450
-                }
4451
-            }
4452
-            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4453
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4454
-                    'event_espresso'), $model_name, get_class($this)));
4455
-            }
4456
-        }
4457
-        return $this->_cache_foreign_key_to_fields[$model_name];
4458
-    }
4459
-
4460
-
4461
-
4462
-    /**
4463
-     * Gets the actual table for the table alias
4464
-     *
4465
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4466
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4467
-     *                            Either one works
4468
-     * @return EE_Table_Base
4469
-     */
4470
-    public function get_table_for_alias($table_alias)
4471
-    {
4472
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4473
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4474
-    }
4475
-
4476
-
4477
-
4478
-    /**
4479
-     * Returns a flat array of all field son this model, instead of organizing them
4480
-     * by table_alias as they are in the constructor.
4481
-     *
4482
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4483
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4484
-     */
4485
-    public function field_settings($include_db_only_fields = false)
4486
-    {
4487
-        if ($include_db_only_fields) {
4488
-            if ($this->_cached_fields === null) {
4489
-                $this->_cached_fields = array();
4490
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4491
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4492
-                        $this->_cached_fields[$field_name] = $field_obj;
4493
-                    }
4494
-                }
4495
-            }
4496
-            return $this->_cached_fields;
4497
-        } else {
4498
-            if ($this->_cached_fields_non_db_only === null) {
4499
-                $this->_cached_fields_non_db_only = array();
4500
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4501
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4502
-                        /** @var $field_obj EE_Model_Field_Base */
4503
-                        if ( ! $field_obj->is_db_only_field()) {
4504
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4505
-                        }
4506
-                    }
4507
-                }
4508
-            }
4509
-            return $this->_cached_fields_non_db_only;
4510
-        }
4511
-    }
4512
-
4513
-
4514
-
4515
-    /**
4516
-     *        cycle though array of attendees and create objects out of each item
4517
-     *
4518
-     * @access        private
4519
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4520
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4521
-     *                          numerically indexed)
4522
-     * @throws \EE_Error
4523
-     */
4524
-    protected function _create_objects($rows = array())
4525
-    {
4526
-        $array_of_objects = array();
4527
-        if (empty($rows)) {
4528
-            return array();
4529
-        }
4530
-        $count_if_model_has_no_primary_key = 0;
4531
-        $has_primary_key = $this->has_primary_key_field();
4532
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4533
-        foreach ((array)$rows as $row) {
4534
-            if (empty($row)) {
4535
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4536
-                return array();
4537
-            }
4538
-            //check if we've already set this object in the results array,
4539
-            //in which case there's no need to process it further (again)
4540
-            if ($has_primary_key) {
4541
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4542
-                    $row,
4543
-                    $primary_key_field->get_qualified_column(),
4544
-                    $primary_key_field->get_table_column()
4545
-                );
4546
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4547
-                    continue;
4548
-                }
4549
-            }
4550
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4551
-            if ( ! $classInstance) {
4552
-                throw new EE_Error(
4553
-                    sprintf(
4554
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4555
-                        $this->get_this_model_name(),
4556
-                        http_build_query($row)
4557
-                    )
4558
-                );
4559
-            }
4560
-            //set the timezone on the instantiated objects
4561
-            $classInstance->set_timezone($this->_timezone);
4562
-            //make sure if there is any timezone setting present that we set the timezone for the object
4563
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4564
-            $array_of_objects[$key] = $classInstance;
4565
-            //also, for all the relations of type BelongsTo, see if we can cache
4566
-            //those related models
4567
-            //(we could do this for other relations too, but if there are conditions
4568
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4569
-            //so it requires a little more thought than just caching them immediately...)
4570
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4571
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4572
-                    //check if this model's INFO is present. If so, cache it on the model
4573
-                    $other_model = $relation_obj->get_other_model();
4574
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4575
-                    //if we managed to make a model object from the results, cache it on the main model object
4576
-                    if ($other_model_obj_maybe) {
4577
-                        //set timezone on these other model objects if they are present
4578
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4579
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4580
-                    }
4581
-                }
4582
-            }
4583
-        }
4584
-        return $array_of_objects;
4585
-    }
4586
-
4587
-
4588
-
4589
-    /**
4590
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4591
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4592
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4593
-     * object (as set in the model_field!).
4594
-     *
4595
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4596
-     */
4597
-    public function create_default_object()
4598
-    {
4599
-        $this_model_fields_and_values = array();
4600
-        //setup the row using default values;
4601
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4602
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4603
-        }
4604
-        $className = $this->_get_class_name();
4605
-        $classInstance = EE_Registry::instance()
4606
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4607
-        return $classInstance;
4608
-    }
4609
-
4610
-
4611
-
4612
-    /**
4613
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4614
-     *                             or an stdClass where each property is the name of a column,
4615
-     * @return EE_Base_Class
4616
-     * @throws \EE_Error
4617
-     */
4618
-    public function instantiate_class_from_array_or_object($cols_n_values)
4619
-    {
4620
-        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4621
-            $cols_n_values = get_object_vars($cols_n_values);
4622
-        }
4623
-        $primary_key = null;
4624
-        //make sure the array only has keys that are fields/columns on this model
4625
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4626
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4627
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4628
-        }
4629
-        $className = $this->_get_class_name();
4630
-        //check we actually found results that we can use to build our model object
4631
-        //if not, return null
4632
-        if ($this->has_primary_key_field()) {
4633
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4634
-                return null;
4635
-            }
4636
-        } else if ($this->unique_indexes()) {
4637
-            $first_column = reset($this_model_fields_n_values);
4638
-            if (empty($first_column)) {
4639
-                return null;
4640
-            }
4641
-        }
4642
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4643
-        if ($primary_key) {
4644
-            $classInstance = $this->get_from_entity_map($primary_key);
4645
-            if ( ! $classInstance) {
4646
-                $classInstance = EE_Registry::instance()
4647
-                                            ->load_class($className,
4648
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4649
-                // add this new object to the entity map
4650
-                $classInstance = $this->add_to_entity_map($classInstance);
4651
-            }
4652
-        } else {
4653
-            $classInstance = EE_Registry::instance()
4654
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4655
-                                            true, false);
4656
-        }
4657
-        //it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4658
-        $this->set_timezone($classInstance->get_timezone());
4659
-        return $classInstance;
4660
-    }
4661
-
4662
-
4663
-
4664
-    /**
4665
-     * Gets the model object from the  entity map if it exists
4666
-     *
4667
-     * @param int|string $id the ID of the model object
4668
-     * @return EE_Base_Class
4669
-     */
4670
-    public function get_from_entity_map($id)
4671
-    {
4672
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4673
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4674
-    }
4675
-
4676
-
4677
-
4678
-    /**
4679
-     * add_to_entity_map
4680
-     * Adds the object to the model's entity mappings
4681
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4682
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4683
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4684
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4685
-     *        then this method should be called immediately after the update query
4686
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4687
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4688
-     *
4689
-     * @param    EE_Base_Class $object
4690
-     * @throws EE_Error
4691
-     * @return \EE_Base_Class
4692
-     */
4693
-    public function add_to_entity_map(EE_Base_Class $object)
4694
-    {
4695
-        $className = $this->_get_class_name();
4696
-        if ( ! $object instanceof $className) {
4697
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4698
-                is_object($object) ? get_class($object) : $object, $className));
4699
-        }
4700
-        /** @var $object EE_Base_Class */
4701
-        if ( ! $object->ID()) {
4702
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4703
-                "event_espresso"), get_class($this)));
4704
-        }
4705
-        // double check it's not already there
4706
-        $classInstance = $this->get_from_entity_map($object->ID());
4707
-        if ($classInstance) {
4708
-            return $classInstance;
4709
-        } else {
4710
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4711
-            return $object;
4712
-        }
4713
-    }
4714
-
4715
-
4716
-
4717
-    /**
4718
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4719
-     * if no identifier is provided, then the entire entity map is emptied
4720
-     *
4721
-     * @param int|string $id the ID of the model object
4722
-     * @return boolean
4723
-     */
4724
-    public function clear_entity_map($id = null)
4725
-    {
4726
-        if (empty($id)) {
4727
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4728
-            return true;
4729
-        }
4730
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4731
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4732
-            return true;
4733
-        }
4734
-        return false;
4735
-    }
4736
-
4737
-
4738
-
4739
-    /**
4740
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4741
-     * Given an array where keys are column (or column alias) names and values,
4742
-     * returns an array of their corresponding field names and database values
4743
-     *
4744
-     * @param array $cols_n_values
4745
-     * @return array
4746
-     */
4747
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4748
-    {
4749
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4750
-    }
4751
-
4752
-
4753
-
4754
-    /**
4755
-     * _deduce_fields_n_values_from_cols_n_values
4756
-     * Given an array where keys are column (or column alias) names and values,
4757
-     * returns an array of their corresponding field names and database values
4758
-     *
4759
-     * @param string $cols_n_values
4760
-     * @return array
4761
-     */
4762
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
4763
-    {
4764
-        $this_model_fields_n_values = array();
4765
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
4766
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
4767
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
4768
-            //there is a primary key on this table and its not set. Use defaults for all its columns
4769
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
4770
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4771
-                    if ( ! $field_obj->is_db_only_field()) {
4772
-                        //prepare field as if its coming from db
4773
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4774
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
4775
-                    }
4776
-                }
4777
-            } else {
4778
-                //the table's rows existed. Use their values
4779
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4780
-                    if ( ! $field_obj->is_db_only_field()) {
4781
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4782
-                            $cols_n_values, $field_obj->get_qualified_column(),
4783
-                            $field_obj->get_table_column()
4784
-                        );
4785
-                    }
4786
-                }
4787
-            }
4788
-        }
4789
-        return $this_model_fields_n_values;
4790
-    }
4791
-
4792
-
4793
-
4794
-    /**
4795
-     * @param $cols_n_values
4796
-     * @param $qualified_column
4797
-     * @param $regular_column
4798
-     * @return null
4799
-     */
4800
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
4801
-    {
4802
-        $value = null;
4803
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4804
-        //does the field on the model relate to this column retrieved from the db?
4805
-        //or is it a db-only field? (not relating to the model)
4806
-        if (isset($cols_n_values[$qualified_column])) {
4807
-            $value = $cols_n_values[$qualified_column];
4808
-        } elseif (isset($cols_n_values[$regular_column])) {
4809
-            $value = $cols_n_values[$regular_column];
4810
-        }
4811
-        return $value;
4812
-    }
4813
-
4814
-
4815
-
4816
-    /**
4817
-     * refresh_entity_map_from_db
4818
-     * Makes sure the model object in the entity map at $id assumes the values
4819
-     * of the database (opposite of EE_base_Class::save())
4820
-     *
4821
-     * @param int|string $id
4822
-     * @return EE_Base_Class
4823
-     * @throws \EE_Error
4824
-     */
4825
-    public function refresh_entity_map_from_db($id)
4826
-    {
4827
-        $obj_in_map = $this->get_from_entity_map($id);
4828
-        if ($obj_in_map) {
4829
-            $wpdb_results = $this->_get_all_wpdb_results(
4830
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
4831
-            );
4832
-            if ($wpdb_results && is_array($wpdb_results)) {
4833
-                $one_row = reset($wpdb_results);
4834
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
4835
-                    $obj_in_map->set_from_db($field_name, $db_value);
4836
-                }
4837
-                //clear the cache of related model objects
4838
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4839
-                    $obj_in_map->clear_cache($relation_name, null, true);
4840
-                }
4841
-            }
4842
-            return $obj_in_map;
4843
-        } else {
4844
-            return $this->get_one_by_ID($id);
4845
-        }
4846
-    }
4847
-
4848
-
4849
-
4850
-    /**
4851
-     * refresh_entity_map_with
4852
-     * Leaves the entry in the entity map alone, but updates it to match the provided
4853
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
4854
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
4855
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
4856
-     *
4857
-     * @param int|string    $id
4858
-     * @param EE_Base_Class $replacing_model_obj
4859
-     * @return \EE_Base_Class
4860
-     * @throws \EE_Error
4861
-     */
4862
-    public function refresh_entity_map_with($id, $replacing_model_obj)
4863
-    {
4864
-        $obj_in_map = $this->get_from_entity_map($id);
4865
-        if ($obj_in_map) {
4866
-            if ($replacing_model_obj instanceof EE_Base_Class) {
4867
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
4868
-                    $obj_in_map->set($field_name, $value);
4869
-                }
4870
-                //make the model object in the entity map's cache match the $replacing_model_obj
4871
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4872
-                    $obj_in_map->clear_cache($relation_name, null, true);
4873
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
4874
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
4875
-                    }
4876
-                }
4877
-            }
4878
-            return $obj_in_map;
4879
-        } else {
4880
-            $this->add_to_entity_map($replacing_model_obj);
4881
-            return $replacing_model_obj;
4882
-        }
4883
-    }
4884
-
4885
-
4886
-
4887
-    /**
4888
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
4889
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
4890
-     * require_once($this->_getClassName().".class.php");
4891
-     *
4892
-     * @return string
4893
-     */
4894
-    private function _get_class_name()
4895
-    {
4896
-        return "EE_" . $this->get_this_model_name();
4897
-    }
4898
-
4899
-
4900
-
4901
-    /**
4902
-     * Get the name of the items this model represents, for the quantity specified. Eg,
4903
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
4904
-     * it would be 'Events'.
4905
-     *
4906
-     * @param int $quantity
4907
-     * @return string
4908
-     */
4909
-    public function item_name($quantity = 1)
4910
-    {
4911
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
4912
-    }
4913
-
4914
-
4915
-
4916
-    /**
4917
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
4918
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
4919
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
4920
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
4921
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
4922
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
4923
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
4924
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
4925
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
4926
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
4927
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
4928
-     *        return $previousReturnValue.$returnString;
4929
-     * }
4930
-     * require('EEM_Answer.model.php');
4931
-     * $answer=EEM_Answer::instance();
4932
-     * echo $answer->my_callback('monkeys',100);
4933
-     * //will output "you called my_callback! and passed args:monkeys,100"
4934
-     *
4935
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
4936
-     * @param array  $args       array of original arguments passed to the function
4937
-     * @throws EE_Error
4938
-     * @return mixed whatever the plugin which calls add_filter decides
4939
-     */
4940
-    public function __call($methodName, $args)
4941
-    {
4942
-        $className = get_class($this);
4943
-        $tagName = "FHEE__{$className}__{$methodName}";
4944
-        if ( ! has_filter($tagName)) {
4945
-            throw new EE_Error(
4946
-                sprintf(
4947
-                    __('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 );',
4948
-                        'event_espresso'),
4949
-                    $methodName,
4950
-                    $className,
4951
-                    $tagName,
4952
-                    '<br />'
4953
-                )
4954
-            );
4955
-        }
4956
-        return apply_filters($tagName, null, $this, $args);
4957
-    }
4958
-
4959
-
4960
-
4961
-    /**
4962
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
4963
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
4964
-     *
4965
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
4966
-     *                                                       the EE_Base_Class object that corresponds to this Model,
4967
-     *                                                       the object's class name
4968
-     *                                                       or object's ID
4969
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
4970
-     *                                                       exists in the database. If it does not, we add it
4971
-     * @throws EE_Error
4972
-     * @return EE_Base_Class
4973
-     */
4974
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
4975
-    {
4976
-        $className = $this->_get_class_name();
4977
-        if ($base_class_obj_or_id instanceof $className) {
4978
-            $model_object = $base_class_obj_or_id;
4979
-        } else {
4980
-            $primary_key_field = $this->get_primary_key_field();
4981
-            if (
4982
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
4983
-                && (
4984
-                    is_int($base_class_obj_or_id)
4985
-                    || is_string($base_class_obj_or_id)
4986
-                )
4987
-            ) {
4988
-                // assume it's an ID.
4989
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
4990
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
4991
-            } else if (
4992
-                $primary_key_field instanceof EE_Primary_Key_String_Field
4993
-                && is_string($base_class_obj_or_id)
4994
-            ) {
4995
-                // assume its a string representation of the object
4996
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
4997
-            } else {
4998
-                throw new EE_Error(
4999
-                    sprintf(
5000
-                        __(
5001
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5002
-                            'event_espresso'
5003
-                        ),
5004
-                        $base_class_obj_or_id,
5005
-                        $this->_get_class_name(),
5006
-                        print_r($base_class_obj_or_id, true)
5007
-                    )
5008
-                );
5009
-            }
5010
-        }
5011
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5012
-            $model_object->save();
5013
-        }
5014
-        return $model_object;
5015
-    }
5016
-
5017
-
5018
-
5019
-    /**
5020
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5021
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5022
-     * returns it ID.
5023
-     *
5024
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5025
-     * @return int|string depending on the type of this model object's ID
5026
-     * @throws EE_Error
5027
-     */
5028
-    public function ensure_is_ID($base_class_obj_or_id)
5029
-    {
5030
-        $className = $this->_get_class_name();
5031
-        if ($base_class_obj_or_id instanceof $className) {
5032
-            /** @var $base_class_obj_or_id EE_Base_Class */
5033
-            $id = $base_class_obj_or_id->ID();
5034
-        } elseif (is_int($base_class_obj_or_id)) {
5035
-            //assume it's an ID
5036
-            $id = $base_class_obj_or_id;
5037
-        } elseif (is_string($base_class_obj_or_id)) {
5038
-            //assume its a string representation of the object
5039
-            $id = $base_class_obj_or_id;
5040
-        } else {
5041
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5042
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5043
-                print_r($base_class_obj_or_id, true)));
5044
-        }
5045
-        return $id;
5046
-    }
5047
-
5048
-
5049
-
5050
-    /**
5051
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5052
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5053
-     * been sanitized and converted into the appropriate domain.
5054
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5055
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5056
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5057
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5058
-     * $EVT = EEM_Event::instance(); $old_setting =
5059
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5060
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5061
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5062
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5063
-     *
5064
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5065
-     * @return void
5066
-     */
5067
-    public function assume_values_already_prepared_by_model_object(
5068
-        $values_already_prepared = self::not_prepared_by_model_object
5069
-    ) {
5070
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5071
-    }
5072
-
5073
-
5074
-
5075
-    /**
5076
-     * Read comments for assume_values_already_prepared_by_model_object()
5077
-     *
5078
-     * @return int
5079
-     */
5080
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5081
-    {
5082
-        return $this->_values_already_prepared_by_model_object;
5083
-    }
5084
-
5085
-
5086
-
5087
-    /**
5088
-     * Gets all the indexes on this model
5089
-     *
5090
-     * @return EE_Index[]
5091
-     */
5092
-    public function indexes()
5093
-    {
5094
-        return $this->_indexes;
5095
-    }
5096
-
5097
-
5098
-
5099
-    /**
5100
-     * Gets all the Unique Indexes on this model
5101
-     *
5102
-     * @return EE_Unique_Index[]
5103
-     */
5104
-    public function unique_indexes()
5105
-    {
5106
-        $unique_indexes = array();
5107
-        foreach ($this->_indexes as $name => $index) {
5108
-            if ($index instanceof EE_Unique_Index) {
5109
-                $unique_indexes [$name] = $index;
5110
-            }
5111
-        }
5112
-        return $unique_indexes;
5113
-    }
5114
-
5115
-
5116
-
5117
-    /**
5118
-     * Gets all the fields which, when combined, make the primary key.
5119
-     * This is usually just an array with 1 element (the primary key), but in cases
5120
-     * where there is no primary key, it's a combination of fields as defined
5121
-     * on a primary index
5122
-     *
5123
-     * @return EE_Model_Field_Base[] indexed by the field's name
5124
-     * @throws \EE_Error
5125
-     */
5126
-    public function get_combined_primary_key_fields()
5127
-    {
5128
-        foreach ($this->indexes() as $index) {
5129
-            if ($index instanceof EE_Primary_Key_Index) {
5130
-                return $index->fields();
5131
-            }
5132
-        }
5133
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5134
-    }
5135
-
5136
-
5137
-
5138
-    /**
5139
-     * Used to build a primary key string (when the model has no primary key),
5140
-     * which can be used a unique string to identify this model object.
5141
-     *
5142
-     * @param array $cols_n_values keys are field names, values are their values
5143
-     * @return string
5144
-     * @throws \EE_Error
5145
-     */
5146
-    public function get_index_primary_key_string($cols_n_values)
5147
-    {
5148
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5149
-            $this->get_combined_primary_key_fields());
5150
-        return http_build_query($cols_n_values_for_primary_key_index);
5151
-    }
5152
-
5153
-
5154
-
5155
-    /**
5156
-     * Gets the field values from the primary key string
5157
-     *
5158
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5159
-     * @param string $index_primary_key_string
5160
-     * @return null|array
5161
-     * @throws \EE_Error
5162
-     */
5163
-    public function parse_index_primary_key_string($index_primary_key_string)
5164
-    {
5165
-        $key_fields = $this->get_combined_primary_key_fields();
5166
-        //check all of them are in the $id
5167
-        $key_vals_in_combined_pk = array();
5168
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5169
-        foreach ($key_fields as $key_field_name => $field_obj) {
5170
-            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5171
-                return null;
5172
-            }
5173
-        }
5174
-        return $key_vals_in_combined_pk;
5175
-    }
5176
-
5177
-
5178
-
5179
-    /**
5180
-     * verifies that an array of key-value pairs for model fields has a key
5181
-     * for each field comprising the primary key index
5182
-     *
5183
-     * @param array $key_vals
5184
-     * @return boolean
5185
-     * @throws \EE_Error
5186
-     */
5187
-    public function has_all_combined_primary_key_fields($key_vals)
5188
-    {
5189
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5190
-        foreach ($keys_it_should_have as $key) {
5191
-            if ( ! isset($key_vals[$key])) {
5192
-                return false;
5193
-            }
5194
-        }
5195
-        return true;
5196
-    }
5197
-
5198
-
5199
-
5200
-    /**
5201
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5202
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5203
-     *
5204
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5205
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5206
-     * @throws EE_Error
5207
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5208
-     *                          indexed)
5209
-     */
5210
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5211
-    {
5212
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5213
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5214
-        } elseif (is_array($model_object_or_attributes_array)) {
5215
-            $attributes_array = $model_object_or_attributes_array;
5216
-        } else {
5217
-            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",
5218
-                "event_espresso"), $model_object_or_attributes_array));
5219
-        }
5220
-        //even copies obviously won't have the same ID, so remove the primary key
5221
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5222
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5223
-            unset($attributes_array[$this->primary_key_name()]);
5224
-        }
5225
-        if (isset($query_params[0])) {
5226
-            $query_params[0] = array_merge($attributes_array, $query_params);
5227
-        } else {
5228
-            $query_params[0] = $attributes_array;
5229
-        }
5230
-        return $this->get_all($query_params);
5231
-    }
5232
-
5233
-
5234
-
5235
-    /**
5236
-     * Gets the first copy we find. See get_all_copies for more details
5237
-     *
5238
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5239
-     * @param array $query_params
5240
-     * @return EE_Base_Class
5241
-     * @throws \EE_Error
5242
-     */
5243
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5244
-    {
5245
-        if ( ! is_array($query_params)) {
5246
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5247
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5248
-                    gettype($query_params)), '4.6.0');
5249
-            $query_params = array();
5250
-        }
5251
-        $query_params['limit'] = 1;
5252
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5253
-        if (is_array($copies)) {
5254
-            return array_shift($copies);
5255
-        } else {
5256
-            return null;
5257
-        }
5258
-    }
5259
-
5260
-
5261
-
5262
-    /**
5263
-     * Updates the item with the specified id. Ignores default query parameters because
5264
-     * we have specified the ID, and its assumed we KNOW what we're doing
5265
-     *
5266
-     * @param array      $fields_n_values keys are field names, values are their new values
5267
-     * @param int|string $id              the value of the primary key to update
5268
-     * @return int number of rows updated
5269
-     * @throws \EE_Error
5270
-     */
5271
-    public function update_by_ID($fields_n_values, $id)
5272
-    {
5273
-        $query_params = array(
5274
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5275
-            'default_where_conditions' => 'other_models_only',
5276
-        );
5277
-        return $this->update($fields_n_values, $query_params);
5278
-    }
5279
-
5280
-
5281
-
5282
-    /**
5283
-     * Changes an operator which was supplied to the models into one usable in SQL
5284
-     *
5285
-     * @param string $operator_supplied
5286
-     * @return string an operator which can be used in SQL
5287
-     * @throws EE_Error
5288
-     */
5289
-    private function _prepare_operator_for_sql($operator_supplied)
5290
-    {
5291
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5292
-            : null;
5293
-        if ($sql_operator) {
5294
-            return $sql_operator;
5295
-        } else {
5296
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5297
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5298
-        }
5299
-    }
5300
-
5301
-
5302
-
5303
-    /**
5304
-     * Gets an array where keys are the primary keys and values are their 'names'
5305
-     * (as determined by the model object's name() function, which is often overridden)
5306
-     *
5307
-     * @param array $query_params like get_all's
5308
-     * @return string[]
5309
-     * @throws \EE_Error
5310
-     */
5311
-    public function get_all_names($query_params = array())
5312
-    {
5313
-        $objs = $this->get_all($query_params);
5314
-        $names = array();
5315
-        foreach ($objs as $obj) {
5316
-            $names[$obj->ID()] = $obj->name();
5317
-        }
5318
-        return $names;
5319
-    }
5320
-
5321
-
5322
-
5323
-    /**
5324
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5325
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5326
-     * this is duplicated effort and reduces efficiency) you would be better to use
5327
-     * array_keys() on $model_objects.
5328
-     *
5329
-     * @param \EE_Base_Class[] $model_objects
5330
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5331
-     *                                               in the returned array
5332
-     * @return array
5333
-     * @throws \EE_Error
5334
-     */
5335
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5336
-    {
5337
-        if ( ! $this->has_primary_key_field()) {
5338
-            if (WP_DEBUG) {
5339
-                EE_Error::add_error(
5340
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5341
-                    __FILE__,
5342
-                    __FUNCTION__,
5343
-                    __LINE__
5344
-                );
5345
-            }
5346
-        }
5347
-        $IDs = array();
5348
-        foreach ($model_objects as $model_object) {
5349
-            $id = $model_object->ID();
5350
-            if ( ! $id) {
5351
-                if ($filter_out_empty_ids) {
5352
-                    continue;
5353
-                }
5354
-                if (WP_DEBUG) {
5355
-                    EE_Error::add_error(
5356
-                        __(
5357
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5358
-                            'event_espresso'
5359
-                        ),
5360
-                        __FILE__,
5361
-                        __FUNCTION__,
5362
-                        __LINE__
5363
-                    );
5364
-                }
5365
-            }
5366
-            $IDs[] = $id;
5367
-        }
5368
-        return $IDs;
5369
-    }
5370
-
5371
-
5372
-
5373
-    /**
5374
-     * Returns the string used in capabilities relating to this model. If there
5375
-     * are no capabilities that relate to this model returns false
5376
-     *
5377
-     * @return string|false
5378
-     */
5379
-    public function cap_slug()
5380
-    {
5381
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5382
-    }
5383
-
5384
-
5385
-
5386
-    /**
5387
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5388
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5389
-     * only returns the cap restrictions array in that context (ie, the array
5390
-     * at that key)
5391
-     *
5392
-     * @param string $context
5393
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5394
-     * @throws \EE_Error
5395
-     */
5396
-    public function cap_restrictions($context = EEM_Base::caps_read)
5397
-    {
5398
-        EEM_Base::verify_is_valid_cap_context($context);
5399
-        //check if we ought to run the restriction generator first
5400
-        if (
5401
-            isset($this->_cap_restriction_generators[$context])
5402
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5403
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5404
-        ) {
5405
-            $this->_cap_restrictions[$context] = array_merge(
5406
-                $this->_cap_restrictions[$context],
5407
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5408
-            );
5409
-        }
5410
-        //and make sure we've finalized the construction of each restriction
5411
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5412
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5413
-                $where_conditions_obj->_finalize_construct($this);
5414
-            }
5415
-        }
5416
-        return $this->_cap_restrictions[$context];
5417
-    }
5418
-
5419
-
5420
-
5421
-    /**
5422
-     * Indicating whether or not this model thinks its a wp core model
5423
-     *
5424
-     * @return boolean
5425
-     */
5426
-    public function is_wp_core_model()
5427
-    {
5428
-        return $this->_wp_core_model;
5429
-    }
5430
-
5431
-
5432
-
5433
-    /**
5434
-     * Gets all the caps that are missing which impose a restriction on
5435
-     * queries made in this context
5436
-     *
5437
-     * @param string $context one of EEM_Base::caps_ constants
5438
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5439
-     * @throws \EE_Error
5440
-     */
5441
-    public function caps_missing($context = EEM_Base::caps_read)
5442
-    {
5443
-        $missing_caps = array();
5444
-        $cap_restrictions = $this->cap_restrictions($context);
5445
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5446
-            if ( ! EE_Capabilities::instance()
5447
-                                  ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5448
-            ) {
5449
-                $missing_caps[$cap] = $restriction_if_no_cap;
5450
-            }
5451
-        }
5452
-        return $missing_caps;
5453
-    }
5454
-
5455
-
5456
-
5457
-    /**
5458
-     * Gets the mapping from capability contexts to action strings used in capability names
5459
-     *
5460
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5461
-     * one of 'read', 'edit', or 'delete'
5462
-     */
5463
-    public function cap_contexts_to_cap_action_map()
5464
-    {
5465
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5466
-            $this);
5467
-    }
5468
-
5469
-
5470
-
5471
-    /**
5472
-     * Gets the action string for the specified capability context
5473
-     *
5474
-     * @param string $context
5475
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5476
-     * @throws \EE_Error
5477
-     */
5478
-    public function cap_action_for_context($context)
5479
-    {
5480
-        $mapping = $this->cap_contexts_to_cap_action_map();
5481
-        if (isset($mapping[$context])) {
5482
-            return $mapping[$context];
5483
-        }
5484
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5485
-            return $action;
5486
-        }
5487
-        throw new EE_Error(
5488
-            sprintf(
5489
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5490
-                $context,
5491
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5492
-            )
5493
-        );
5494
-    }
5495
-
5496
-
5497
-
5498
-    /**
5499
-     * Returns all the capability contexts which are valid when querying models
5500
-     *
5501
-     * @return array
5502
-     */
5503
-    static public function valid_cap_contexts()
5504
-    {
5505
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5506
-            self::caps_read,
5507
-            self::caps_read_admin,
5508
-            self::caps_edit,
5509
-            self::caps_delete,
5510
-        ));
5511
-    }
5512
-
5513
-
5514
-
5515
-    /**
5516
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5517
-     *
5518
-     * @param string $context
5519
-     * @return bool
5520
-     * @throws \EE_Error
5521
-     */
5522
-    static public function verify_is_valid_cap_context($context)
5523
-    {
5524
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5525
-        if (in_array($context, $valid_cap_contexts)) {
5526
-            return true;
5527
-        } else {
5528
-            throw new EE_Error(
5529
-                sprintf(
5530
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5531
-                        'event_espresso'),
5532
-                    $context,
5533
-                    'EEM_Base',
5534
-                    implode(',', $valid_cap_contexts)
5535
-                )
5536
-            );
5537
-        }
5538
-    }
5539
-
5540
-
5541
-
5542
-    /**
5543
-     * Clears all the models field caches. This is only useful when a sub-class
5544
-     * might have added a field or something and these caches might be invalidated
5545
-     */
5546
-    protected function _invalidate_field_caches()
5547
-    {
5548
-        $this->_cache_foreign_key_to_fields = array();
5549
-        $this->_cached_fields = null;
5550
-        $this->_cached_fields_non_db_only = null;
5551
-    }
3428
+		}
3429
+		return $null_friendly_where_conditions;
3430
+	}
3431
+
3432
+
3433
+
3434
+	/**
3435
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3436
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3437
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3438
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3439
+	 *
3440
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3441
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3442
+	 */
3443
+	private function _get_default_where_conditions($model_relation_path = null)
3444
+	{
3445
+		if ($this->_ignore_where_strategy) {
3446
+			return array();
3447
+		}
3448
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3449
+	}
3450
+
3451
+
3452
+
3453
+	/**
3454
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3455
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3456
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3457
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3458
+	 * Similar to _get_default_where_conditions
3459
+	 *
3460
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3461
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3462
+	 */
3463
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3464
+	{
3465
+		if ($this->_ignore_where_strategy) {
3466
+			return array();
3467
+		}
3468
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3469
+	}
3470
+
3471
+
3472
+
3473
+	/**
3474
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3475
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3476
+	 *
3477
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3478
+	 * @return string
3479
+	 * @throws \EE_Error
3480
+	 */
3481
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3482
+	{
3483
+		$selects = $this->_get_columns_to_select_for_this_model();
3484
+		foreach (
3485
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3486
+			$name_of_other_model_included
3487
+		) {
3488
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3489
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3490
+			foreach ($other_model_selects as $key => $value) {
3491
+				$selects[] = $value;
3492
+			}
3493
+		}
3494
+		return implode(", ", $selects);
3495
+	}
3496
+
3497
+
3498
+
3499
+	/**
3500
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3501
+	 * So that's going to be the columns for all the fields on the model
3502
+	 *
3503
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3504
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3505
+	 */
3506
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3507
+	{
3508
+		$fields = $this->field_settings();
3509
+		$selects = array();
3510
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3511
+			$this->get_this_model_name());
3512
+		foreach ($fields as $field_obj) {
3513
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3514
+						 . $field_obj->get_table_alias()
3515
+						 . "."
3516
+						 . $field_obj->get_table_column()
3517
+						 . " AS '"
3518
+						 . $table_alias_with_model_relation_chain_prefix
3519
+						 . $field_obj->get_table_alias()
3520
+						 . "."
3521
+						 . $field_obj->get_table_column()
3522
+						 . "'";
3523
+		}
3524
+		//make sure we are also getting the PKs of each table
3525
+		$tables = $this->get_tables();
3526
+		if (count($tables) > 1) {
3527
+			foreach ($tables as $table_obj) {
3528
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3529
+									   . $table_obj->get_fully_qualified_pk_column();
3530
+				if ( ! in_array($qualified_pk_column, $selects)) {
3531
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3532
+				}
3533
+			}
3534
+		}
3535
+		return $selects;
3536
+	}
3537
+
3538
+
3539
+
3540
+	/**
3541
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3542
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3543
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3544
+	 * SQL for joining, and the data types
3545
+	 *
3546
+	 * @param null|string                 $original_query_param
3547
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3548
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3549
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3550
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3551
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3552
+	 *                                                          or 'Registration's
3553
+	 * @param string                      $original_query_param what it originally was (eg
3554
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3555
+	 *                                                          matches $query_param
3556
+	 * @throws EE_Error
3557
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3558
+	 */
3559
+	private function _extract_related_model_info_from_query_param(
3560
+		$query_param,
3561
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3562
+		$query_param_type,
3563
+		$original_query_param = null
3564
+	) {
3565
+		if ($original_query_param === null) {
3566
+			$original_query_param = $query_param;
3567
+		}
3568
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3569
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3570
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3571
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3572
+		//check to see if we have a field on this model
3573
+		$this_model_fields = $this->field_settings(true);
3574
+		if (array_key_exists($query_param, $this_model_fields)) {
3575
+			if ($allow_fields) {
3576
+				return;
3577
+			} else {
3578
+				throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3579
+					"event_espresso"),
3580
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3581
+			}
3582
+		} //check if this is a special logic query param
3583
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3584
+			if ($allow_logic_query_params) {
3585
+				return;
3586
+			} else {
3587
+				throw new EE_Error(
3588
+					sprintf(
3589
+						__('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',
3590
+							'event_espresso'),
3591
+						implode('", "', $this->_logic_query_param_keys),
3592
+						$query_param,
3593
+						get_class($this),
3594
+						'<br />',
3595
+						"\t"
3596
+						. ' $passed_in_query_info = <pre>'
3597
+						. print_r($passed_in_query_info, true)
3598
+						. '</pre>'
3599
+						. "\n\t"
3600
+						. ' $query_param_type = '
3601
+						. $query_param_type
3602
+						. "\n\t"
3603
+						. ' $original_query_param = '
3604
+						. $original_query_param
3605
+					)
3606
+				);
3607
+			}
3608
+		} //check if it's a custom selection
3609
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3610
+			return;
3611
+		}
3612
+		//check if has a model name at the beginning
3613
+		//and
3614
+		//check if it's a field on a related model
3615
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3616
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3617
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3618
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3619
+				if ($query_param === '') {
3620
+					//nothing left to $query_param
3621
+					//we should actually end in a field name, not a model like this!
3622
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3623
+						"event_espresso"),
3624
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3625
+				} else {
3626
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3627
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3628
+						$passed_in_query_info, $query_param_type, $original_query_param);
3629
+					return;
3630
+				}
3631
+			} elseif ($query_param === $valid_related_model_name) {
3632
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3633
+				return;
3634
+			}
3635
+		}
3636
+		//ok so $query_param didn't start with a model name
3637
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3638
+		//it's wack, that's what it is
3639
+		throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3640
+			"event_espresso"),
3641
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3642
+	}
3643
+
3644
+
3645
+
3646
+	/**
3647
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3648
+	 * and store it on $passed_in_query_info
3649
+	 *
3650
+	 * @param string                      $model_name
3651
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3652
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3653
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3654
+	 *                                                          and are adding a join to 'Payment' with the original
3655
+	 *                                                          query param key
3656
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3657
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3658
+	 *                                                          Payment wants to add default query params so that it
3659
+	 *                                                          will know what models to prepend onto its default query
3660
+	 *                                                          params or in case it wants to rename tables (in case
3661
+	 *                                                          there are multiple joins to the same table)
3662
+	 * @return void
3663
+	 * @throws \EE_Error
3664
+	 */
3665
+	private function _add_join_to_model(
3666
+		$model_name,
3667
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3668
+		$original_query_param
3669
+	) {
3670
+		$relation_obj = $this->related_settings_for($model_name);
3671
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3672
+		//check if the relation is HABTM, because then we're essentially doing two joins
3673
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3674
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3675
+			$join_model_obj = $relation_obj->get_join_model();
3676
+			//replace the model specified with the join model for this relation chain, whi
3677
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3678
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3679
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3680
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3681
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3682
+			$passed_in_query_info->merge($new_query_info);
3683
+		}
3684
+		//now just join to the other table pointed to by the relation object, and add its data types
3685
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3686
+			array($model_relation_chain => $model_name),
3687
+			$relation_obj->get_join_statement($model_relation_chain));
3688
+		$passed_in_query_info->merge($new_query_info);
3689
+	}
3690
+
3691
+
3692
+
3693
+	/**
3694
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3695
+	 *
3696
+	 * @param array $where_params like EEM_Base::get_all
3697
+	 * @return string of SQL
3698
+	 * @throws \EE_Error
3699
+	 */
3700
+	private function _construct_where_clause($where_params)
3701
+	{
3702
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3703
+		if ($SQL) {
3704
+			return " WHERE " . $SQL;
3705
+		} else {
3706
+			return '';
3707
+		}
3708
+	}
3709
+
3710
+
3711
+
3712
+	/**
3713
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3714
+	 * and should be passed HAVING parameters, not WHERE parameters
3715
+	 *
3716
+	 * @param array $having_params
3717
+	 * @return string
3718
+	 * @throws \EE_Error
3719
+	 */
3720
+	private function _construct_having_clause($having_params)
3721
+	{
3722
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3723
+		if ($SQL) {
3724
+			return " HAVING " . $SQL;
3725
+		} else {
3726
+			return '';
3727
+		}
3728
+	}
3729
+
3730
+
3731
+
3732
+	/**
3733
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3734
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3735
+	 * EEM_Attendee.
3736
+	 *
3737
+	 * @param string $field_name
3738
+	 * @param string $model_name
3739
+	 * @return EE_Model_Field_Base
3740
+	 * @throws EE_Error
3741
+	 */
3742
+	protected function _get_field_on_model($field_name, $model_name)
3743
+	{
3744
+		$model_class = 'EEM_' . $model_name;
3745
+		$model_filepath = $model_class . ".model.php";
3746
+		if (is_readable($model_filepath)) {
3747
+			require_once($model_filepath);
3748
+			$model_instance = call_user_func($model_name . "::instance");
3749
+			/* @var $model_instance EEM_Base */
3750
+			return $model_instance->field_settings_for($field_name);
3751
+		} else {
3752
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3753
+				'event_espresso'), $model_name, $model_class, $model_filepath));
3754
+		}
3755
+	}
3756
+
3757
+
3758
+
3759
+	/**
3760
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3761
+	 * Event_Meta.meta_value = 'foo'))"
3762
+	 *
3763
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3764
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3765
+	 * @throws EE_Error
3766
+	 * @return string of SQL
3767
+	 */
3768
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3769
+	{
3770
+		$where_clauses = array();
3771
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3772
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3773
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3774
+				switch ($query_param) {
3775
+					case 'not':
3776
+					case 'NOT':
3777
+						$where_clauses[] = "! ("
3778
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3779
+								$glue)
3780
+										   . ")";
3781
+						break;
3782
+					case 'and':
3783
+					case 'AND':
3784
+						$where_clauses[] = " ("
3785
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3786
+								' AND ')
3787
+										   . ")";
3788
+						break;
3789
+					case 'or':
3790
+					case 'OR':
3791
+						$where_clauses[] = " ("
3792
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3793
+								' OR ')
3794
+										   . ")";
3795
+						break;
3796
+				}
3797
+			} else {
3798
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3799
+				//if it's not a normal field, maybe it's a custom selection?
3800
+				if ( ! $field_obj) {
3801
+					if (isset($this->_custom_selections[$query_param][1])) {
3802
+						$field_obj = $this->_custom_selections[$query_param][1];
3803
+					} else {
3804
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3805
+							"event_espresso"), $query_param));
3806
+					}
3807
+				}
3808
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3809
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3810
+			}
3811
+		}
3812
+		return $where_clauses ? implode($glue, $where_clauses) : '';
3813
+	}
3814
+
3815
+
3816
+
3817
+	/**
3818
+	 * Takes the input parameter and extract the table name (alias) and column name
3819
+	 *
3820
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3821
+	 * @throws EE_Error
3822
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3823
+	 */
3824
+	private function _deduce_column_name_from_query_param($query_param)
3825
+	{
3826
+		$field = $this->_deduce_field_from_query_param($query_param);
3827
+		if ($field) {
3828
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
3829
+				$query_param);
3830
+			return $table_alias_prefix . $field->get_qualified_column();
3831
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
3832
+			//maybe it's custom selection item?
3833
+			//if so, just use it as the "column name"
3834
+			return $query_param;
3835
+		} else {
3836
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
3837
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
3838
+		}
3839
+	}
3840
+
3841
+
3842
+
3843
+	/**
3844
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
3845
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
3846
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
3847
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
3848
+	 *
3849
+	 * @param string $condition_query_param_key
3850
+	 * @return string
3851
+	 */
3852
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
3853
+	{
3854
+		$pos_of_star = strpos($condition_query_param_key, '*');
3855
+		if ($pos_of_star === false) {
3856
+			return $condition_query_param_key;
3857
+		} else {
3858
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
3859
+			return $condition_query_param_sans_star;
3860
+		}
3861
+	}
3862
+
3863
+
3864
+
3865
+	/**
3866
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
3867
+	 *
3868
+	 * @param                            mixed      array | string    $op_and_value
3869
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
3870
+	 * @throws EE_Error
3871
+	 * @return string
3872
+	 */
3873
+	private function _construct_op_and_value($op_and_value, $field_obj)
3874
+	{
3875
+		if (is_array($op_and_value)) {
3876
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
3877
+			if ( ! $operator) {
3878
+				$php_array_like_string = array();
3879
+				foreach ($op_and_value as $key => $value) {
3880
+					$php_array_like_string[] = "$key=>$value";
3881
+				}
3882
+				throw new EE_Error(
3883
+					sprintf(
3884
+						__(
3885
+							"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))",
3886
+							"event_espresso"
3887
+						),
3888
+						implode(",", $php_array_like_string)
3889
+					)
3890
+				);
3891
+			}
3892
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
3893
+		} else {
3894
+			$operator = '=';
3895
+			$value = $op_and_value;
3896
+		}
3897
+		//check to see if the value is actually another field
3898
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
3899
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
3900
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
3901
+			//in this case, the value should be an array, or at least a comma-separated list
3902
+			//it will need to handle a little differently
3903
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
3904
+			//note: $cleaned_value has already been run through $wpdb->prepare()
3905
+			return $operator . SP . $cleaned_value;
3906
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
3907
+			//the value should be an array with count of two.
3908
+			if (count($value) !== 2) {
3909
+				throw new EE_Error(
3910
+					sprintf(
3911
+						__(
3912
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
3913
+							'event_espresso'
3914
+						),
3915
+						"BETWEEN"
3916
+					)
3917
+				);
3918
+			}
3919
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
3920
+			return $operator . SP . $cleaned_value;
3921
+		} elseif (in_array($operator, $this->_null_style_operators)) {
3922
+			if ($value !== null) {
3923
+				throw new EE_Error(
3924
+					sprintf(
3925
+						__(
3926
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
3927
+							"event_espresso"
3928
+						),
3929
+						$value,
3930
+						$operator
3931
+					)
3932
+				);
3933
+			}
3934
+			return $operator;
3935
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
3936
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
3937
+			//remove other junk. So just treat it as a string.
3938
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
3939
+		} elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3940
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
3941
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3942
+			throw new EE_Error(
3943
+				sprintf(
3944
+					__(
3945
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
3946
+						'event_espresso'
3947
+					),
3948
+					$operator,
3949
+					$operator
3950
+				)
3951
+			);
3952
+		} elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
3953
+			throw new EE_Error(
3954
+				sprintf(
3955
+					__(
3956
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
3957
+						'event_espresso'
3958
+					),
3959
+					$operator,
3960
+					$operator
3961
+				)
3962
+			);
3963
+		} else {
3964
+			throw new EE_Error(
3965
+				sprintf(
3966
+					__(
3967
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
3968
+						"event_espresso"
3969
+					),
3970
+					http_build_query($op_and_value)
3971
+				)
3972
+			);
3973
+		}
3974
+	}
3975
+
3976
+
3977
+
3978
+	/**
3979
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
3980
+	 *
3981
+	 * @param array                      $values
3982
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
3983
+	 *                                              '%s'
3984
+	 * @return string
3985
+	 * @throws \EE_Error
3986
+	 */
3987
+	public function _construct_between_value($values, $field_obj)
3988
+	{
3989
+		$cleaned_values = array();
3990
+		foreach ($values as $value) {
3991
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
3992
+		}
3993
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
3994
+	}
3995
+
3996
+
3997
+
3998
+	/**
3999
+	 * Takes an array or a comma-separated list of $values and cleans them
4000
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4001
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4002
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4003
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4004
+	 *
4005
+	 * @param mixed                      $values    array or comma-separated string
4006
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4007
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4008
+	 * @throws \EE_Error
4009
+	 */
4010
+	public function _construct_in_value($values, $field_obj)
4011
+	{
4012
+		//check if the value is a CSV list
4013
+		if (is_string($values)) {
4014
+			//in which case, turn it into an array
4015
+			$values = explode(",", $values);
4016
+		}
4017
+		$cleaned_values = array();
4018
+		foreach ($values as $value) {
4019
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4020
+		}
4021
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4022
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4023
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4024
+		if (empty($cleaned_values)) {
4025
+			$all_fields = $this->field_settings();
4026
+			$a_field = array_shift($all_fields);
4027
+			$main_table = $this->_get_main_table();
4028
+			$cleaned_values[] = "SELECT "
4029
+								. $a_field->get_table_column()
4030
+								. " FROM "
4031
+								. $main_table->get_table_name()
4032
+								. " WHERE FALSE";
4033
+		}
4034
+		return "(" . implode(",", $cleaned_values) . ")";
4035
+	}
4036
+
4037
+
4038
+
4039
+	/**
4040
+	 * @param mixed                      $value
4041
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4042
+	 * @throws EE_Error
4043
+	 * @return false|null|string
4044
+	 */
4045
+	private function _wpdb_prepare_using_field($value, $field_obj)
4046
+	{
4047
+		/** @type WPDB $wpdb */
4048
+		global $wpdb;
4049
+		if ($field_obj instanceof EE_Model_Field_Base) {
4050
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4051
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4052
+		} else {//$field_obj should really just be a data type
4053
+			if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4054
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4055
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4056
+			}
4057
+			return $wpdb->prepare($field_obj, $value);
4058
+		}
4059
+	}
4060
+
4061
+
4062
+
4063
+	/**
4064
+	 * Takes the input parameter and finds the model field that it indicates.
4065
+	 *
4066
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4067
+	 * @throws EE_Error
4068
+	 * @return EE_Model_Field_Base
4069
+	 */
4070
+	protected function _deduce_field_from_query_param($query_param_name)
4071
+	{
4072
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4073
+		//which will help us find the database table and column
4074
+		$query_param_parts = explode(".", $query_param_name);
4075
+		if (empty($query_param_parts)) {
4076
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4077
+				'event_espresso'), $query_param_name));
4078
+		}
4079
+		$number_of_parts = count($query_param_parts);
4080
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4081
+		if ($number_of_parts === 1) {
4082
+			$field_name = $last_query_param_part;
4083
+			$model_obj = $this;
4084
+		} else {// $number_of_parts >= 2
4085
+			//the last part is the column name, and there are only 2parts. therefore...
4086
+			$field_name = $last_query_param_part;
4087
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4088
+		}
4089
+		try {
4090
+			return $model_obj->field_settings_for($field_name);
4091
+		} catch (EE_Error $e) {
4092
+			return null;
4093
+		}
4094
+	}
4095
+
4096
+
4097
+
4098
+	/**
4099
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4100
+	 * alias and column which corresponds to it
4101
+	 *
4102
+	 * @param string $field_name
4103
+	 * @throws EE_Error
4104
+	 * @return string
4105
+	 */
4106
+	public function _get_qualified_column_for_field($field_name)
4107
+	{
4108
+		$all_fields = $this->field_settings();
4109
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4110
+		if ($field) {
4111
+			return $field->get_qualified_column();
4112
+		} else {
4113
+			throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4114
+				'event_espresso'), $field_name, get_class($this)));
4115
+		}
4116
+	}
4117
+
4118
+
4119
+
4120
+	/**
4121
+	 * constructs the select use on special limit joins
4122
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4123
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4124
+	 * (as that is typically where the limits would be set).
4125
+	 *
4126
+	 * @param  string       $table_alias The table the select is being built for
4127
+	 * @param  mixed|string $limit       The limit for this select
4128
+	 * @return string                The final select join element for the query.
4129
+	 */
4130
+	public function _construct_limit_join_select($table_alias, $limit)
4131
+	{
4132
+		$SQL = '';
4133
+		foreach ($this->_tables as $table_obj) {
4134
+			if ($table_obj instanceof EE_Primary_Table) {
4135
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4136
+					? $table_obj->get_select_join_limit($limit)
4137
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4138
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4139
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4140
+					? $table_obj->get_select_join_limit_join($limit)
4141
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4142
+			}
4143
+		}
4144
+		return $SQL;
4145
+	}
4146
+
4147
+
4148
+
4149
+	/**
4150
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4151
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4152
+	 *
4153
+	 * @return string SQL
4154
+	 * @throws \EE_Error
4155
+	 */
4156
+	public function _construct_internal_join()
4157
+	{
4158
+		$SQL = $this->_get_main_table()->get_table_sql();
4159
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4160
+		return $SQL;
4161
+	}
4162
+
4163
+
4164
+
4165
+	/**
4166
+	 * Constructs the SQL for joining all the tables on this model.
4167
+	 * Normally $alias should be the primary table's alias, but in cases where
4168
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4169
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4170
+	 * alias, this will construct SQL like:
4171
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4172
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4173
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4174
+	 *
4175
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4176
+	 * @return string
4177
+	 */
4178
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4179
+	{
4180
+		$SQL = '';
4181
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4182
+		foreach ($this->_tables as $table_obj) {
4183
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4184
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4185
+					//so we're joining to this table, meaning the table is already in
4186
+					//the FROM statement, BUT the primary table isn't. So we want
4187
+					//to add the inverse join sql
4188
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4189
+				} else {
4190
+					//just add a regular JOIN to this table from the primary table
4191
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4192
+				}
4193
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4194
+		}
4195
+		return $SQL;
4196
+	}
4197
+
4198
+
4199
+
4200
+	/**
4201
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4202
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4203
+	 * their data type (eg, '%s', '%d', etc)
4204
+	 *
4205
+	 * @return array
4206
+	 */
4207
+	public function _get_data_types()
4208
+	{
4209
+		$data_types = array();
4210
+		foreach ($this->field_settings() as $field_obj) {
4211
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4212
+			/** @var $field_obj EE_Model_Field_Base */
4213
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4214
+		}
4215
+		return $data_types;
4216
+	}
4217
+
4218
+
4219
+
4220
+	/**
4221
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4222
+	 *
4223
+	 * @param string $model_name
4224
+	 * @throws EE_Error
4225
+	 * @return EEM_Base
4226
+	 */
4227
+	public function get_related_model_obj($model_name)
4228
+	{
4229
+		$model_classname = "EEM_" . $model_name;
4230
+		if ( ! class_exists($model_classname)) {
4231
+			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",
4232
+				'event_espresso'), $model_name, $model_classname));
4233
+		}
4234
+		return call_user_func($model_classname . "::instance");
4235
+	}
4236
+
4237
+
4238
+
4239
+	/**
4240
+	 * Returns the array of EE_ModelRelations for this model.
4241
+	 *
4242
+	 * @return EE_Model_Relation_Base[]
4243
+	 */
4244
+	public function relation_settings()
4245
+	{
4246
+		return $this->_model_relations;
4247
+	}
4248
+
4249
+
4250
+
4251
+	/**
4252
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4253
+	 * because without THOSE models, this model probably doesn't have much purpose.
4254
+	 * (Eg, without an event, datetimes have little purpose.)
4255
+	 *
4256
+	 * @return EE_Belongs_To_Relation[]
4257
+	 */
4258
+	public function belongs_to_relations()
4259
+	{
4260
+		$belongs_to_relations = array();
4261
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4262
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4263
+				$belongs_to_relations[$model_name] = $relation_obj;
4264
+			}
4265
+		}
4266
+		return $belongs_to_relations;
4267
+	}
4268
+
4269
+
4270
+
4271
+	/**
4272
+	 * Returns the specified EE_Model_Relation, or throws an exception
4273
+	 *
4274
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4275
+	 * @throws EE_Error
4276
+	 * @return EE_Model_Relation_Base
4277
+	 */
4278
+	public function related_settings_for($relation_name)
4279
+	{
4280
+		$relatedModels = $this->relation_settings();
4281
+		if ( ! array_key_exists($relation_name, $relatedModels)) {
4282
+			throw new EE_Error(
4283
+				sprintf(
4284
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4285
+						'event_espresso'),
4286
+					$relation_name,
4287
+					$this->_get_class_name(),
4288
+					implode(', ', array_keys($relatedModels))
4289
+				)
4290
+			);
4291
+		}
4292
+		return $relatedModels[$relation_name];
4293
+	}
4294
+
4295
+
4296
+
4297
+	/**
4298
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4299
+	 * fields
4300
+	 *
4301
+	 * @param string $fieldName
4302
+	 * @throws EE_Error
4303
+	 * @return EE_Model_Field_Base
4304
+	 */
4305
+	public function field_settings_for($fieldName)
4306
+	{
4307
+		$fieldSettings = $this->field_settings(true);
4308
+		if ( ! array_key_exists($fieldName, $fieldSettings)) {
4309
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4310
+				get_class($this)));
4311
+		}
4312
+		return $fieldSettings[$fieldName];
4313
+	}
4314
+
4315
+
4316
+
4317
+	/**
4318
+	 * Checks if this field exists on this model
4319
+	 *
4320
+	 * @param string $fieldName a key in the model's _field_settings array
4321
+	 * @return boolean
4322
+	 */
4323
+	public function has_field($fieldName)
4324
+	{
4325
+		$fieldSettings = $this->field_settings(true);
4326
+		if (isset($fieldSettings[$fieldName])) {
4327
+			return true;
4328
+		} else {
4329
+			return false;
4330
+		}
4331
+	}
4332
+
4333
+
4334
+
4335
+	/**
4336
+	 * Returns whether or not this model has a relation to the specified model
4337
+	 *
4338
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4339
+	 * @return boolean
4340
+	 */
4341
+	public function has_relation($relation_name)
4342
+	{
4343
+		$relations = $this->relation_settings();
4344
+		if (isset($relations[$relation_name])) {
4345
+			return true;
4346
+		} else {
4347
+			return false;
4348
+		}
4349
+	}
4350
+
4351
+
4352
+
4353
+	/**
4354
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4355
+	 * Eg, on EE_Answer that would be ANS_ID field object
4356
+	 *
4357
+	 * @param $field_obj
4358
+	 * @return boolean
4359
+	 */
4360
+	public function is_primary_key_field($field_obj)
4361
+	{
4362
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4363
+	}
4364
+
4365
+
4366
+
4367
+	/**
4368
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4369
+	 * Eg, on EE_Answer that would be ANS_ID field object
4370
+	 *
4371
+	 * @return EE_Model_Field_Base
4372
+	 * @throws EE_Error
4373
+	 */
4374
+	public function get_primary_key_field()
4375
+	{
4376
+		if ($this->_primary_key_field === null) {
4377
+			foreach ($this->field_settings(true) as $field_obj) {
4378
+				if ($this->is_primary_key_field($field_obj)) {
4379
+					$this->_primary_key_field = $field_obj;
4380
+					break;
4381
+				}
4382
+			}
4383
+			if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4384
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4385
+					get_class($this)));
4386
+			}
4387
+		}
4388
+		return $this->_primary_key_field;
4389
+	}
4390
+
4391
+
4392
+
4393
+	/**
4394
+	 * Returns whether or not not there is a primary key on this model.
4395
+	 * Internally does some caching.
4396
+	 *
4397
+	 * @return boolean
4398
+	 */
4399
+	public function has_primary_key_field()
4400
+	{
4401
+		if ($this->_has_primary_key_field === null) {
4402
+			try {
4403
+				$this->get_primary_key_field();
4404
+				$this->_has_primary_key_field = true;
4405
+			} catch (EE_Error $e) {
4406
+				$this->_has_primary_key_field = false;
4407
+			}
4408
+		}
4409
+		return $this->_has_primary_key_field;
4410
+	}
4411
+
4412
+
4413
+
4414
+	/**
4415
+	 * Finds the first field of type $field_class_name.
4416
+	 *
4417
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4418
+	 *                                 EE_Foreign_Key_Field, etc
4419
+	 * @return EE_Model_Field_Base or null if none is found
4420
+	 */
4421
+	public function get_a_field_of_type($field_class_name)
4422
+	{
4423
+		foreach ($this->field_settings() as $field) {
4424
+			if ($field instanceof $field_class_name) {
4425
+				return $field;
4426
+			}
4427
+		}
4428
+		return null;
4429
+	}
4430
+
4431
+
4432
+
4433
+	/**
4434
+	 * Gets a foreign key field pointing to model.
4435
+	 *
4436
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4437
+	 * @return EE_Foreign_Key_Field_Base
4438
+	 * @throws EE_Error
4439
+	 */
4440
+	public function get_foreign_key_to($model_name)
4441
+	{
4442
+		if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4443
+			foreach ($this->field_settings() as $field) {
4444
+				if (
4445
+					$field instanceof EE_Foreign_Key_Field_Base
4446
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4447
+				) {
4448
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4449
+					break;
4450
+				}
4451
+			}
4452
+			if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4453
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4454
+					'event_espresso'), $model_name, get_class($this)));
4455
+			}
4456
+		}
4457
+		return $this->_cache_foreign_key_to_fields[$model_name];
4458
+	}
4459
+
4460
+
4461
+
4462
+	/**
4463
+	 * Gets the actual table for the table alias
4464
+	 *
4465
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4466
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4467
+	 *                            Either one works
4468
+	 * @return EE_Table_Base
4469
+	 */
4470
+	public function get_table_for_alias($table_alias)
4471
+	{
4472
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4473
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4474
+	}
4475
+
4476
+
4477
+
4478
+	/**
4479
+	 * Returns a flat array of all field son this model, instead of organizing them
4480
+	 * by table_alias as they are in the constructor.
4481
+	 *
4482
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4483
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4484
+	 */
4485
+	public function field_settings($include_db_only_fields = false)
4486
+	{
4487
+		if ($include_db_only_fields) {
4488
+			if ($this->_cached_fields === null) {
4489
+				$this->_cached_fields = array();
4490
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4491
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4492
+						$this->_cached_fields[$field_name] = $field_obj;
4493
+					}
4494
+				}
4495
+			}
4496
+			return $this->_cached_fields;
4497
+		} else {
4498
+			if ($this->_cached_fields_non_db_only === null) {
4499
+				$this->_cached_fields_non_db_only = array();
4500
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4501
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4502
+						/** @var $field_obj EE_Model_Field_Base */
4503
+						if ( ! $field_obj->is_db_only_field()) {
4504
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4505
+						}
4506
+					}
4507
+				}
4508
+			}
4509
+			return $this->_cached_fields_non_db_only;
4510
+		}
4511
+	}
4512
+
4513
+
4514
+
4515
+	/**
4516
+	 *        cycle though array of attendees and create objects out of each item
4517
+	 *
4518
+	 * @access        private
4519
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4520
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4521
+	 *                          numerically indexed)
4522
+	 * @throws \EE_Error
4523
+	 */
4524
+	protected function _create_objects($rows = array())
4525
+	{
4526
+		$array_of_objects = array();
4527
+		if (empty($rows)) {
4528
+			return array();
4529
+		}
4530
+		$count_if_model_has_no_primary_key = 0;
4531
+		$has_primary_key = $this->has_primary_key_field();
4532
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4533
+		foreach ((array)$rows as $row) {
4534
+			if (empty($row)) {
4535
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4536
+				return array();
4537
+			}
4538
+			//check if we've already set this object in the results array,
4539
+			//in which case there's no need to process it further (again)
4540
+			if ($has_primary_key) {
4541
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4542
+					$row,
4543
+					$primary_key_field->get_qualified_column(),
4544
+					$primary_key_field->get_table_column()
4545
+				);
4546
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4547
+					continue;
4548
+				}
4549
+			}
4550
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4551
+			if ( ! $classInstance) {
4552
+				throw new EE_Error(
4553
+					sprintf(
4554
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4555
+						$this->get_this_model_name(),
4556
+						http_build_query($row)
4557
+					)
4558
+				);
4559
+			}
4560
+			//set the timezone on the instantiated objects
4561
+			$classInstance->set_timezone($this->_timezone);
4562
+			//make sure if there is any timezone setting present that we set the timezone for the object
4563
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4564
+			$array_of_objects[$key] = $classInstance;
4565
+			//also, for all the relations of type BelongsTo, see if we can cache
4566
+			//those related models
4567
+			//(we could do this for other relations too, but if there are conditions
4568
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4569
+			//so it requires a little more thought than just caching them immediately...)
4570
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4571
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4572
+					//check if this model's INFO is present. If so, cache it on the model
4573
+					$other_model = $relation_obj->get_other_model();
4574
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4575
+					//if we managed to make a model object from the results, cache it on the main model object
4576
+					if ($other_model_obj_maybe) {
4577
+						//set timezone on these other model objects if they are present
4578
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4579
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4580
+					}
4581
+				}
4582
+			}
4583
+		}
4584
+		return $array_of_objects;
4585
+	}
4586
+
4587
+
4588
+
4589
+	/**
4590
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4591
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4592
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4593
+	 * object (as set in the model_field!).
4594
+	 *
4595
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4596
+	 */
4597
+	public function create_default_object()
4598
+	{
4599
+		$this_model_fields_and_values = array();
4600
+		//setup the row using default values;
4601
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4602
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4603
+		}
4604
+		$className = $this->_get_class_name();
4605
+		$classInstance = EE_Registry::instance()
4606
+									->load_class($className, array($this_model_fields_and_values), false, false);
4607
+		return $classInstance;
4608
+	}
4609
+
4610
+
4611
+
4612
+	/**
4613
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4614
+	 *                             or an stdClass where each property is the name of a column,
4615
+	 * @return EE_Base_Class
4616
+	 * @throws \EE_Error
4617
+	 */
4618
+	public function instantiate_class_from_array_or_object($cols_n_values)
4619
+	{
4620
+		if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4621
+			$cols_n_values = get_object_vars($cols_n_values);
4622
+		}
4623
+		$primary_key = null;
4624
+		//make sure the array only has keys that are fields/columns on this model
4625
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4626
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4627
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4628
+		}
4629
+		$className = $this->_get_class_name();
4630
+		//check we actually found results that we can use to build our model object
4631
+		//if not, return null
4632
+		if ($this->has_primary_key_field()) {
4633
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4634
+				return null;
4635
+			}
4636
+		} else if ($this->unique_indexes()) {
4637
+			$first_column = reset($this_model_fields_n_values);
4638
+			if (empty($first_column)) {
4639
+				return null;
4640
+			}
4641
+		}
4642
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4643
+		if ($primary_key) {
4644
+			$classInstance = $this->get_from_entity_map($primary_key);
4645
+			if ( ! $classInstance) {
4646
+				$classInstance = EE_Registry::instance()
4647
+											->load_class($className,
4648
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4649
+				// add this new object to the entity map
4650
+				$classInstance = $this->add_to_entity_map($classInstance);
4651
+			}
4652
+		} else {
4653
+			$classInstance = EE_Registry::instance()
4654
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4655
+											true, false);
4656
+		}
4657
+		//it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4658
+		$this->set_timezone($classInstance->get_timezone());
4659
+		return $classInstance;
4660
+	}
4661
+
4662
+
4663
+
4664
+	/**
4665
+	 * Gets the model object from the  entity map if it exists
4666
+	 *
4667
+	 * @param int|string $id the ID of the model object
4668
+	 * @return EE_Base_Class
4669
+	 */
4670
+	public function get_from_entity_map($id)
4671
+	{
4672
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4673
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4674
+	}
4675
+
4676
+
4677
+
4678
+	/**
4679
+	 * add_to_entity_map
4680
+	 * Adds the object to the model's entity mappings
4681
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4682
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4683
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4684
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4685
+	 *        then this method should be called immediately after the update query
4686
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4687
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4688
+	 *
4689
+	 * @param    EE_Base_Class $object
4690
+	 * @throws EE_Error
4691
+	 * @return \EE_Base_Class
4692
+	 */
4693
+	public function add_to_entity_map(EE_Base_Class $object)
4694
+	{
4695
+		$className = $this->_get_class_name();
4696
+		if ( ! $object instanceof $className) {
4697
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4698
+				is_object($object) ? get_class($object) : $object, $className));
4699
+		}
4700
+		/** @var $object EE_Base_Class */
4701
+		if ( ! $object->ID()) {
4702
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4703
+				"event_espresso"), get_class($this)));
4704
+		}
4705
+		// double check it's not already there
4706
+		$classInstance = $this->get_from_entity_map($object->ID());
4707
+		if ($classInstance) {
4708
+			return $classInstance;
4709
+		} else {
4710
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4711
+			return $object;
4712
+		}
4713
+	}
4714
+
4715
+
4716
+
4717
+	/**
4718
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4719
+	 * if no identifier is provided, then the entire entity map is emptied
4720
+	 *
4721
+	 * @param int|string $id the ID of the model object
4722
+	 * @return boolean
4723
+	 */
4724
+	public function clear_entity_map($id = null)
4725
+	{
4726
+		if (empty($id)) {
4727
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4728
+			return true;
4729
+		}
4730
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4731
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4732
+			return true;
4733
+		}
4734
+		return false;
4735
+	}
4736
+
4737
+
4738
+
4739
+	/**
4740
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4741
+	 * Given an array where keys are column (or column alias) names and values,
4742
+	 * returns an array of their corresponding field names and database values
4743
+	 *
4744
+	 * @param array $cols_n_values
4745
+	 * @return array
4746
+	 */
4747
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4748
+	{
4749
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4750
+	}
4751
+
4752
+
4753
+
4754
+	/**
4755
+	 * _deduce_fields_n_values_from_cols_n_values
4756
+	 * Given an array where keys are column (or column alias) names and values,
4757
+	 * returns an array of their corresponding field names and database values
4758
+	 *
4759
+	 * @param string $cols_n_values
4760
+	 * @return array
4761
+	 */
4762
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
4763
+	{
4764
+		$this_model_fields_n_values = array();
4765
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
4766
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
4767
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
4768
+			//there is a primary key on this table and its not set. Use defaults for all its columns
4769
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
4770
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4771
+					if ( ! $field_obj->is_db_only_field()) {
4772
+						//prepare field as if its coming from db
4773
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4774
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
4775
+					}
4776
+				}
4777
+			} else {
4778
+				//the table's rows existed. Use their values
4779
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4780
+					if ( ! $field_obj->is_db_only_field()) {
4781
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4782
+							$cols_n_values, $field_obj->get_qualified_column(),
4783
+							$field_obj->get_table_column()
4784
+						);
4785
+					}
4786
+				}
4787
+			}
4788
+		}
4789
+		return $this_model_fields_n_values;
4790
+	}
4791
+
4792
+
4793
+
4794
+	/**
4795
+	 * @param $cols_n_values
4796
+	 * @param $qualified_column
4797
+	 * @param $regular_column
4798
+	 * @return null
4799
+	 */
4800
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
4801
+	{
4802
+		$value = null;
4803
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4804
+		//does the field on the model relate to this column retrieved from the db?
4805
+		//or is it a db-only field? (not relating to the model)
4806
+		if (isset($cols_n_values[$qualified_column])) {
4807
+			$value = $cols_n_values[$qualified_column];
4808
+		} elseif (isset($cols_n_values[$regular_column])) {
4809
+			$value = $cols_n_values[$regular_column];
4810
+		}
4811
+		return $value;
4812
+	}
4813
+
4814
+
4815
+
4816
+	/**
4817
+	 * refresh_entity_map_from_db
4818
+	 * Makes sure the model object in the entity map at $id assumes the values
4819
+	 * of the database (opposite of EE_base_Class::save())
4820
+	 *
4821
+	 * @param int|string $id
4822
+	 * @return EE_Base_Class
4823
+	 * @throws \EE_Error
4824
+	 */
4825
+	public function refresh_entity_map_from_db($id)
4826
+	{
4827
+		$obj_in_map = $this->get_from_entity_map($id);
4828
+		if ($obj_in_map) {
4829
+			$wpdb_results = $this->_get_all_wpdb_results(
4830
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
4831
+			);
4832
+			if ($wpdb_results && is_array($wpdb_results)) {
4833
+				$one_row = reset($wpdb_results);
4834
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
4835
+					$obj_in_map->set_from_db($field_name, $db_value);
4836
+				}
4837
+				//clear the cache of related model objects
4838
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4839
+					$obj_in_map->clear_cache($relation_name, null, true);
4840
+				}
4841
+			}
4842
+			return $obj_in_map;
4843
+		} else {
4844
+			return $this->get_one_by_ID($id);
4845
+		}
4846
+	}
4847
+
4848
+
4849
+
4850
+	/**
4851
+	 * refresh_entity_map_with
4852
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
4853
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
4854
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
4855
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
4856
+	 *
4857
+	 * @param int|string    $id
4858
+	 * @param EE_Base_Class $replacing_model_obj
4859
+	 * @return \EE_Base_Class
4860
+	 * @throws \EE_Error
4861
+	 */
4862
+	public function refresh_entity_map_with($id, $replacing_model_obj)
4863
+	{
4864
+		$obj_in_map = $this->get_from_entity_map($id);
4865
+		if ($obj_in_map) {
4866
+			if ($replacing_model_obj instanceof EE_Base_Class) {
4867
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
4868
+					$obj_in_map->set($field_name, $value);
4869
+				}
4870
+				//make the model object in the entity map's cache match the $replacing_model_obj
4871
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4872
+					$obj_in_map->clear_cache($relation_name, null, true);
4873
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
4874
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
4875
+					}
4876
+				}
4877
+			}
4878
+			return $obj_in_map;
4879
+		} else {
4880
+			$this->add_to_entity_map($replacing_model_obj);
4881
+			return $replacing_model_obj;
4882
+		}
4883
+	}
4884
+
4885
+
4886
+
4887
+	/**
4888
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
4889
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
4890
+	 * require_once($this->_getClassName().".class.php");
4891
+	 *
4892
+	 * @return string
4893
+	 */
4894
+	private function _get_class_name()
4895
+	{
4896
+		return "EE_" . $this->get_this_model_name();
4897
+	}
4898
+
4899
+
4900
+
4901
+	/**
4902
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
4903
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
4904
+	 * it would be 'Events'.
4905
+	 *
4906
+	 * @param int $quantity
4907
+	 * @return string
4908
+	 */
4909
+	public function item_name($quantity = 1)
4910
+	{
4911
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
4912
+	}
4913
+
4914
+
4915
+
4916
+	/**
4917
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
4918
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
4919
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
4920
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
4921
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
4922
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
4923
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
4924
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
4925
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
4926
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
4927
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
4928
+	 *        return $previousReturnValue.$returnString;
4929
+	 * }
4930
+	 * require('EEM_Answer.model.php');
4931
+	 * $answer=EEM_Answer::instance();
4932
+	 * echo $answer->my_callback('monkeys',100);
4933
+	 * //will output "you called my_callback! and passed args:monkeys,100"
4934
+	 *
4935
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
4936
+	 * @param array  $args       array of original arguments passed to the function
4937
+	 * @throws EE_Error
4938
+	 * @return mixed whatever the plugin which calls add_filter decides
4939
+	 */
4940
+	public function __call($methodName, $args)
4941
+	{
4942
+		$className = get_class($this);
4943
+		$tagName = "FHEE__{$className}__{$methodName}";
4944
+		if ( ! has_filter($tagName)) {
4945
+			throw new EE_Error(
4946
+				sprintf(
4947
+					__('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 );',
4948
+						'event_espresso'),
4949
+					$methodName,
4950
+					$className,
4951
+					$tagName,
4952
+					'<br />'
4953
+				)
4954
+			);
4955
+		}
4956
+		return apply_filters($tagName, null, $this, $args);
4957
+	}
4958
+
4959
+
4960
+
4961
+	/**
4962
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
4963
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
4964
+	 *
4965
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
4966
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
4967
+	 *                                                       the object's class name
4968
+	 *                                                       or object's ID
4969
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
4970
+	 *                                                       exists in the database. If it does not, we add it
4971
+	 * @throws EE_Error
4972
+	 * @return EE_Base_Class
4973
+	 */
4974
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
4975
+	{
4976
+		$className = $this->_get_class_name();
4977
+		if ($base_class_obj_or_id instanceof $className) {
4978
+			$model_object = $base_class_obj_or_id;
4979
+		} else {
4980
+			$primary_key_field = $this->get_primary_key_field();
4981
+			if (
4982
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
4983
+				&& (
4984
+					is_int($base_class_obj_or_id)
4985
+					|| is_string($base_class_obj_or_id)
4986
+				)
4987
+			) {
4988
+				// assume it's an ID.
4989
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
4990
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
4991
+			} else if (
4992
+				$primary_key_field instanceof EE_Primary_Key_String_Field
4993
+				&& is_string($base_class_obj_or_id)
4994
+			) {
4995
+				// assume its a string representation of the object
4996
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
4997
+			} else {
4998
+				throw new EE_Error(
4999
+					sprintf(
5000
+						__(
5001
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5002
+							'event_espresso'
5003
+						),
5004
+						$base_class_obj_or_id,
5005
+						$this->_get_class_name(),
5006
+						print_r($base_class_obj_or_id, true)
5007
+					)
5008
+				);
5009
+			}
5010
+		}
5011
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5012
+			$model_object->save();
5013
+		}
5014
+		return $model_object;
5015
+	}
5016
+
5017
+
5018
+
5019
+	/**
5020
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5021
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5022
+	 * returns it ID.
5023
+	 *
5024
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5025
+	 * @return int|string depending on the type of this model object's ID
5026
+	 * @throws EE_Error
5027
+	 */
5028
+	public function ensure_is_ID($base_class_obj_or_id)
5029
+	{
5030
+		$className = $this->_get_class_name();
5031
+		if ($base_class_obj_or_id instanceof $className) {
5032
+			/** @var $base_class_obj_or_id EE_Base_Class */
5033
+			$id = $base_class_obj_or_id->ID();
5034
+		} elseif (is_int($base_class_obj_or_id)) {
5035
+			//assume it's an ID
5036
+			$id = $base_class_obj_or_id;
5037
+		} elseif (is_string($base_class_obj_or_id)) {
5038
+			//assume its a string representation of the object
5039
+			$id = $base_class_obj_or_id;
5040
+		} else {
5041
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5042
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5043
+				print_r($base_class_obj_or_id, true)));
5044
+		}
5045
+		return $id;
5046
+	}
5047
+
5048
+
5049
+
5050
+	/**
5051
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5052
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5053
+	 * been sanitized and converted into the appropriate domain.
5054
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5055
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5056
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5057
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5058
+	 * $EVT = EEM_Event::instance(); $old_setting =
5059
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5060
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5061
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5062
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5063
+	 *
5064
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5065
+	 * @return void
5066
+	 */
5067
+	public function assume_values_already_prepared_by_model_object(
5068
+		$values_already_prepared = self::not_prepared_by_model_object
5069
+	) {
5070
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5071
+	}
5072
+
5073
+
5074
+
5075
+	/**
5076
+	 * Read comments for assume_values_already_prepared_by_model_object()
5077
+	 *
5078
+	 * @return int
5079
+	 */
5080
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5081
+	{
5082
+		return $this->_values_already_prepared_by_model_object;
5083
+	}
5084
+
5085
+
5086
+
5087
+	/**
5088
+	 * Gets all the indexes on this model
5089
+	 *
5090
+	 * @return EE_Index[]
5091
+	 */
5092
+	public function indexes()
5093
+	{
5094
+		return $this->_indexes;
5095
+	}
5096
+
5097
+
5098
+
5099
+	/**
5100
+	 * Gets all the Unique Indexes on this model
5101
+	 *
5102
+	 * @return EE_Unique_Index[]
5103
+	 */
5104
+	public function unique_indexes()
5105
+	{
5106
+		$unique_indexes = array();
5107
+		foreach ($this->_indexes as $name => $index) {
5108
+			if ($index instanceof EE_Unique_Index) {
5109
+				$unique_indexes [$name] = $index;
5110
+			}
5111
+		}
5112
+		return $unique_indexes;
5113
+	}
5114
+
5115
+
5116
+
5117
+	/**
5118
+	 * Gets all the fields which, when combined, make the primary key.
5119
+	 * This is usually just an array with 1 element (the primary key), but in cases
5120
+	 * where there is no primary key, it's a combination of fields as defined
5121
+	 * on a primary index
5122
+	 *
5123
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5124
+	 * @throws \EE_Error
5125
+	 */
5126
+	public function get_combined_primary_key_fields()
5127
+	{
5128
+		foreach ($this->indexes() as $index) {
5129
+			if ($index instanceof EE_Primary_Key_Index) {
5130
+				return $index->fields();
5131
+			}
5132
+		}
5133
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5134
+	}
5135
+
5136
+
5137
+
5138
+	/**
5139
+	 * Used to build a primary key string (when the model has no primary key),
5140
+	 * which can be used a unique string to identify this model object.
5141
+	 *
5142
+	 * @param array $cols_n_values keys are field names, values are their values
5143
+	 * @return string
5144
+	 * @throws \EE_Error
5145
+	 */
5146
+	public function get_index_primary_key_string($cols_n_values)
5147
+	{
5148
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5149
+			$this->get_combined_primary_key_fields());
5150
+		return http_build_query($cols_n_values_for_primary_key_index);
5151
+	}
5152
+
5153
+
5154
+
5155
+	/**
5156
+	 * Gets the field values from the primary key string
5157
+	 *
5158
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5159
+	 * @param string $index_primary_key_string
5160
+	 * @return null|array
5161
+	 * @throws \EE_Error
5162
+	 */
5163
+	public function parse_index_primary_key_string($index_primary_key_string)
5164
+	{
5165
+		$key_fields = $this->get_combined_primary_key_fields();
5166
+		//check all of them are in the $id
5167
+		$key_vals_in_combined_pk = array();
5168
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5169
+		foreach ($key_fields as $key_field_name => $field_obj) {
5170
+			if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5171
+				return null;
5172
+			}
5173
+		}
5174
+		return $key_vals_in_combined_pk;
5175
+	}
5176
+
5177
+
5178
+
5179
+	/**
5180
+	 * verifies that an array of key-value pairs for model fields has a key
5181
+	 * for each field comprising the primary key index
5182
+	 *
5183
+	 * @param array $key_vals
5184
+	 * @return boolean
5185
+	 * @throws \EE_Error
5186
+	 */
5187
+	public function has_all_combined_primary_key_fields($key_vals)
5188
+	{
5189
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5190
+		foreach ($keys_it_should_have as $key) {
5191
+			if ( ! isset($key_vals[$key])) {
5192
+				return false;
5193
+			}
5194
+		}
5195
+		return true;
5196
+	}
5197
+
5198
+
5199
+
5200
+	/**
5201
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5202
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5203
+	 *
5204
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5205
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5206
+	 * @throws EE_Error
5207
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5208
+	 *                          indexed)
5209
+	 */
5210
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5211
+	{
5212
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5213
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5214
+		} elseif (is_array($model_object_or_attributes_array)) {
5215
+			$attributes_array = $model_object_or_attributes_array;
5216
+		} else {
5217
+			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",
5218
+				"event_espresso"), $model_object_or_attributes_array));
5219
+		}
5220
+		//even copies obviously won't have the same ID, so remove the primary key
5221
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5222
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5223
+			unset($attributes_array[$this->primary_key_name()]);
5224
+		}
5225
+		if (isset($query_params[0])) {
5226
+			$query_params[0] = array_merge($attributes_array, $query_params);
5227
+		} else {
5228
+			$query_params[0] = $attributes_array;
5229
+		}
5230
+		return $this->get_all($query_params);
5231
+	}
5232
+
5233
+
5234
+
5235
+	/**
5236
+	 * Gets the first copy we find. See get_all_copies for more details
5237
+	 *
5238
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5239
+	 * @param array $query_params
5240
+	 * @return EE_Base_Class
5241
+	 * @throws \EE_Error
5242
+	 */
5243
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5244
+	{
5245
+		if ( ! is_array($query_params)) {
5246
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5247
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5248
+					gettype($query_params)), '4.6.0');
5249
+			$query_params = array();
5250
+		}
5251
+		$query_params['limit'] = 1;
5252
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5253
+		if (is_array($copies)) {
5254
+			return array_shift($copies);
5255
+		} else {
5256
+			return null;
5257
+		}
5258
+	}
5259
+
5260
+
5261
+
5262
+	/**
5263
+	 * Updates the item with the specified id. Ignores default query parameters because
5264
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5265
+	 *
5266
+	 * @param array      $fields_n_values keys are field names, values are their new values
5267
+	 * @param int|string $id              the value of the primary key to update
5268
+	 * @return int number of rows updated
5269
+	 * @throws \EE_Error
5270
+	 */
5271
+	public function update_by_ID($fields_n_values, $id)
5272
+	{
5273
+		$query_params = array(
5274
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5275
+			'default_where_conditions' => 'other_models_only',
5276
+		);
5277
+		return $this->update($fields_n_values, $query_params);
5278
+	}
5279
+
5280
+
5281
+
5282
+	/**
5283
+	 * Changes an operator which was supplied to the models into one usable in SQL
5284
+	 *
5285
+	 * @param string $operator_supplied
5286
+	 * @return string an operator which can be used in SQL
5287
+	 * @throws EE_Error
5288
+	 */
5289
+	private function _prepare_operator_for_sql($operator_supplied)
5290
+	{
5291
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5292
+			: null;
5293
+		if ($sql_operator) {
5294
+			return $sql_operator;
5295
+		} else {
5296
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5297
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5298
+		}
5299
+	}
5300
+
5301
+
5302
+
5303
+	/**
5304
+	 * Gets an array where keys are the primary keys and values are their 'names'
5305
+	 * (as determined by the model object's name() function, which is often overridden)
5306
+	 *
5307
+	 * @param array $query_params like get_all's
5308
+	 * @return string[]
5309
+	 * @throws \EE_Error
5310
+	 */
5311
+	public function get_all_names($query_params = array())
5312
+	{
5313
+		$objs = $this->get_all($query_params);
5314
+		$names = array();
5315
+		foreach ($objs as $obj) {
5316
+			$names[$obj->ID()] = $obj->name();
5317
+		}
5318
+		return $names;
5319
+	}
5320
+
5321
+
5322
+
5323
+	/**
5324
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5325
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5326
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5327
+	 * array_keys() on $model_objects.
5328
+	 *
5329
+	 * @param \EE_Base_Class[] $model_objects
5330
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5331
+	 *                                               in the returned array
5332
+	 * @return array
5333
+	 * @throws \EE_Error
5334
+	 */
5335
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5336
+	{
5337
+		if ( ! $this->has_primary_key_field()) {
5338
+			if (WP_DEBUG) {
5339
+				EE_Error::add_error(
5340
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5341
+					__FILE__,
5342
+					__FUNCTION__,
5343
+					__LINE__
5344
+				);
5345
+			}
5346
+		}
5347
+		$IDs = array();
5348
+		foreach ($model_objects as $model_object) {
5349
+			$id = $model_object->ID();
5350
+			if ( ! $id) {
5351
+				if ($filter_out_empty_ids) {
5352
+					continue;
5353
+				}
5354
+				if (WP_DEBUG) {
5355
+					EE_Error::add_error(
5356
+						__(
5357
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5358
+							'event_espresso'
5359
+						),
5360
+						__FILE__,
5361
+						__FUNCTION__,
5362
+						__LINE__
5363
+					);
5364
+				}
5365
+			}
5366
+			$IDs[] = $id;
5367
+		}
5368
+		return $IDs;
5369
+	}
5370
+
5371
+
5372
+
5373
+	/**
5374
+	 * Returns the string used in capabilities relating to this model. If there
5375
+	 * are no capabilities that relate to this model returns false
5376
+	 *
5377
+	 * @return string|false
5378
+	 */
5379
+	public function cap_slug()
5380
+	{
5381
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5382
+	}
5383
+
5384
+
5385
+
5386
+	/**
5387
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5388
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5389
+	 * only returns the cap restrictions array in that context (ie, the array
5390
+	 * at that key)
5391
+	 *
5392
+	 * @param string $context
5393
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5394
+	 * @throws \EE_Error
5395
+	 */
5396
+	public function cap_restrictions($context = EEM_Base::caps_read)
5397
+	{
5398
+		EEM_Base::verify_is_valid_cap_context($context);
5399
+		//check if we ought to run the restriction generator first
5400
+		if (
5401
+			isset($this->_cap_restriction_generators[$context])
5402
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5403
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5404
+		) {
5405
+			$this->_cap_restrictions[$context] = array_merge(
5406
+				$this->_cap_restrictions[$context],
5407
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5408
+			);
5409
+		}
5410
+		//and make sure we've finalized the construction of each restriction
5411
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5412
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5413
+				$where_conditions_obj->_finalize_construct($this);
5414
+			}
5415
+		}
5416
+		return $this->_cap_restrictions[$context];
5417
+	}
5418
+
5419
+
5420
+
5421
+	/**
5422
+	 * Indicating whether or not this model thinks its a wp core model
5423
+	 *
5424
+	 * @return boolean
5425
+	 */
5426
+	public function is_wp_core_model()
5427
+	{
5428
+		return $this->_wp_core_model;
5429
+	}
5430
+
5431
+
5432
+
5433
+	/**
5434
+	 * Gets all the caps that are missing which impose a restriction on
5435
+	 * queries made in this context
5436
+	 *
5437
+	 * @param string $context one of EEM_Base::caps_ constants
5438
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5439
+	 * @throws \EE_Error
5440
+	 */
5441
+	public function caps_missing($context = EEM_Base::caps_read)
5442
+	{
5443
+		$missing_caps = array();
5444
+		$cap_restrictions = $this->cap_restrictions($context);
5445
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5446
+			if ( ! EE_Capabilities::instance()
5447
+								  ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5448
+			) {
5449
+				$missing_caps[$cap] = $restriction_if_no_cap;
5450
+			}
5451
+		}
5452
+		return $missing_caps;
5453
+	}
5454
+
5455
+
5456
+
5457
+	/**
5458
+	 * Gets the mapping from capability contexts to action strings used in capability names
5459
+	 *
5460
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5461
+	 * one of 'read', 'edit', or 'delete'
5462
+	 */
5463
+	public function cap_contexts_to_cap_action_map()
5464
+	{
5465
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5466
+			$this);
5467
+	}
5468
+
5469
+
5470
+
5471
+	/**
5472
+	 * Gets the action string for the specified capability context
5473
+	 *
5474
+	 * @param string $context
5475
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5476
+	 * @throws \EE_Error
5477
+	 */
5478
+	public function cap_action_for_context($context)
5479
+	{
5480
+		$mapping = $this->cap_contexts_to_cap_action_map();
5481
+		if (isset($mapping[$context])) {
5482
+			return $mapping[$context];
5483
+		}
5484
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5485
+			return $action;
5486
+		}
5487
+		throw new EE_Error(
5488
+			sprintf(
5489
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5490
+				$context,
5491
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5492
+			)
5493
+		);
5494
+	}
5495
+
5496
+
5497
+
5498
+	/**
5499
+	 * Returns all the capability contexts which are valid when querying models
5500
+	 *
5501
+	 * @return array
5502
+	 */
5503
+	static public function valid_cap_contexts()
5504
+	{
5505
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5506
+			self::caps_read,
5507
+			self::caps_read_admin,
5508
+			self::caps_edit,
5509
+			self::caps_delete,
5510
+		));
5511
+	}
5512
+
5513
+
5514
+
5515
+	/**
5516
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5517
+	 *
5518
+	 * @param string $context
5519
+	 * @return bool
5520
+	 * @throws \EE_Error
5521
+	 */
5522
+	static public function verify_is_valid_cap_context($context)
5523
+	{
5524
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5525
+		if (in_array($context, $valid_cap_contexts)) {
5526
+			return true;
5527
+		} else {
5528
+			throw new EE_Error(
5529
+				sprintf(
5530
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5531
+						'event_espresso'),
5532
+					$context,
5533
+					'EEM_Base',
5534
+					implode(',', $valid_cap_contexts)
5535
+				)
5536
+			);
5537
+		}
5538
+	}
5539
+
5540
+
5541
+
5542
+	/**
5543
+	 * Clears all the models field caches. This is only useful when a sub-class
5544
+	 * might have added a field or something and these caches might be invalidated
5545
+	 */
5546
+	protected function _invalidate_field_caches()
5547
+	{
5548
+		$this->_cache_foreign_key_to_fields = array();
5549
+		$this->_cached_fields = null;
5550
+		$this->_cached_fields_non_db_only = null;
5551
+	}
5552 5552
 
5553 5553
 
5554 5554
 
Please login to merge, or discard this patch.
Spacing   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
     {
468 468
         // check that the model has not been loaded too soon
469 469
         if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
470
-            throw new EE_Error (
470
+            throw new EE_Error(
471 471
                 sprintf(
472 472
                     __('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.',
473 473
                         'event_espresso'),
@@ -487,7 +487,7 @@  discard block
 block discarded – undo
487 487
          *
488 488
          * @var EE_Table_Base[] $_tables
489 489
          */
490
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
490
+        $this->_tables = apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
491 491
         foreach ($this->_tables as $table_alias => $table_obj) {
492 492
             /** @var $table_obj EE_Table_Base */
493 493
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
          *
503 503
          * @param EE_Model_Field_Base[] $_fields
504 504
          */
505
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
505
+        $this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
506 506
         $this->_invalidate_field_caches();
507 507
         foreach ($this->_fields as $table_alias => $fields_for_table) {
508 508
             if ( ! array_key_exists($table_alias, $this->_tables)) {
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
          *
534 534
          * @param EE_Model_Relation_Base[] $_model_relations
535 535
          */
536
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
536
+        $this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
537 537
             $this->_model_relations);
538 538
         foreach ($this->_model_relations as $model_name => $relation_obj) {
539 539
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
                 }
596 596
             }
597 597
         }
598
-        do_action('AHEE__' . get_class($this) . '__construct__end');
598
+        do_action('AHEE__'.get_class($this).'__construct__end');
599 599
     }
600 600
 
601 601
 
@@ -630,7 +630,7 @@  discard block
 block discarded – undo
630 630
      */
631 631
     public static function set_model_query_blog_id($blog_id = 0)
632 632
     {
633
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
633
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
634 634
     }
635 635
 
636 636
 
@@ -870,13 +870,13 @@  discard block
 block discarded – undo
870 870
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
871 871
                 $last_model_name = end($models_to_follow_to_wp_users);
872 872
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
873
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
873
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
874 874
             } else {
875 875
                 $model_with_fk_to_wp_users = $this;
876 876
                 $model_chain_to_wp_user = '';
877 877
             }
878 878
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
879
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
879
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
880 880
         } catch (EE_Error $e) {
881 881
             return false;
882 882
         }
@@ -948,12 +948,12 @@  discard block
 block discarded – undo
948 948
         // remember the custom selections, if any, and type cast as array
949 949
         // (unless $columns_to_select is an object, then just set as an empty array)
950 950
         // Note: (array) 'some string' === array( 'some string' )
951
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
951
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
952 952
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
953 953
         $select_expressions = $columns_to_select !== null
954 954
             ? $this->_construct_select_from_input($columns_to_select)
955 955
             : $this->_construct_default_select_sql($model_query_info);
956
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
956
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
957 957
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
958 958
     }
959 959
 
@@ -1285,7 +1285,7 @@  discard block
 block discarded – undo
1285 1285
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1286 1286
         $query_params['limit'] = $limit;
1287 1287
         //set direction
1288
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1288
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1289 1289
         $query_params['order_by'] = $operand === '>'
1290 1290
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1291 1291
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1525,7 +1525,7 @@  discard block
 block discarded – undo
1525 1525
          * @param EEM_Base $model           the model being queried
1526 1526
          * @param array    $query_params    see EEM_Base::get_all()
1527 1527
          */
1528
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1528
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1529 1529
             $query_params);
1530 1530
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1531 1531
         //to do that, for each table, verify that it's PK isn't null.
@@ -1539,7 +1539,7 @@  discard block
 block discarded – undo
1539 1539
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1540 1540
         foreach ($wpdb_select_results as $wpdb_result) {
1541 1541
             // type cast stdClass as array
1542
-            $wpdb_result = (array)$wpdb_result;
1542
+            $wpdb_result = (array) $wpdb_result;
1543 1543
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1544 1544
             if ($this->has_primary_key_field()) {
1545 1545
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1620,7 +1620,7 @@  discard block
 block discarded – undo
1620 1620
                . $model_query_info->get_full_join_sql()
1621 1621
                . " SET "
1622 1622
                . $this->_construct_update_sql($fields_n_values)
1623
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1623
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1624 1624
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1625 1625
         /**
1626 1626
          * Action called after a model update call has been made.
@@ -1631,7 +1631,7 @@  discard block
 block discarded – undo
1631 1631
          * @param int      $rows_affected
1632 1632
          */
1633 1633
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1634
-        return $rows_affected;//how many supposedly got updated
1634
+        return $rows_affected; //how many supposedly got updated
1635 1635
     }
1636 1636
 
1637 1637
 
@@ -1659,7 +1659,7 @@  discard block
 block discarded – undo
1659 1659
         }
1660 1660
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1661 1661
         $select_expressions = $field->get_qualified_column();
1662
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1662
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1663 1663
         return $this->_do_wpdb_query('get_col', array($SQL));
1664 1664
     }
1665 1665
 
@@ -1709,7 +1709,7 @@  discard block
 block discarded – undo
1709 1709
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1710 1710
             $value_sql = $prepared_value === null ? 'NULL'
1711 1711
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1712
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1712
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1713 1713
         }
1714 1714
         return implode(",", $cols_n_values);
1715 1715
     }
@@ -1841,7 +1841,7 @@  discard block
 block discarded – undo
1841 1841
          * @param int      $rows_deleted
1842 1842
          */
1843 1843
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1844
-        return $rows_deleted;//how many supposedly got deleted
1844
+        return $rows_deleted; //how many supposedly got deleted
1845 1845
     }
1846 1846
 
1847 1847
 
@@ -1957,7 +1957,7 @@  discard block
 block discarded – undo
1957 1957
             foreach ($deletes as $column => $values) {
1958 1958
                 //make sure we have unique $values;
1959 1959
                 $values = array_unique($values);
1960
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
1960
+                $query[] = $column.' IN('.implode(",", $values).')';
1961 1961
             }
1962 1962
             return ! empty($query) ? implode(' AND ', $query) : '';
1963 1963
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -1973,7 +1973,7 @@  discard block
 block discarded – undo
1973 1973
                                                            . $delete_object[$cpk_field->get_qualified_column()];
1974 1974
                     }
1975 1975
                 }
1976
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
1976
+                $ways_to_identify_a_row[] = "(".implode(" AND ", $values_for_each_cpk_for_a_row).")";
1977 1977
             }
1978 1978
             return implode(" OR ", $ways_to_identify_a_row);
1979 1979
         } else {
@@ -2022,9 +2022,9 @@  discard block
 block discarded – undo
2022 2022
                 $column_to_count = '*';
2023 2023
             }
2024 2024
         }
2025
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2026
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2027
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2025
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2026
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2027
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2028 2028
     }
2029 2029
 
2030 2030
 
@@ -2046,13 +2046,13 @@  discard block
 block discarded – undo
2046 2046
             $field_obj = $this->get_primary_key_field();
2047 2047
         }
2048 2048
         $column_to_count = $field_obj->get_qualified_column();
2049
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2049
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2050 2050
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2051 2051
         $data_type = $field_obj->get_wpdb_data_type();
2052 2052
         if ($data_type === '%d' || $data_type === '%s') {
2053
-            return (float)$return_value;
2053
+            return (float) $return_value;
2054 2054
         } else {//must be %f
2055
-            return (float)$return_value;
2055
+            return (float) $return_value;
2056 2056
         }
2057 2057
     }
2058 2058
 
@@ -2227,11 +2227,11 @@  discard block
 block discarded – undo
2227 2227
      */
2228 2228
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2229 2229
     {
2230
-        return " FROM " . $model_query_info->get_full_join_sql() .
2231
-               $model_query_info->get_where_sql() .
2232
-               $model_query_info->get_group_by_sql() .
2233
-               $model_query_info->get_having_sql() .
2234
-               $model_query_info->get_order_by_sql() .
2230
+        return " FROM ".$model_query_info->get_full_join_sql().
2231
+               $model_query_info->get_where_sql().
2232
+               $model_query_info->get_group_by_sql().
2233
+               $model_query_info->get_having_sql().
2234
+               $model_query_info->get_order_by_sql().
2235 2235
                $model_query_info->get_limit_sql();
2236 2236
     }
2237 2237
 
@@ -2432,7 +2432,7 @@  discard block
 block discarded – undo
2432 2432
         }
2433 2433
         $this_model_name = $this->get_this_model_name();
2434 2434
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2435
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2435
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2436 2436
         return $related_model->count($query_params, $field_to_count, $distinct);
2437 2437
     }
2438 2438
 
@@ -2465,7 +2465,7 @@  discard block
 block discarded – undo
2465 2465
         }
2466 2466
         $this_model_name = $this->get_this_model_name();
2467 2467
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2468
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2468
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2469 2469
         return $related_model->sum($query_params, $field_to_sum);
2470 2470
     }
2471 2471
 
@@ -2552,7 +2552,7 @@  discard block
 block discarded – undo
2552 2552
          * @param array    $fields_n_values keys are the fields and values are their new values
2553 2553
          * @param EEM_Base $model           the model used
2554 2554
          */
2555
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2555
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2556 2556
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2557 2557
             $main_table = $this->_get_main_table();
2558 2558
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2660,7 +2660,7 @@  discard block
 block discarded – undo
2660 2660
         }
2661 2661
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2662 2662
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2663
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2663
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2664 2664
         }
2665 2665
         //if there is nothing to base this search on, then we shouldn't find anything
2666 2666
         if (empty($query_params)) {
@@ -2740,7 +2740,7 @@  discard block
 block discarded – undo
2740 2740
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2741 2741
             //so add the fk to the main table as a column
2742 2742
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2743
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2743
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2744 2744
         }
2745 2745
         //insert the new entry
2746 2746
         $result = $this->_do_wpdb_query('insert',
@@ -3000,7 +3000,7 @@  discard block
 block discarded – undo
3000 3000
         $query_param_type
3001 3001
     ) {
3002 3002
         if ( ! empty($sub_query_params)) {
3003
-            $sub_query_params = (array)$sub_query_params;
3003
+            $sub_query_params = (array) $sub_query_params;
3004 3004
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3005 3005
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3006 3006
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3171,12 +3171,12 @@  discard block
 block discarded – undo
3171 3171
                         ),
3172 3172
                         http_build_query($query_params['limit'])
3173 3173
                     );
3174
-                    throw new EE_Error($e . "|" . $e);
3174
+                    throw new EE_Error($e."|".$e);
3175 3175
                 }
3176 3176
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3177
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3177
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3178 3178
             } elseif ( ! empty ($query_params['limit'])) {
3179
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3179
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3180 3180
             }
3181 3181
         }
3182 3182
         //set order by
@@ -3208,9 +3208,9 @@  discard block
 block discarded – undo
3208 3208
                 $order_array = array();
3209 3209
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3210 3210
                     $order = $this->_extract_order($order);
3211
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3211
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3212 3212
                 }
3213
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3213
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3214 3214
             } elseif ( ! empty ($query_params['order_by'])) {
3215 3215
                 $this->_extract_related_model_info_from_query_param(
3216 3216
                     $query_params['order_by'],
@@ -3222,7 +3222,7 @@  discard block
 block discarded – undo
3222 3222
                     ? $this->_extract_order($query_params['order'])
3223 3223
                     : 'DESC';
3224 3224
                 $query_object->set_order_by_sql(
3225
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3225
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3226 3226
                 );
3227 3227
             }
3228 3228
         }
@@ -3233,7 +3233,7 @@  discard block
 block discarded – undo
3233 3233
         ) {
3234 3234
             $pk_field = $this->get_primary_key_field();
3235 3235
             $order = $this->_extract_order($query_params['order']);
3236
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3236
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3237 3237
         }
3238 3238
         //set group by
3239 3239
         if (array_key_exists('group_by', $query_params)) {
@@ -3243,10 +3243,10 @@  discard block
 block discarded – undo
3243 3243
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3244 3244
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3245 3245
                 }
3246
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3246
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3247 3247
             } elseif ( ! empty ($query_params['group_by'])) {
3248 3248
                 $query_object->set_group_by_sql(
3249
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3249
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3250 3250
                 );
3251 3251
             }
3252 3252
         }
@@ -3409,7 +3409,7 @@  discard block
 block discarded – undo
3409 3409
     ) {
3410 3410
         $null_friendly_where_conditions = array();
3411 3411
         $none_overridden = true;
3412
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3412
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3413 3413
         foreach ($default_where_conditions as $key => $val) {
3414 3414
             if (isset($provided_where_conditions[$key])) {
3415 3415
                 $none_overridden = false;
@@ -3613,9 +3613,9 @@  discard block
 block discarded – undo
3613 3613
         //and
3614 3614
         //check if it's a field on a related model
3615 3615
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3616
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3616
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3617 3617
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3618
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3618
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3619 3619
                 if ($query_param === '') {
3620 3620
                     //nothing left to $query_param
3621 3621
                     //we should actually end in a field name, not a model like this!
@@ -3701,7 +3701,7 @@  discard block
 block discarded – undo
3701 3701
     {
3702 3702
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3703 3703
         if ($SQL) {
3704
-            return " WHERE " . $SQL;
3704
+            return " WHERE ".$SQL;
3705 3705
         } else {
3706 3706
             return '';
3707 3707
         }
@@ -3721,7 +3721,7 @@  discard block
 block discarded – undo
3721 3721
     {
3722 3722
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3723 3723
         if ($SQL) {
3724
-            return " HAVING " . $SQL;
3724
+            return " HAVING ".$SQL;
3725 3725
         } else {
3726 3726
             return '';
3727 3727
         }
@@ -3741,11 +3741,11 @@  discard block
 block discarded – undo
3741 3741
      */
3742 3742
     protected function _get_field_on_model($field_name, $model_name)
3743 3743
     {
3744
-        $model_class = 'EEM_' . $model_name;
3745
-        $model_filepath = $model_class . ".model.php";
3744
+        $model_class = 'EEM_'.$model_name;
3745
+        $model_filepath = $model_class.".model.php";
3746 3746
         if (is_readable($model_filepath)) {
3747 3747
             require_once($model_filepath);
3748
-            $model_instance = call_user_func($model_name . "::instance");
3748
+            $model_instance = call_user_func($model_name."::instance");
3749 3749
             /* @var $model_instance EEM_Base */
3750 3750
             return $model_instance->field_settings_for($field_name);
3751 3751
         } else {
@@ -3769,7 +3769,7 @@  discard block
 block discarded – undo
3769 3769
     {
3770 3770
         $where_clauses = array();
3771 3771
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3772
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3772
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
3773 3773
             if (in_array($query_param, $this->_logic_query_param_keys)) {
3774 3774
                 switch ($query_param) {
3775 3775
                     case 'not':
@@ -3806,7 +3806,7 @@  discard block
 block discarded – undo
3806 3806
                     }
3807 3807
                 }
3808 3808
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3809
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3809
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
3810 3810
             }
3811 3811
         }
3812 3812
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -3827,7 +3827,7 @@  discard block
 block discarded – undo
3827 3827
         if ($field) {
3828 3828
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
3829 3829
                 $query_param);
3830
-            return $table_alias_prefix . $field->get_qualified_column();
3830
+            return $table_alias_prefix.$field->get_qualified_column();
3831 3831
         } elseif (array_key_exists($query_param, $this->_custom_selections)) {
3832 3832
             //maybe it's custom selection item?
3833 3833
             //if so, just use it as the "column name"
@@ -3896,13 +3896,13 @@  discard block
 block discarded – undo
3896 3896
         }
3897 3897
         //check to see if the value is actually another field
3898 3898
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
3899
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
3899
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
3900 3900
         } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
3901 3901
             //in this case, the value should be an array, or at least a comma-separated list
3902 3902
             //it will need to handle a little differently
3903 3903
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
3904 3904
             //note: $cleaned_value has already been run through $wpdb->prepare()
3905
-            return $operator . SP . $cleaned_value;
3905
+            return $operator.SP.$cleaned_value;
3906 3906
         } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
3907 3907
             //the value should be an array with count of two.
3908 3908
             if (count($value) !== 2) {
@@ -3917,7 +3917,7 @@  discard block
 block discarded – undo
3917 3917
                 );
3918 3918
             }
3919 3919
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
3920
-            return $operator . SP . $cleaned_value;
3920
+            return $operator.SP.$cleaned_value;
3921 3921
         } elseif (in_array($operator, $this->_null_style_operators)) {
3922 3922
             if ($value !== null) {
3923 3923
                 throw new EE_Error(
@@ -3935,9 +3935,9 @@  discard block
 block discarded – undo
3935 3935
         } elseif ($operator === 'LIKE' && ! is_array($value)) {
3936 3936
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
3937 3937
             //remove other junk. So just treat it as a string.
3938
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
3938
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
3939 3939
         } elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3940
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
3940
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
3941 3941
         } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3942 3942
             throw new EE_Error(
3943 3943
                 sprintf(
@@ -3990,7 +3990,7 @@  discard block
 block discarded – undo
3990 3990
         foreach ($values as $value) {
3991 3991
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
3992 3992
         }
3993
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
3993
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
3994 3994
     }
3995 3995
 
3996 3996
 
@@ -4031,7 +4031,7 @@  discard block
 block discarded – undo
4031 4031
                                 . $main_table->get_table_name()
4032 4032
                                 . " WHERE FALSE";
4033 4033
         }
4034
-        return "(" . implode(",", $cleaned_values) . ")";
4034
+        return "(".implode(",", $cleaned_values).")";
4035 4035
     }
4036 4036
 
4037 4037
 
@@ -4134,11 +4134,11 @@  discard block
 block discarded – undo
4134 4134
             if ($table_obj instanceof EE_Primary_Table) {
4135 4135
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4136 4136
                     ? $table_obj->get_select_join_limit($limit)
4137
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4137
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4138 4138
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4139 4139
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4140 4140
                     ? $table_obj->get_select_join_limit_join($limit)
4141
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4141
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4142 4142
             }
4143 4143
         }
4144 4144
         return $SQL;
@@ -4226,12 +4226,12 @@  discard block
 block discarded – undo
4226 4226
      */
4227 4227
     public function get_related_model_obj($model_name)
4228 4228
     {
4229
-        $model_classname = "EEM_" . $model_name;
4229
+        $model_classname = "EEM_".$model_name;
4230 4230
         if ( ! class_exists($model_classname)) {
4231 4231
             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",
4232 4232
                 'event_espresso'), $model_name, $model_classname));
4233 4233
         }
4234
-        return call_user_func($model_classname . "::instance");
4234
+        return call_user_func($model_classname."::instance");
4235 4235
     }
4236 4236
 
4237 4237
 
@@ -4530,7 +4530,7 @@  discard block
 block discarded – undo
4530 4530
         $count_if_model_has_no_primary_key = 0;
4531 4531
         $has_primary_key = $this->has_primary_key_field();
4532 4532
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4533
-        foreach ((array)$rows as $row) {
4533
+        foreach ((array) $rows as $row) {
4534 4534
             if (empty($row)) {
4535 4535
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4536 4536
                 return array();
@@ -4893,7 +4893,7 @@  discard block
 block discarded – undo
4893 4893
      */
4894 4894
     private function _get_class_name()
4895 4895
     {
4896
-        return "EE_" . $this->get_this_model_name();
4896
+        return "EE_".$this->get_this_model_name();
4897 4897
     }
4898 4898
 
4899 4899
 
@@ -4908,7 +4908,7 @@  discard block
 block discarded – undo
4908 4908
      */
4909 4909
     public function item_name($quantity = 1)
4910 4910
     {
4911
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
4911
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
4912 4912
     }
4913 4913
 
4914 4914
 
@@ -5444,7 +5444,7 @@  discard block
 block discarded – undo
5444 5444
         $cap_restrictions = $this->cap_restrictions($context);
5445 5445
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5446 5446
             if ( ! EE_Capabilities::instance()
5447
-                                  ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5447
+                                  ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5448 5448
             ) {
5449 5449
                 $missing_caps[$cap] = $restriction_if_no_cap;
5450 5450
             }
Please login to merge, or discard this patch.
core/helpers/EEH_Event_Query.helper.php 1 patch
Spacing   +118 added lines, -118 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1
-<?php if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) {
2
-	exit( 'No direct script access allowed' );
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
 	 */
86 86
 	public static function add_query_filters() {
87 87
 		//add query filters
88
-		add_action( 'pre_get_posts', array( 'EEH_Event_Query', 'filter_query_parts' ), 10, 1 );
88
+		add_action('pre_get_posts', array('EEH_Event_Query', 'filter_query_parts'), 10, 1);
89 89
 	}
90 90
 
91 91
 
@@ -97,8 +97,8 @@  discard block
 block discarded – undo
97 97
 	 * @param \WP_Query $WP_Query
98 98
 	 * @return bool
99 99
 	 */
100
-	public static function apply_query_filters( WP_Query $WP_Query ) {
101
-		return ( isset( $WP_Query->query, $WP_Query->query['post_type'] ) && $WP_Query->query['post_type'] == 'espresso_events' ) ||  apply_filters( 'FHEE__EEH_Event_Query__apply_query_filters', false ) ? true : false;
100
+	public static function apply_query_filters(WP_Query $WP_Query) {
101
+		return (isset($WP_Query->query, $WP_Query->query['post_type']) && $WP_Query->query['post_type'] == 'espresso_events') || apply_filters('FHEE__EEH_Event_Query__apply_query_filters', false) ? true : false;
102 102
 	}
103 103
 
104 104
 
@@ -108,15 +108,15 @@  discard block
 block discarded – undo
108 108
 	 * @access    public
109 109
 	 * @param \WP_Query $WP_Query
110 110
 	 */
111
-	public static function filter_query_parts( WP_Query $WP_Query ) {
111
+	public static function filter_query_parts(WP_Query $WP_Query) {
112 112
 		//ONLY add our filters if this isn't the main wp_query, because if this is the main wp_query we already have our cpt strategies take care of adding things in.
113
-		if ( $WP_Query instanceof WP_Query && ! $WP_Query->is_main_query() ) {
113
+		if ($WP_Query instanceof WP_Query && ! $WP_Query->is_main_query()) {
114 114
 			// build event list query
115
-			add_filter( 'posts_fields', array( 'EEH_Event_Query', 'posts_fields' ), 10, 2 );
116
-			add_filter( 'posts_join', array( 'EEH_Event_Query', 'posts_join' ), 10, 2 );
117
-			add_filter( 'posts_where', array( 'EEH_Event_Query', 'posts_where' ), 10, 2 );
118
-			add_filter( 'posts_orderby', array( 'EEH_Event_Query', 'posts_orderby' ), 10, 2 );
119
-			add_filter( 'posts_clauses_request', array( 'EEH_Event_Query', 'posts_clauses' ), 10, 2 );
115
+			add_filter('posts_fields', array('EEH_Event_Query', 'posts_fields'), 10, 2);
116
+			add_filter('posts_join', array('EEH_Event_Query', 'posts_join'), 10, 2);
117
+			add_filter('posts_where', array('EEH_Event_Query', 'posts_where'), 10, 2);
118
+			add_filter('posts_orderby', array('EEH_Event_Query', 'posts_orderby'), 10, 2);
119
+			add_filter('posts_clauses_request', array('EEH_Event_Query', 'posts_clauses'), 10, 2);
120 120
 		}
121 121
 	}
122 122
 
@@ -131,13 +131,13 @@  discard block
 block discarded – undo
131 131
 	 * @param string $orderby
132 132
 	 * @param string $sort
133 133
 	 */
134
-	public static function set_query_params( $month = '', $category = '', $show_expired = FALSE, $orderby = 'start_date', $sort = 'ASC' ) {
134
+	public static function set_query_params($month = '', $category = '', $show_expired = FALSE, $orderby = 'start_date', $sort = 'ASC') {
135 135
 		self::$_query_params = array();
136
-		EEH_Event_Query::$_event_query_month = EEH_Event_Query::_display_month( $month );
137
-		EEH_Event_Query::$_event_query_category = EEH_Event_Query::_event_category_slug( $category );
138
-		EEH_Event_Query::$_event_query_show_expired = EEH_Event_Query::_show_expired( $show_expired );
139
-		EEH_Event_Query::$_event_query_orderby = EEH_Event_Query::_orderby( $orderby );
140
-		EEH_Event_Query::$_event_query_sort = EEH_Event_Query::_sort( $sort );
136
+		EEH_Event_Query::$_event_query_month = EEH_Event_Query::_display_month($month);
137
+		EEH_Event_Query::$_event_query_category = EEH_Event_Query::_event_category_slug($category);
138
+		EEH_Event_Query::$_event_query_show_expired = EEH_Event_Query::_show_expired($show_expired);
139
+		EEH_Event_Query::$_event_query_orderby = EEH_Event_Query::_orderby($orderby);
140
+		EEH_Event_Query::$_event_query_sort = EEH_Event_Query::_sort($sort);
141 141
 	}
142 142
 
143 143
 
@@ -149,8 +149,8 @@  discard block
 block discarded – undo
149 149
 	 * @param string $month
150 150
 	 * @return    string
151 151
 	 */
152
-	private static function _display_month( $month = '' ) {
153
-		return EE_Registry::instance()->REQ->is_set( 'event_query_month' ) ? sanitize_text_field( EE_Registry::instance()->REQ->get( 'event_query_month' ) ) : $month;
152
+	private static function _display_month($month = '') {
153
+		return EE_Registry::instance()->REQ->is_set('event_query_month') ? sanitize_text_field(EE_Registry::instance()->REQ->get('event_query_month')) : $month;
154 154
 	}
155 155
 
156 156
 
@@ -162,8 +162,8 @@  discard block
 block discarded – undo
162 162
 	 * @param string $category
163 163
 	 * @return    string
164 164
 	 */
165
-	private static function _event_category_slug( $category = '' ) {
166
-		return EE_Registry::instance()->REQ->is_set( 'event_query_category' ) ? sanitize_text_field( EE_Registry::instance()->REQ->get( 'event_query_category' ) ) : $category;
165
+	private static function _event_category_slug($category = '') {
166
+		return EE_Registry::instance()->REQ->is_set('event_query_category') ? sanitize_text_field(EE_Registry::instance()->REQ->get('event_query_category')) : $category;
167 167
 	}
168 168
 
169 169
 
@@ -175,10 +175,10 @@  discard block
 block discarded – undo
175 175
 	 * @param bool $show_expired
176 176
 	 * @return    boolean
177 177
 	 */
178
-	private static function _show_expired( $show_expired = FALSE ) {
178
+	private static function _show_expired($show_expired = FALSE) {
179 179
 		// override default expired option if set via filter
180
-		$_event_query_show_expired =EE_Registry::instance()->REQ->is_set( 'event_query_show_expired' ) ? EE_Registry::instance()->REQ->get( 'event_query_show_expired' ) : $show_expired;
181
-		return filter_var( $_event_query_show_expired, FILTER_VALIDATE_BOOLEAN );
180
+		$_event_query_show_expired = EE_Registry::instance()->REQ->is_set('event_query_show_expired') ? EE_Registry::instance()->REQ->get('event_query_show_expired') : $show_expired;
181
+		return filter_var($_event_query_show_expired, FILTER_VALIDATE_BOOLEAN);
182 182
 	}
183 183
 
184 184
 
@@ -190,10 +190,10 @@  discard block
 block discarded – undo
190 190
 	 * @param    string $orderby
191 191
 	 * @return    array
192 192
 	 */
193
-	private static function _orderby( $orderby = 'start_date' ) {
194
-		$event_query_orderby = EE_Registry::instance()->REQ->is_set( 'event_query_orderby' ) ? sanitize_text_field( EE_Registry::instance()->REQ->get( 'event_query_orderby' ) ) : $orderby;
195
-		$event_query_orderby = is_array( $event_query_orderby ) ? $event_query_orderby : explode( ',', $event_query_orderby );
196
-		$event_query_orderby = array_map( 'trim', $event_query_orderby );
193
+	private static function _orderby($orderby = 'start_date') {
194
+		$event_query_orderby = EE_Registry::instance()->REQ->is_set('event_query_orderby') ? sanitize_text_field(EE_Registry::instance()->REQ->get('event_query_orderby')) : $orderby;
195
+		$event_query_orderby = is_array($event_query_orderby) ? $event_query_orderby : explode(',', $event_query_orderby);
196
+		$event_query_orderby = array_map('trim', $event_query_orderby);
197 197
 		return $event_query_orderby;
198 198
 	}
199 199
 
@@ -206,9 +206,9 @@  discard block
 block discarded – undo
206 206
 	 * @param string $sort
207 207
 	 * @return    array
208 208
 	 */
209
-	private static function _sort( $sort = 'ASC' ) {
210
-		$sort = EE_Registry::instance()->REQ->is_set( 'event_query_sort' ) ? sanitize_text_field( EE_Registry::instance()->REQ->get( 'event_query_sort' ) ) : $sort;
211
-		return in_array( $sort, array( 'ASC', 'asc', 'DESC', 'desc' )) ? strtoupper( $sort ) : 'ASC';
209
+	private static function _sort($sort = 'ASC') {
210
+		$sort = EE_Registry::instance()->REQ->is_set('event_query_sort') ? sanitize_text_field(EE_Registry::instance()->REQ->get('event_query_sort')) : $sort;
211
+		return in_array($sort, array('ASC', 'asc', 'DESC', 'desc')) ? strtoupper($sort) : 'ASC';
212 212
 	}
213 213
 
214 214
 
@@ -221,10 +221,10 @@  discard block
 block discarded – undo
221 221
 	 *
222 222
 	 * @return array   array of clauses
223 223
 	 */
224
-	public static function posts_clauses( $clauses, WP_Query $wp_query ) {
225
-		if ( EEH_Event_Query::apply_query_filters( $wp_query ) ) {
224
+	public static function posts_clauses($clauses, WP_Query $wp_query) {
225
+		if (EEH_Event_Query::apply_query_filters($wp_query)) {
226 226
 			global $wpdb;
227
-			$clauses['groupby'] = $wpdb->posts . '.ID ';
227
+			$clauses['groupby'] = $wpdb->posts.'.ID ';
228 228
 		}
229 229
 		return $clauses;
230 230
 	}
@@ -239,10 +239,10 @@  discard block
 block discarded – undo
239 239
 	 * @param WP_Query $wp_query
240 240
 	 * @return    string
241 241
 	 */
242
-	public static function posts_fields( $SQL, WP_Query $wp_query ) {
243
-		if ( EEH_Event_Query::apply_query_filters( $wp_query ) ) {
242
+	public static function posts_fields($SQL, WP_Query $wp_query) {
243
+		if (EEH_Event_Query::apply_query_filters($wp_query)) {
244 244
 			// adds something like ", wp_esp_datetime.* " to WP Query SELECT statement
245
-			$SQL .= EEH_Event_Query::posts_fields_sql_for_orderby( EEH_Event_Query::$_event_query_orderby );
245
+			$SQL .= EEH_Event_Query::posts_fields_sql_for_orderby(EEH_Event_Query::$_event_query_orderby);
246 246
 		}
247 247
 		return $SQL;
248 248
 	}
@@ -257,29 +257,29 @@  discard block
 block discarded – undo
257 257
 	 * @internal  param bool|string $mixed $join_terms pass TRUE or term string, doesn't really matter since this value doesn't really get used for anything yet
258 258
 	 * @return    string
259 259
 	 */
260
-	public static function posts_fields_sql_for_orderby( $orderby_params = array() ) {
261
-		$SQL = ', MIN( ' . EEM_Datetime::instance()->table() . '.DTT_EVT_start ) as event_start_date ' ;
262
-		foreach( (array)$orderby_params as $orderby ) {
263
-			switch ( $orderby ) {
260
+	public static function posts_fields_sql_for_orderby($orderby_params = array()) {
261
+		$SQL = ', MIN( '.EEM_Datetime::instance()->table().'.DTT_EVT_start ) as event_start_date ';
262
+		foreach ((array) $orderby_params as $orderby) {
263
+			switch ($orderby) {
264 264
 
265 265
 				case 'ticket_start' :
266
-					$SQL .= ', ' . EEM_Ticket::instance()->table() . '.TKT_start_date' ;
266
+					$SQL .= ', '.EEM_Ticket::instance()->table().'.TKT_start_date';
267 267
 					break;
268 268
 
269 269
 				case 'ticket_end' :
270
-					$SQL .= ', ' . EEM_Ticket::instance()->table() . '.TKT_end_date' ;
270
+					$SQL .= ', '.EEM_Ticket::instance()->table().'.TKT_end_date';
271 271
 					break;
272 272
 
273 273
 				case 'venue_title' :
274
-					$SQL .= ', Venue.post_title AS venue_title' ;
274
+					$SQL .= ', Venue.post_title AS venue_title';
275 275
 					break;
276 276
 
277 277
 				case 'city' :
278
-					$SQL .= ', ' . EEM_Venue::instance()->second_table() . '.VNU_city' ;
278
+					$SQL .= ', '.EEM_Venue::instance()->second_table().'.VNU_city';
279 279
 					break;
280 280
 
281 281
 				case 'state' :
282
-					$SQL .= ', ' . EEM_State::instance()->table() . '.STA_name' ;
282
+					$SQL .= ', '.EEM_State::instance()->table().'.STA_name';
283 283
 					break;
284 284
 
285 285
 			}
@@ -297,12 +297,12 @@  discard block
 block discarded – undo
297 297
 	 * @param WP_Query $wp_query
298 298
 	 * @return    string
299 299
 	 */
300
-	public static function posts_join( $SQL = '', WP_Query $wp_query ) {
301
-		if ( EEH_Event_Query::apply_query_filters( $wp_query ) ) {
300
+	public static function posts_join($SQL = '', WP_Query $wp_query) {
301
+		if (EEH_Event_Query::apply_query_filters($wp_query)) {
302 302
 			// Category
303
-			$SQL = EEH_Event_Query::posts_join_sql_for_show_expired( $SQL, EEH_Event_Query::$_event_query_show_expired );
304
-			$SQL = EEH_Event_Query::posts_join_sql_for_terms( $SQL, EEH_Event_Query::$_event_query_category );
305
-			$SQL = EEH_Event_Query::posts_join_for_orderby( $SQL, EEH_Event_Query::$_event_query_orderby );
303
+			$SQL = EEH_Event_Query::posts_join_sql_for_show_expired($SQL, EEH_Event_Query::$_event_query_show_expired);
304
+			$SQL = EEH_Event_Query::posts_join_sql_for_terms($SQL, EEH_Event_Query::$_event_query_category);
305
+			$SQL = EEH_Event_Query::posts_join_for_orderby($SQL, EEH_Event_Query::$_event_query_orderby);
306 306
 		}
307 307
 		return $SQL;
308 308
 	}
@@ -317,11 +317,11 @@  discard block
 block discarded – undo
317 317
 	 * @param    boolean $show_expired if TRUE, then displayed past events
318 318
 	 * @return string
319 319
 	 */
320
-	public static function posts_join_sql_for_show_expired( $SQL = '', $show_expired = FALSE ) {
321
-		if ( ! $show_expired ) {
322
-			$join = EEM_Event::instance()->table() . '.ID = ' . EEM_Datetime::instance()->table() . '.' . EEM_Event::instance()->primary_key_name();
323
-			if ( strpos( $SQL, $join ) === FALSE ) {
324
-				$SQL .= ' INNER JOIN ' . EEM_Datetime::instance()->table() . ' ON ( ' . $join . ' ) ';
320
+	public static function posts_join_sql_for_show_expired($SQL = '', $show_expired = FALSE) {
321
+		if ( ! $show_expired) {
322
+			$join = EEM_Event::instance()->table().'.ID = '.EEM_Datetime::instance()->table().'.'.EEM_Event::instance()->primary_key_name();
323
+			if (strpos($SQL, $join) === FALSE) {
324
+				$SQL .= ' INNER JOIN '.EEM_Datetime::instance()->table().' ON ( '.$join.' ) ';
325 325
 			}
326 326
 		}
327 327
 		return $SQL;
@@ -337,8 +337,8 @@  discard block
 block discarded – undo
337 337
 	 * @param 	string $join_terms pass TRUE or term string, doesn't really matter since this value doesn't really get used for anything yet
338 338
 	 * @return 	string
339 339
 	 */
340
-	public static function posts_join_sql_for_terms( $SQL = '', $join_terms = '' ) {
341
-		if ( ! empty( $join_terms ) ) {
340
+	public static function posts_join_sql_for_terms($SQL = '', $join_terms = '') {
341
+		if ( ! empty($join_terms)) {
342 342
 			global $wpdb;
343 343
 			$SQL .= " LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)";
344 344
 			$SQL .= " LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)";
@@ -358,25 +358,25 @@  discard block
 block discarded – undo
358 358
 	 * @param 	array $orderby_params
359 359
 	 * @return 	string
360 360
 	 */
361
-	public static function posts_join_for_orderby( $SQL = '', $orderby_params = array() ) {
362
-		foreach ( (array)$orderby_params as $orderby ) {
363
-			switch ( $orderby ) {
361
+	public static function posts_join_for_orderby($SQL = '', $orderby_params = array()) {
362
+		foreach ((array) $orderby_params as $orderby) {
363
+			switch ($orderby) {
364 364
 				case 'ticket_start' :
365 365
 				case 'ticket_end' :
366
-					$SQL .= EEH_Event_Query::_posts_join_for_datetime( $SQL, EEM_Datetime_Ticket::instance()->table() . '.' . EEM_Datetime::instance()->primary_key_name() );
367
-					$SQL .= ' LEFT JOIN ' . EEM_Ticket::instance()->table() . ' ON (' . EEM_Datetime_Ticket::instance()->table() . '.' . EEM_Ticket::instance()->primary_key_name() . ' = ' . EEM_Ticket::instance()->table() . '.' . EEM_Ticket::instance()->primary_key_name() . ' )';
366
+					$SQL .= EEH_Event_Query::_posts_join_for_datetime($SQL, EEM_Datetime_Ticket::instance()->table().'.'.EEM_Datetime::instance()->primary_key_name());
367
+					$SQL .= ' LEFT JOIN '.EEM_Ticket::instance()->table().' ON ('.EEM_Datetime_Ticket::instance()->table().'.'.EEM_Ticket::instance()->primary_key_name().' = '.EEM_Ticket::instance()->table().'.'.EEM_Ticket::instance()->primary_key_name().' )';
368 368
 					break;
369 369
 				case 'venue_title' :
370 370
 				case 'city' :
371
-					$SQL .= EEH_Event_Query::_posts_join_for_event_venue( $SQL );
371
+					$SQL .= EEH_Event_Query::_posts_join_for_event_venue($SQL);
372 372
 					break;
373 373
 				case 'state' :
374
-					$SQL .= EEH_Event_Query::_posts_join_for_event_venue( $SQL );
375
-					$SQL .= EEH_Event_Query::_posts_join_for_venue_state( $SQL );
374
+					$SQL .= EEH_Event_Query::_posts_join_for_event_venue($SQL);
375
+					$SQL .= EEH_Event_Query::_posts_join_for_venue_state($SQL);
376 376
 					break;
377 377
 				case 'start_date' :
378 378
 				default :
379
-					$SQL .= EEH_Event_Query::_posts_join_for_datetime( $SQL, EEM_Event::instance()->table() . '.ID' );
379
+					$SQL .= EEH_Event_Query::_posts_join_for_datetime($SQL, EEM_Event::instance()->table().'.ID');
380 380
 					break;
381 381
 
382 382
 			}
@@ -394,11 +394,11 @@  discard block
 block discarded – undo
394 394
 	 * @param string $join
395 395
 	 * @return string
396 396
 	 */
397
-	protected static function _posts_join_for_datetime( $SQL = '', $join = '' ) {
398
-		if ( ! empty( $join )) {
399
-			$join .= ' = ' . EEM_Datetime::instance()->table() . '.' . EEM_Event::instance()->primary_key_name();
400
-			if ( strpos( $SQL, $join ) === FALSE ) {
401
-				return ' INNER JOIN ' . EEM_Datetime::instance()->table() . ' ON ( ' . $join . ' )';
397
+	protected static function _posts_join_for_datetime($SQL = '', $join = '') {
398
+		if ( ! empty($join)) {
399
+			$join .= ' = '.EEM_Datetime::instance()->table().'.'.EEM_Event::instance()->primary_key_name();
400
+			if (strpos($SQL, $join) === FALSE) {
401
+				return ' INNER JOIN '.EEM_Datetime::instance()->table().' ON ( '.$join.' )';
402 402
 			}
403 403
 		}
404 404
 		return '';
@@ -413,13 +413,13 @@  discard block
 block discarded – undo
413 413
 	 * @param string $SQL
414 414
 	 * @return string
415 415
 	 */
416
-	protected static function _posts_join_for_event_venue( $SQL = '' ) {
416
+	protected static function _posts_join_for_event_venue($SQL = '') {
417 417
 		// Event Venue table name
418 418
 		$event_venue_table = EEM_Event_Venue::instance()->table();
419 419
 		// generate conditions for:  Event <=> Event Venue  JOIN clause
420
-		$event_to_event_venue_join = EEM_Event::instance()->table() . '.ID = ' . $event_venue_table . '.' . EEM_Event::instance()->primary_key_name();
420
+		$event_to_event_venue_join = EEM_Event::instance()->table().'.ID = '.$event_venue_table.'.'.EEM_Event::instance()->primary_key_name();
421 421
 		// don't add joins if they have already been added
422
-		if ( strpos( $SQL, $event_to_event_venue_join ) === FALSE ) {
422
+		if (strpos($SQL, $event_to_event_venue_join) === FALSE) {
423 423
 			// Venue table name
424 424
 			$venue_table = EEM_Venue::instance()->table();
425 425
 			// Venue table pk
@@ -432,10 +432,10 @@  discard block
 block discarded – undo
432 432
 			$venue_SQL .= " LEFT JOIN $venue_table as Venue ON ( $event_venue_table.$venue_table_pk = Venue.ID )";
433 433
 			// generate JOIN clause for: Venue <=> Venue Meta
434 434
 			$venue_SQL .= " LEFT JOIN $venue_meta_table ON ( Venue.ID = $venue_meta_table.$venue_table_pk )";
435
-			unset( $event_venue_table, $event_to_event_venue_join, $venue_table, $venue_table_pk, $venue_meta_table );
435
+			unset($event_venue_table, $event_to_event_venue_join, $venue_table, $venue_table_pk, $venue_meta_table);
436 436
 			return $venue_SQL;
437 437
 		}
438
-		unset( $event_venue_table, $event_to_event_venue_join );
438
+		unset($event_venue_table, $event_to_event_venue_join);
439 439
 		return '';
440 440
 	}
441 441
 
@@ -448,7 +448,7 @@  discard block
 block discarded – undo
448 448
 	 * @param string $SQL
449 449
 	 * @return string
450 450
 	 */
451
-	protected static function _posts_join_for_venue_state( $SQL = '' ) {
451
+	protected static function _posts_join_for_venue_state($SQL = '') {
452 452
 		// Venue Meta table name
453 453
 		$venue_meta_table = EEM_Venue::instance()->second_table();
454 454
 		// State table name
@@ -456,16 +456,16 @@  discard block
 block discarded – undo
456 456
 		// State table pk
457 457
 		$state_table_pk = EEM_State::instance()->primary_key_name();
458 458
 		// verify vars
459
-		if ( $venue_meta_table && $state_table && $state_table_pk ) {
459
+		if ($venue_meta_table && $state_table && $state_table_pk) {
460 460
 			// like: wp_esp_venue_meta.STA_ID = wp_esp_state.STA_ID
461 461
 			$join = "$venue_meta_table.$state_table_pk = $state_table.$state_table_pk";
462 462
 			// don't add join if it has already been added
463
-			if ( strpos( $SQL, $join ) === FALSE ) {
464
-				unset( $state_table_pk, $venue_meta_table, $venue_table_pk );
463
+			if (strpos($SQL, $join) === FALSE) {
464
+				unset($state_table_pk, $venue_meta_table, $venue_table_pk);
465 465
 				return " LEFT JOIN $state_table ON ( $join )";
466 466
 			}
467 467
 		}
468
-		unset( $join, $state_table, $state_table_pk, $venue_meta_table, $venue_table_pk );
468
+		unset($join, $state_table, $state_table_pk, $venue_meta_table, $venue_table_pk);
469 469
 		return '';
470 470
 	}
471 471
 
@@ -479,14 +479,14 @@  discard block
 block discarded – undo
479 479
 	 * @param WP_Query $wp_query
480 480
 	 * @return    string
481 481
 	 */
482
-	public static function posts_where( $SQL = '', WP_Query $wp_query ) {
483
-		if ( EEH_Event_Query::apply_query_filters( $wp_query ) ) {
482
+	public static function posts_where($SQL = '', WP_Query $wp_query) {
483
+		if (EEH_Event_Query::apply_query_filters($wp_query)) {
484 484
 			// Show Expired ?
485
-			$SQL .= EEH_Event_Query::posts_where_sql_for_show_expired( EEH_Event_Query::$_event_query_show_expired  );
485
+			$SQL .= EEH_Event_Query::posts_where_sql_for_show_expired(EEH_Event_Query::$_event_query_show_expired);
486 486
 			// Category
487
-			$SQL .= EEH_Event_Query::posts_where_sql_for_event_category_slug( EEH_Event_Query::$_event_query_category  );
487
+			$SQL .= EEH_Event_Query::posts_where_sql_for_event_category_slug(EEH_Event_Query::$_event_query_category);
488 488
 			// Start Date
489
-			$SQL .= EEH_Event_Query::posts_where_sql_for_event_list_month( EEH_Event_Query::$_event_query_month );
489
+			$SQL .= EEH_Event_Query::posts_where_sql_for_event_list_month(EEH_Event_Query::$_event_query_month);
490 490
 		}
491 491
 		return $SQL;
492 492
 	}
@@ -500,8 +500,8 @@  discard block
 block discarded – undo
500 500
 	 * @param    boolean $show_expired if TRUE, then displayed past events
501 501
 	 * @return    string
502 502
 	 */
503
-	public static function posts_where_sql_for_show_expired( $show_expired = FALSE ) {
504
-		return ! $show_expired ? ' AND ' . EEM_Datetime::instance()->table() . '.DTT_EVT_end > \'' . current_time( 'mysql', TRUE ) . '\' ' : '';
503
+	public static function posts_where_sql_for_show_expired($show_expired = FALSE) {
504
+		return ! $show_expired ? ' AND '.EEM_Datetime::instance()->table().'.DTT_EVT_end > \''.current_time('mysql', TRUE).'\' ' : '';
505 505
 	}
506 506
 
507 507
 
@@ -513,9 +513,9 @@  discard block
 block discarded – undo
513 513
 	 * @param    boolean $event_category_slug
514 514
 	 * @return    string
515 515
 	 */
516
-	public static function posts_where_sql_for_event_category_slug( $event_category_slug = NULL ) {
516
+	public static function posts_where_sql_for_event_category_slug($event_category_slug = NULL) {
517 517
 		global $wpdb;
518
-		return ! empty( $event_category_slug ) ? " AND {$wpdb->terms}.slug = '{$event_category_slug}' " : '';
518
+		return ! empty($event_category_slug) ? " AND {$wpdb->terms}.slug = '{$event_category_slug}' " : '';
519 519
 	}
520 520
 
521 521
 
@@ -527,14 +527,14 @@  discard block
 block discarded – undo
527 527
 	 * @param    boolean $month
528 528
 	 * @return    string
529 529
 	 */
530
-	public static function posts_where_sql_for_event_list_month( $month = NULL ) {
530
+	public static function posts_where_sql_for_event_list_month($month = NULL) {
531 531
 		$SQL = '';
532
-		if ( ! empty( $month ) ) {
532
+		if ( ! empty($month)) {
533 533
 			$datetime_table = EEM_Datetime::instance()->table();
534 534
 			// event start date is LESS than the end of the month ( so nothing that doesn't start until next month )
535
-			$SQL = " AND {$datetime_table}.DTT_EVT_start <= '" . date( 'Y-m-t 23:59:59', strtotime( $month ) ) . "'";
535
+			$SQL = " AND {$datetime_table}.DTT_EVT_start <= '".date('Y-m-t 23:59:59', strtotime($month))."'";
536 536
 			// event end date is GREATER than the start of the month ( so nothing that ended before this month )
537
-			$SQL .= " AND {$datetime_table}.DTT_EVT_end >= '" . date( 'Y-m-01 0:0:00', strtotime( $month ) ) . "' ";
537
+			$SQL .= " AND {$datetime_table}.DTT_EVT_end >= '".date('Y-m-01 0:0:00', strtotime($month))."' ";
538 538
 		}
539 539
 		return $SQL;
540 540
 	}
@@ -549,9 +549,9 @@  discard block
 block discarded – undo
549 549
 	 * @param WP_Query $wp_query
550 550
 	 * @return    string
551 551
 	 */
552
-	public static function posts_orderby( $SQL = '', WP_Query $wp_query ) {
553
-		if ( EEH_Event_Query::apply_query_filters( $wp_query ) ) {
554
-			$SQL = EEH_Event_Query::posts_orderby_sql( EEH_Event_Query::$_event_query_orderby, EEH_Event_Query::$_event_query_sort );
552
+	public static function posts_orderby($SQL = '', WP_Query $wp_query) {
553
+		if (EEH_Event_Query::apply_query_filters($wp_query)) {
554
+			$SQL = EEH_Event_Query::posts_orderby_sql(EEH_Event_Query::$_event_query_orderby, EEH_Event_Query::$_event_query_sort);
555 555
 		}
556 556
 		return $SQL;
557 557
 	}
@@ -582,63 +582,63 @@  discard block
 block discarded – undo
582 582
 	 * @param string     $sort
583 583
 	 * @return string
584 584
 	 */
585
-	public static function posts_orderby_sql( $orderby_params = array(), $sort = 'ASC' ) {
585
+	public static function posts_orderby_sql($orderby_params = array(), $sort = 'ASC') {
586 586
 		global $wpdb;
587 587
 		$SQL = '';
588 588
 		$counter = 0;
589 589
 		//make sure 'orderby' is set in query params
590
-		if ( ! isset( self::$_query_params['orderby'] )) {
590
+		if ( ! isset(self::$_query_params['orderby'])) {
591 591
 			self::$_query_params['orderby'] = array();
592 592
 		}
593 593
 		// loop thru $orderby_params (type cast as array)
594
-		foreach ( (array)$orderby_params as $orderby ) {
594
+		foreach ((array) $orderby_params as $orderby) {
595 595
 			// check if we have already added this param
596
-			if ( isset( self::$_query_params['orderby'][ $orderby ] )) {
596
+			if (isset(self::$_query_params['orderby'][$orderby])) {
597 597
 				// if so then remove from the $orderby_params so that the count() method below is accurate
598
-				unset( $orderby_params[ $orderby ] );
598
+				unset($orderby_params[$orderby]);
599 599
 				// then bump ahead to the next param
600 600
 				continue;
601 601
 			}
602 602
 			// this will ad a comma depending on whether this is the first or last param
603
-			$glue = $counter == 0 || $counter == count( $orderby_params ) ? ' ' : ', ';
603
+			$glue = $counter == 0 || $counter == count($orderby_params) ? ' ' : ', ';
604 604
 			// ok what's we dealing with?
605
-			switch ( $orderby ) {
605
+			switch ($orderby) {
606 606
 				case 'id' :
607 607
 				case 'ID' :
608
-					$SQL .= $glue . $wpdb->posts . '.ID ' . $sort;
608
+					$SQL .= $glue.$wpdb->posts.'.ID '.$sort;
609 609
 					break;
610 610
 				case 'end_date' :
611
-					$SQL .= $glue . EEM_Datetime::instance()->table() . '.DTT_EVT_end ' . $sort;
611
+					$SQL .= $glue.EEM_Datetime::instance()->table().'.DTT_EVT_end '.$sort;
612 612
 					break;
613 613
 				case 'event_name' :
614
-					$SQL .= $glue . $wpdb->posts . '.post_title ' . $sort;
614
+					$SQL .= $glue.$wpdb->posts.'.post_title '.$sort;
615 615
 					break;
616 616
 				case 'category_slug' :
617
-					$SQL .= $glue . $wpdb->terms . '.slug ' . $sort;
617
+					$SQL .= $glue.$wpdb->terms.'.slug '.$sort;
618 618
 					break;
619 619
 				case 'ticket_start' :
620
-					$SQL .= $glue . EEM_Ticket::instance()->table() . '.TKT_start_date ' . $sort;
620
+					$SQL .= $glue.EEM_Ticket::instance()->table().'.TKT_start_date '.$sort;
621 621
 					break;
622 622
 				case 'ticket_end' :
623
-					$SQL .= $glue . EEM_Ticket::instance()->table() . '.TKT_end_date ' . $sort;
623
+					$SQL .= $glue.EEM_Ticket::instance()->table().'.TKT_end_date '.$sort;
624 624
 					break;
625 625
 				case 'venue_title' :
626
-					$SQL .= $glue . 'venue_title ' . $sort;
626
+					$SQL .= $glue.'venue_title '.$sort;
627 627
 					break;
628 628
 				case 'city' :
629
-					$SQL .= $glue . EEM_Venue::instance()->second_table() . '.VNU_city ' . $sort;
629
+					$SQL .= $glue.EEM_Venue::instance()->second_table().'.VNU_city '.$sort;
630 630
 					break;
631 631
 				case 'state' :
632
-					$SQL .= $glue . EEM_State::instance()->table() . '.STA_name ' . $sort;
632
+					$SQL .= $glue.EEM_State::instance()->table().'.STA_name '.$sort;
633 633
 					break;
634 634
 				case 'start_date' :
635 635
 				default :
636
-					$SQL .= $glue . ' event_start_date ' . $sort;
636
+					$SQL .= $glue.' event_start_date '.$sort;
637 637
 					break;
638 638
 			}
639 639
 			// add to array of orderby params that have been added
640
-			self::$_query_params['orderby'][ $orderby ] = TRUE;
641
-			$counter ++;
640
+			self::$_query_params['orderby'][$orderby] = TRUE;
641
+			$counter++;
642 642
 		}
643 643
 		return $SQL;
644 644
 	}
Please login to merge, or discard this patch.
espresso.php 1 patch
Spacing   +91 added lines, -91 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1
-<?php if ( ! defined( 'ABSPATH' ) ) {
2
-	exit( 'No direct script access allowed' );
1
+<?php if ( ! defined('ABSPATH')) {
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /*
5 5
   Plugin Name:		Event Espresso
@@ -39,7 +39,7 @@  discard block
 block discarded – undo
39 39
  * @link             {@link http://www.eventespresso.com}
40 40
  * @since            4.0
41 41
  */
42
-if ( function_exists( 'espresso_version' ) ) {
42
+if (function_exists('espresso_version')) {
43 43
 
44 44
 	/**
45 45
 	 *    espresso_duplicate_plugin_error
@@ -56,15 +56,15 @@  discard block
 block discarded – undo
56 56
 			</p>
57 57
 		</div>
58 58
 		<?php
59
-		espresso_deactivate_plugin( plugin_basename( __FILE__ ) );
59
+		espresso_deactivate_plugin(plugin_basename(__FILE__));
60 60
 	}
61
-	add_action( 'admin_notices', 'espresso_duplicate_plugin_error', 1 );
61
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62 62
 
63 63
 } else {
64 64
 
65
-	define( 'EE_MIN_PHP_VER_REQUIRED', '5.3.0' );
65
+	define('EE_MIN_PHP_VER_REQUIRED', '5.3.0');
66 66
 
67
-	if ( ! version_compare( PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=' ) ) {
67
+	if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
68 68
 
69 69
 		/**
70 70
 		 * espresso_minimum_php_version_error
@@ -90,9 +90,9 @@  discard block
 block discarded – undo
90 90
 				</p>
91 91
 			</div>
92 92
 			<?php
93
-			espresso_deactivate_plugin( plugin_basename( __FILE__ ) );
93
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
94 94
 		}
95
-		add_action( 'admin_notices', 'espresso_minimum_php_version_error', 1 );
95
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
96 96
 
97 97
 	} else {
98 98
 
@@ -103,99 +103,99 @@  discard block
 block discarded – undo
103 103
 		 * @return string
104 104
 		 */
105 105
 		function espresso_version() {
106
-			return apply_filters( 'FHEE__espresso__espresso_version', '4.9.20.rc.002' );
106
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.20.rc.002');
107 107
 		}
108 108
 
109 109
 		// define versions
110
-		define( 'EVENT_ESPRESSO_VERSION', espresso_version() );
111
-		define( 'EE_MIN_WP_VER_REQUIRED', '4.1' );
112
-		define( 'EE_MIN_WP_VER_RECOMMENDED', '4.4.2' );
113
-		define( 'EE_MIN_PHP_VER_RECOMMENDED', '5.4.44' );
114
-		define( 'EVENT_ESPRESSO_MAIN_FILE', __FILE__ );
110
+		define('EVENT_ESPRESSO_VERSION', espresso_version());
111
+		define('EE_MIN_WP_VER_REQUIRED', '4.1');
112
+		define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
113
+		define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
114
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
115 115
 
116 116
 		//used to be DIRECTORY_SEPARATOR, but that caused issues on windows
117
-		if ( ! defined( 'DS' ) ) {
118
-			define( 'DS', '/' );
117
+		if ( ! defined('DS')) {
118
+			define('DS', '/');
119 119
 		}
120
-		if ( ! defined( 'PS' ) ) {
121
-			define( 'PS', PATH_SEPARATOR );
120
+		if ( ! defined('PS')) {
121
+			define('PS', PATH_SEPARATOR);
122 122
 		}
123
-		if ( ! defined( 'SP' ) ) {
124
-			define( 'SP', ' ' );
123
+		if ( ! defined('SP')) {
124
+			define('SP', ' ');
125 125
 		}
126
-		if ( ! defined( 'EENL' ) ) {
127
-			define( 'EENL', "\n" );
126
+		if ( ! defined('EENL')) {
127
+			define('EENL', "\n");
128 128
 		}
129
-		define( 'EE_SUPPORT_EMAIL', '[email protected]' );
129
+		define('EE_SUPPORT_EMAIL', '[email protected]');
130 130
 		// define the plugin directory and URL
131
-		define( 'EE_PLUGIN_BASENAME', plugin_basename( EVENT_ESPRESSO_MAIN_FILE ) );
132
-		define( 'EE_PLUGIN_DIR_PATH', plugin_dir_path( EVENT_ESPRESSO_MAIN_FILE ) );
133
-		define( 'EE_PLUGIN_DIR_URL', plugin_dir_url( EVENT_ESPRESSO_MAIN_FILE ) );
131
+		define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
132
+		define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
133
+		define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
134 134
 		// main root folder paths
135
-		define( 'EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS );
136
-		define( 'EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS );
137
-		define( 'EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS );
138
-		define( 'EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS );
139
-		define( 'EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS );
140
-		define( 'EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS );
141
-		define( 'EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS );
142
-		define( 'EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS );
135
+		define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH.'admin_pages'.DS);
136
+		define('EE_CORE', EE_PLUGIN_DIR_PATH.'core'.DS);
137
+		define('EE_MODULES', EE_PLUGIN_DIR_PATH.'modules'.DS);
138
+		define('EE_PUBLIC', EE_PLUGIN_DIR_PATH.'public'.DS);
139
+		define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH.'shortcodes'.DS);
140
+		define('EE_WIDGETS', EE_PLUGIN_DIR_PATH.'widgets'.DS);
141
+		define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH.'payment_methods'.DS);
142
+		define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH.'caffeinated'.DS);
143 143
 		// core system paths
144
-		define( 'EE_ADMIN', EE_CORE . 'admin' . DS );
145
-		define( 'EE_CPTS', EE_CORE . 'CPTs' . DS );
146
-		define( 'EE_CLASSES', EE_CORE . 'db_classes' . DS );
147
-		define( 'EE_INTERFACES', EE_CORE . 'interfaces' . DS );
148
-		define( 'EE_BUSINESS', EE_CORE . 'business' . DS );
149
-		define( 'EE_MODELS', EE_CORE . 'db_models' . DS );
150
-		define( 'EE_HELPERS', EE_CORE . 'helpers' . DS );
151
-		define( 'EE_LIBRARIES', EE_CORE . 'libraries' . DS );
152
-		define( 'EE_TEMPLATES', EE_CORE . 'templates' . DS );
153
-		define( 'EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS );
154
-		define( 'EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS );
155
-		define( 'EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS );
144
+		define('EE_ADMIN', EE_CORE.'admin'.DS);
145
+		define('EE_CPTS', EE_CORE.'CPTs'.DS);
146
+		define('EE_CLASSES', EE_CORE.'db_classes'.DS);
147
+		define('EE_INTERFACES', EE_CORE.'interfaces'.DS);
148
+		define('EE_BUSINESS', EE_CORE.'business'.DS);
149
+		define('EE_MODELS', EE_CORE.'db_models'.DS);
150
+		define('EE_HELPERS', EE_CORE.'helpers'.DS);
151
+		define('EE_LIBRARIES', EE_CORE.'libraries'.DS);
152
+		define('EE_TEMPLATES', EE_CORE.'templates'.DS);
153
+		define('EE_THIRD_PARTY', EE_CORE.'third_party_libs'.DS);
154
+		define('EE_GLOBAL_ASSETS', EE_TEMPLATES.'global_assets'.DS);
155
+		define('EE_FORM_SECTIONS', EE_LIBRARIES.'form_sections'.DS);
156 156
 		// gateways
157
-		define( 'EE_GATEWAYS', EE_MODULES . 'gateways' . DS );
158
-		define( 'EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS );
157
+		define('EE_GATEWAYS', EE_MODULES.'gateways'.DS);
158
+		define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL.'modules'.DS.'gateways'.DS);
159 159
 		// asset URL paths
160
-		define( 'EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS );
161
-		define( 'EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS );
162
-		define( 'EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS );
163
-		define( 'EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS );
164
-		define( 'EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/' );
165
-		define( 'EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/' );
160
+		define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL.'core'.DS.'templates'.DS);
161
+		define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL.'global_assets'.DS);
162
+		define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL.'images'.DS);
163
+		define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL.'core'.DS.'third_party_libs'.DS);
164
+		define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL.'core/helpers/assets/');
165
+		define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL.'core/libraries/');
166 166
 		// define upload paths
167 167
 		$uploads = wp_upload_dir();
168 168
 		// define the uploads directory and URL
169
-		define( 'EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS );
170
-		define( 'EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS );
169
+		define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'].DS.'espresso'.DS);
170
+		define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'].DS.'espresso'.DS);
171 171
 		// define the templates directory and URL
172
-		define( 'EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS );
173
-		define( 'EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS );
172
+		define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'].DS.'espresso'.DS.'templates'.DS);
173
+		define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'].DS.'espresso'.DS.'templates'.DS);
174 174
 		// define the gateway directory and URL
175
-		define( 'EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS );
176
-		define( 'EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS );
175
+		define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'].DS.'espresso'.DS.'gateways'.DS);
176
+		define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'].DS.'espresso'.DS.'gateways'.DS);
177 177
 		// languages folder/path
178
-		define( 'EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS );
179
-		define( 'EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS );
178
+		define('EE_LANGUAGES_SAFE_LOC', '..'.DS.'uploads'.DS.'espresso'.DS.'languages'.DS);
179
+		define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR.'languages'.DS);
180 180
 		//check for dompdf fonts in uploads
181
-		if ( file_exists( EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS ) ) {
182
-			define( 'DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS );
181
+		if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR.'fonts'.DS)) {
182
+			define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR.'fonts'.DS);
183 183
 		}
184 184
 		//ajax constants
185 185
 		define(
186 186
 			'EE_FRONT_AJAX',
187
-			isset( $_REQUEST['ee_front_ajax'] ) || isset( $_REQUEST['data']['ee_front_ajax'] ) ? true : false
187
+			isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
188 188
 		);
189 189
 		define(
190 190
 			'EE_ADMIN_AJAX',
191
-			isset( $_REQUEST['ee_admin_ajax'] ) || isset( $_REQUEST['data']['ee_admin_ajax'] ) ? true : false
191
+			isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
192 192
 		);
193 193
 		//just a handy constant occasionally needed for finding values representing infinity in the DB
194 194
 		//you're better to use this than its straight value (currently -1) in case you ever
195 195
 		//want to change its default value! or find when -1 means infinity
196
-		define( 'EE_INF_IN_DB', -1 );
197
-		define( 'EE_INF', INF > (float) PHP_INT_MAX ? INF : PHP_INT_MAX );
198
-		define( 'EE_DEBUG', false );
196
+		define('EE_INF_IN_DB', -1);
197
+		define('EE_INF', INF > (float) PHP_INT_MAX ? INF : PHP_INT_MAX);
198
+		define('EE_DEBUG', false);
199 199
 
200 200
 
201 201
 		/**
@@ -203,9 +203,9 @@  discard block
 block discarded – undo
203 203
 		 *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
204 204
 		 */
205 205
 		function espresso_plugin_activation() {
206
-			update_option( 'ee_espresso_activation', true );
206
+			update_option('ee_espresso_activation', true);
207 207
 		}
208
-		register_activation_hook( EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation' );
208
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
209 209
 
210 210
 
211 211
 
@@ -215,15 +215,15 @@  discard block
 block discarded – undo
215 215
 		 */
216 216
 		function espresso_load_error_handling() {
217 217
 			// load debugging tools
218
-			if ( WP_DEBUG === true && is_readable( EE_HELPERS . 'EEH_Debug_Tools.helper.php' ) ) {
219
-				require_once( EE_HELPERS . 'EEH_Debug_Tools.helper.php' );
218
+			if (WP_DEBUG === true && is_readable(EE_HELPERS.'EEH_Debug_Tools.helper.php')) {
219
+				require_once(EE_HELPERS.'EEH_Debug_Tools.helper.php');
220 220
 				EEH_Debug_Tools::instance();
221 221
 			}
222 222
 			// load error handling
223
-			if ( is_readable( EE_CORE . 'EE_Error.core.php' ) ) {
224
-				require_once( EE_CORE . 'EE_Error.core.php' );
223
+			if (is_readable(EE_CORE.'EE_Error.core.php')) {
224
+				require_once(EE_CORE.'EE_Error.core.php');
225 225
 			} else {
226
-				wp_die( esc_html__( 'The EE_Error core class could not be loaded.', 'event_espresso' ) );
226
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
227 227
 			}
228 228
 		}
229 229
 
@@ -237,16 +237,16 @@  discard block
 block discarded – undo
237 237
 		 * @param    string $full_path_to_file
238 238
 		 * @throws    EE_Error
239 239
 		 */
240
-		function espresso_load_required( $classname, $full_path_to_file ) {
240
+		function espresso_load_required($classname, $full_path_to_file) {
241 241
 			static $error_handling_loaded = false;
242
-			if ( ! $error_handling_loaded ) {
242
+			if ( ! $error_handling_loaded) {
243 243
 				espresso_load_error_handling();
244 244
 				$error_handling_loaded = true;
245 245
 			}
246
-			if ( is_readable( $full_path_to_file ) ) {
247
-				require_once( $full_path_to_file );
246
+			if (is_readable($full_path_to_file)) {
247
+				require_once($full_path_to_file);
248 248
 			} else {
249
-				throw new EE_Error (
249
+				throw new EE_Error(
250 250
 					sprintf(
251 251
 						esc_html__(
252 252
 							'The %s class file could not be located or is not readable due to file permissions.',
@@ -258,15 +258,15 @@  discard block
 block discarded – undo
258 258
 			}
259 259
 		}
260 260
 
261
-		espresso_load_required( 'EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php' );
262
-		espresso_load_required( 'EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php' );
263
-		espresso_load_required( 'EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php' );
261
+		espresso_load_required('EEH_Base', EE_CORE.'helpers'.DS.'EEH_Base.helper.php');
262
+		espresso_load_required('EEH_File', EE_CORE.'helpers'.DS.'EEH_File.helper.php');
263
+		espresso_load_required('EE_Bootstrap', EE_CORE.'EE_Bootstrap.core.php');
264 264
 		new EE_Bootstrap();
265 265
 
266 266
 	}
267 267
 }
268 268
 
269
-if ( ! function_exists( 'espresso_deactivate_plugin' ) ) {
269
+if ( ! function_exists('espresso_deactivate_plugin')) {
270 270
 
271 271
 	/**
272 272
 	 *    deactivate_plugin
@@ -276,12 +276,12 @@  discard block
 block discarded – undo
276 276
 	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
277 277
 	 * @return    void
278 278
 	 */
279
-	function espresso_deactivate_plugin( $plugin_basename = '' ) {
280
-		if ( ! function_exists( 'deactivate_plugins' ) ) {
281
-			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
279
+	function espresso_deactivate_plugin($plugin_basename = '') {
280
+		if ( ! function_exists('deactivate_plugins')) {
281
+			require_once(ABSPATH.'wp-admin/includes/plugin.php');
282 282
 		}
283
-		unset( $_GET['activate'], $_REQUEST['activate'] );
284
-		deactivate_plugins( $plugin_basename );
283
+		unset($_GET['activate'], $_REQUEST['activate']);
284
+		deactivate_plugins($plugin_basename);
285 285
 	}
286 286
 
287 287
 }
Please login to merge, or discard this patch.