Completed
Branch FET-8385-datetime-ticket-selec... (f41f36)
by
unknown
184:03 queued 173:38
created
core/data_migration_scripts/EE_DMS_Core_4_3_0.dms.php 1 patch
Indentation   +194 added lines, -194 removed lines patch added patch discarded remove patch
@@ -14,11 +14,11 @@  discard block
 block discarded – undo
14 14
 $stages = glob(EE_CORE . 'data_migration_scripts/4_3_0_stages/*');
15 15
 $class_to_filepath = array();
16 16
 if ( ! empty($stages)) {
17
-    foreach ($stages as $filepath) {
18
-        $matches = array();
19
-        preg_match('~4_3_0_stages/(.*).dmsstage.php~', $filepath, $matches);
20
-        $class_to_filepath[$matches[1]] = $filepath;
21
-    }
17
+	foreach ($stages as $filepath) {
18
+		$matches = array();
19
+		preg_match('~4_3_0_stages/(.*).dmsstage.php~', $filepath, $matches);
20
+		$class_to_filepath[$matches[1]] = $filepath;
21
+	}
22 22
 }
23 23
 //give addons a chance to autoload their stages too
24 24
 $class_to_filepath = apply_filters('FHEE__EE_DMS_4_3_0__autoloaded_stages', $class_to_filepath);
@@ -31,57 +31,57 @@  discard block
 block discarded – undo
31 31
 
32 32
 
33 33
 
34
-    /**
35
-     * EE_DMS_Core_4_3_0 constructor.
36
-     *
37
-     * @param TableManager  $table_manager
38
-     * @param TableAnalysis $table_analysis
39
-     */
40
-    public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
41
-    {
42
-        $this->_pretty_name = __("Data Update to Event Espresso 4.3.0", "event_espresso");
43
-        $this->_priority = 10;
44
-        $this->_migration_stages = array(
45
-            new EE_DMS_4_3_0_question_option_order(),
46
-            new EE_DMS_4_3_0_event_message_templates(),
47
-            new EE_DMS_4_3_0_critical_page_shortcode_tracking(),
48
-        );
49
-        parent::__construct($table_manager, $table_analysis);
50
-    }
34
+	/**
35
+	 * EE_DMS_Core_4_3_0 constructor.
36
+	 *
37
+	 * @param TableManager  $table_manager
38
+	 * @param TableAnalysis $table_analysis
39
+	 */
40
+	public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
41
+	{
42
+		$this->_pretty_name = __("Data Update to Event Espresso 4.3.0", "event_espresso");
43
+		$this->_priority = 10;
44
+		$this->_migration_stages = array(
45
+			new EE_DMS_4_3_0_question_option_order(),
46
+			new EE_DMS_4_3_0_event_message_templates(),
47
+			new EE_DMS_4_3_0_critical_page_shortcode_tracking(),
48
+		);
49
+		parent::__construct($table_manager, $table_analysis);
50
+	}
51 51
 
52 52
 
53 53
 
54
-    public function can_migrate_from_version($version_array)
55
-    {
56
-        $version_string = $version_array['Core'];
57
-        if (version_compare($version_string, '4.3.0', '<=') && version_compare($version_string, '4.2.0', '>=')) {
54
+	public function can_migrate_from_version($version_array)
55
+	{
56
+		$version_string = $version_array['Core'];
57
+		if (version_compare($version_string, '4.3.0', '<=') && version_compare($version_string, '4.2.0', '>=')) {
58 58
 //			echo "$version_string can be migrated fro";
59
-            return true;
60
-        } elseif ( ! $version_string) {
59
+			return true;
60
+		} elseif ( ! $version_string) {
61 61
 //			echo "no version string provided: $version_string";
62
-            //no version string provided... this must be pre 4.2
63
-            return false;//changed mind. dont want people thinking they should migrate yet because they cant
64
-        } else {
62
+			//no version string provided... this must be pre 4.2
63
+			return false;//changed mind. dont want people thinking they should migrate yet because they cant
64
+		} else {
65 65
 //			echo "$version_string doesnt apply";
66
-            return false;
67
-        }
68
-    }
66
+			return false;
67
+		}
68
+	}
69 69
 
70 70
 
71 71
 
72
-    public function schema_changes_before_migration()
73
-    {
74
-        //relies on 4.1's EEH_Activation::create_table
75
-        require_once(EE_HELPERS . 'EEH_Activation.helper.php');
76
-        $table_name = 'esp_answer';
77
-        $sql = " ANS_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
72
+	public function schema_changes_before_migration()
73
+	{
74
+		//relies on 4.1's EEH_Activation::create_table
75
+		require_once(EE_HELPERS . 'EEH_Activation.helper.php');
76
+		$table_name = 'esp_answer';
77
+		$sql = " ANS_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
78 78
 					REG_ID INT UNSIGNED NOT NULL,
79 79
 					QST_ID INT UNSIGNED NOT NULL,
80 80
 					ANS_value TEXT NOT NULL,
81 81
 					PRIMARY KEY  (ANS_ID)";
82
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
83
-        $table_name = 'esp_attendee_meta';
84
-        $sql = "ATTM_ID INT(10) UNSIGNED NOT	NULL AUTO_INCREMENT,
82
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
83
+		$table_name = 'esp_attendee_meta';
84
+		$sql = "ATTM_ID INT(10) UNSIGNED NOT	NULL AUTO_INCREMENT,
85 85
 						ATT_ID BIGINT(20) UNSIGNED NOT NULL,
86 86
 						ATT_fname VARCHAR(45) NOT NULL,
87 87
 						ATT_lname VARCHAR(45) NOT	NULL,
@@ -97,9 +97,9 @@  discard block
 block discarded – undo
97 97
 								KEY ATT_fname (ATT_fname),
98 98
 								KEY ATT_lname (ATT_lname),
99 99
 								KEY ATT_email (ATT_email)";
100
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB ');
101
-        $table_name = 'esp_country';
102
-        $sql = "CNT_ISO VARCHAR(2) COLLATE utf8_bin NOT NULL,
100
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB ');
101
+		$table_name = 'esp_country';
102
+		$sql = "CNT_ISO VARCHAR(2) COLLATE utf8_bin NOT NULL,
103 103
 					  CNT_ISO3 VARCHAR(3) COLLATE utf8_bin NOT NULL,
104 104
 					  RGN_ID TINYINT(3) UNSIGNED DEFAULT NULL,
105 105
 					  CNT_name VARCHAR(45) COLLATE utf8_bin NOT NULL,
@@ -115,9 +115,9 @@  discard block
 block discarded – undo
115 115
 					  CNT_is_EU TINYINT(1) DEFAULT '0',
116 116
 					  CNT_active TINYINT(1) DEFAULT '0',
117 117
 					  PRIMARY KEY  (CNT_ISO)";
118
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
119
-        $table_name = 'esp_datetime';
120
-        $sql = "DTT_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
118
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
119
+		$table_name = 'esp_datetime';
120
+		$sql = "DTT_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
121 121
 				  EVT_ID BIGINT(20) UNSIGNED NOT NULL,
122 122
 				  DTT_name VARCHAR(255) NOT NULL DEFAULT '',
123 123
 				  DTT_description TEXT NOT NULL,
@@ -132,9 +132,9 @@  discard block
 block discarded – undo
132 132
 						PRIMARY KEY  (DTT_ID),
133 133
 						KEY EVT_ID (EVT_ID),
134 134
 						KEY DTT_is_primary (DTT_is_primary)";
135
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
136
-        $table_name = 'esp_event_meta';
137
-        $sql = "
135
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
136
+		$table_name = 'esp_event_meta';
137
+		$sql = "
138 138
 			EVTM_ID INT NOT NULL AUTO_INCREMENT,
139 139
 			EVT_ID BIGINT(20) UNSIGNED NOT NULL,
140 140
 			EVT_display_desc TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
@@ -149,31 +149,31 @@  discard block
 block discarded – undo
149 149
 			EVT_external_URL VARCHAR(200) NULL,
150 150
 			EVT_donations TINYINT(1) NULL,
151 151
 			PRIMARY KEY  (EVTM_ID)";
152
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
153
-        $table_name = 'esp_event_question_group';
154
-        $sql = "EQG_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
152
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
153
+		$table_name = 'esp_event_question_group';
154
+		$sql = "EQG_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
155 155
 					EVT_ID BIGINT(20) UNSIGNED NOT NULL,
156 156
 					QSG_ID INT UNSIGNED NOT NULL,
157 157
 					EQG_primary TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
158 158
 					PRIMARY KEY  (EQG_ID)";
159
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
160
-        $table_name = 'esp_event_venue';
161
-        $sql = "EVV_ID INT(11) NOT NULL AUTO_INCREMENT,
159
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
160
+		$table_name = 'esp_event_venue';
161
+		$sql = "EVV_ID INT(11) NOT NULL AUTO_INCREMENT,
162 162
 				EVT_ID BIGINT(20) UNSIGNED NOT NULL,
163 163
 				VNU_ID BIGINT(20) UNSIGNED NOT NULL,
164 164
 				EVV_primary TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
165 165
 				PRIMARY KEY  (EVV_ID)";
166
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
167
-        $table_name = 'esp_extra_meta';
168
-        $sql = "EXM_ID INT(11) NOT NULL AUTO_INCREMENT,
166
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
167
+		$table_name = 'esp_extra_meta';
168
+		$sql = "EXM_ID INT(11) NOT NULL AUTO_INCREMENT,
169 169
 				OBJ_ID INT(11) DEFAULT NULL,
170 170
 				EXM_type VARCHAR(45) DEFAULT NULL,
171 171
 				EXM_key VARCHAR(45) DEFAULT NULL,
172 172
 				EXM_value TEXT,
173 173
 				PRIMARY KEY  (EXM_ID)";
174
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
175
-        $table_name = 'esp_line_item';
176
-        $sql = "LIN_ID INT(11) NOT NULL AUTO_INCREMENT,
174
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
175
+		$table_name = 'esp_line_item';
176
+		$sql = "LIN_ID INT(11) NOT NULL AUTO_INCREMENT,
177 177
 				LIN_code VARCHAR(245) NOT NULL DEFAULT '',
178 178
 				TXN_ID INT(11) DEFAULT NULL,
179 179
 				LIN_name VARCHAR(245) NOT NULL DEFAULT '',
@@ -189,19 +189,19 @@  discard block
 block discarded – undo
189 189
 				OBJ_ID INT(11) DEFAULT NULL,
190 190
 				OBJ_type VARCHAR(45)DEFAULT NULL,
191 191
 				PRIMARY KEY  (LIN_ID)";
192
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
193
-        $table_name = 'esp_message_template';
194
-        $sql = "MTP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
192
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
193
+		$table_name = 'esp_message_template';
194
+		$sql = "MTP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
195 195
 					GRP_ID INT(10) UNSIGNED NOT NULL,
196 196
 					MTP_context VARCHAR(50) NOT NULL,
197 197
 					MTP_template_field VARCHAR(30) NOT NULL,
198 198
 					MTP_content TEXT NOT NULL,
199 199
 					PRIMARY KEY  (MTP_ID),
200 200
 					KEY GRP_ID (GRP_ID)";
201
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
202
-        $this->_get_table_manager()->dropIndex('esp_message_template_group', 'EVT_ID');
203
-        $table_name = 'esp_message_template_group';
204
-        $sql = "GRP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
201
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
202
+		$this->_get_table_manager()->dropIndex('esp_message_template_group', 'EVT_ID');
203
+		$table_name = 'esp_message_template_group';
204
+		$sql = "GRP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
205 205
 					MTP_user_id INT(10) NOT NULL DEFAULT '1',
206 206
 					MTP_name VARCHAR(245) NOT NULL DEFAULT '',
207 207
 					MTP_description VARCHAR(245) NOT NULL DEFAULT '',
@@ -213,17 +213,17 @@  discard block
 block discarded – undo
213 213
 					MTP_is_active TINYINT(1) NOT NULL DEFAULT '1',
214 214
 					PRIMARY KEY  (GRP_ID),
215 215
 					KEY MTP_user_id (MTP_user_id)";
216
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
217
-        $table_name = 'esp_event_message_template';
218
-        $sql = "EMT_ID BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
216
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
217
+		$table_name = 'esp_event_message_template';
218
+		$sql = "EMT_ID BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
219 219
 					EVT_ID BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
220 220
 					GRP_ID INT(10) UNSIGNED NOT NULL DEFAULT 0,
221 221
 					PRIMARY KEY  (EMT_ID),
222 222
 					KEY EVT_ID (EVT_ID),
223 223
 					KEY GRP_ID (GRP_ID)";
224
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
225
-        $table_name = 'esp_payment';
226
-        $sql = "PAY_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
224
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
225
+		$table_name = 'esp_payment';
226
+		$sql = "PAY_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
227 227
 					TXN_ID INT(10) UNSIGNED DEFAULT NULL,
228 228
 					STS_ID VARCHAR(3) COLLATE utf8_bin DEFAULT NULL,
229 229
 					PAY_timestamp DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
@@ -239,9 +239,9 @@  discard block
 block discarded – undo
239 239
 					PRIMARY KEY  (PAY_ID),
240 240
 					KEY TXN_ID (TXN_ID),
241 241
 					KEY PAY_timestamp (PAY_timestamp)";
242
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB ');
243
-        $table_name = "esp_ticket";
244
-        $sql = "TKT_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
242
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB ');
243
+		$table_name = "esp_ticket";
244
+		$sql = "TKT_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
245 245
 					  TTM_ID INT(10) UNSIGNED NOT NULL,
246 246
 					  TKT_name VARCHAR(245) NOT NULL DEFAULT '',
247 247
 					  TKT_description TEXT NOT NULL,
@@ -261,28 +261,28 @@  discard block
 block discarded – undo
261 261
 					  TKT_parent INT(10) UNSIGNED DEFAULT '0',
262 262
 					  TKT_deleted TINYINT(1) NOT NULL DEFAULT '0',
263 263
 					  PRIMARY KEY  (TKT_ID)";
264
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
265
-        $table_name = "esp_ticket_price";
266
-        $sql = "TKP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
264
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
265
+		$table_name = "esp_ticket_price";
266
+		$sql = "TKP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
267 267
 					  TKT_ID INT(10) UNSIGNED NOT NULL,
268 268
 					  PRC_ID INT(10) UNSIGNED NOT NULL,
269 269
 					  PRIMARY KEY  (TKP_ID)";
270
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
271
-        $table_name = "esp_datetime_ticket";
272
-        $sql = "DTK_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
270
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
271
+		$table_name = "esp_datetime_ticket";
272
+		$sql = "DTK_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
273 273
 					  DTT_ID INT(10) UNSIGNED NOT NULL,
274 274
 					  TKT_ID INT(10) UNSIGNED NOT NULL,
275 275
 					  PRIMARY KEY  (DTK_ID)";
276
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
277
-        $table_name = "esp_ticket_template";
278
-        $sql = "TTM_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
276
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
277
+		$table_name = "esp_ticket_template";
278
+		$sql = "TTM_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
279 279
 					  TTM_name VARCHAR(45) NOT NULL,
280 280
 					  TTM_description TEXT,
281 281
 					  TTM_file VARCHAR(45),
282 282
 					  PRIMARY KEY  (TTM_ID)";
283
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
284
-        $table_name = "esp_price";
285
-        $sql = "PRC_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
283
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
284
+		$table_name = "esp_price";
285
+		$sql = "PRC_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
286 286
 					  PRT_ID TINYINT(3) UNSIGNED NOT NULL,
287 287
 					  PRC_amount DECIMAL(10,3) NOT NULL DEFAULT '0.00',
288 288
 					  PRC_name VARCHAR(245) NOT NULL,
@@ -293,9 +293,9 @@  discard block
 block discarded – undo
293 293
 					  PRC_order TINYINT(3) UNSIGNED NOT NULL DEFAULT '0',
294 294
 					  PRC_parent INT(10) UNSIGNED DEFAULT 0,
295 295
 					  PRIMARY KEY  (PRC_ID)";
296
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
297
-        $table_name = "esp_price_type";
298
-        $sql = "PRT_ID TINYINT(3) UNSIGNED NOT NULL AUTO_INCREMENT,
296
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
297
+		$table_name = "esp_price_type";
298
+		$sql = "PRT_ID TINYINT(3) UNSIGNED NOT NULL AUTO_INCREMENT,
299 299
 				  PRT_name VARCHAR(45) NOT NULL,
300 300
 				  PBT_ID TINYINT(3) UNSIGNED NOT NULL DEFAULT '1',
301 301
 				  PRT_is_percent TINYINT(1) NOT NULL DEFAULT '0',
@@ -303,9 +303,9 @@  discard block
 block discarded – undo
303 303
 				  PRT_deleted TINYINT(1) NOT NULL DEFAULT '0',
304 304
 				  UNIQUE KEY PRT_name_UNIQUE (PRT_name),
305 305
 				  PRIMARY KEY  (PRT_ID)";
306
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
307
-        $table_name = 'esp_question';
308
-        $sql = 'QST_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
306
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
307
+		$table_name = 'esp_question';
308
+		$sql = 'QST_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
309 309
 					QST_display_text TEXT NOT NULL,
310 310
 					QST_admin_label VARCHAR(255) NOT NULL,
311 311
 					QST_system VARCHAR(25) DEFAULT NULL,
@@ -317,10 +317,10 @@  discard block
 block discarded – undo
317 317
 					QST_wp_user BIGINT UNSIGNED NULL,
318 318
 					QST_deleted TINYINT UNSIGNED NOT NULL DEFAULT 0,
319 319
 					PRIMARY KEY  (QST_ID)';
320
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
321
-        $this->_get_table_manager()->dropIndex('esp_question_group', 'QSG_identifier_UNIQUE');
322
-        $table_name = 'esp_question_group';
323
-        $sql = 'QSG_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
320
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
321
+		$this->_get_table_manager()->dropIndex('esp_question_group', 'QSG_identifier_UNIQUE');
322
+		$table_name = 'esp_question_group';
323
+		$sql = 'QSG_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
324 324
 					QSG_name VARCHAR(255) NOT NULL,
325 325
 					QSG_identifier VARCHAR(100) NOT NULL,
326 326
 					QSG_desc TEXT NULL,
@@ -331,25 +331,25 @@  discard block
 block discarded – undo
331 331
 					QSG_deleted TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
332 332
 					PRIMARY KEY  (QSG_ID),
333 333
 					UNIQUE KEY QSG_identifier_UNIQUE (QSG_identifier ASC)';
334
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
335
-        $table_name = 'esp_question_group_question';
336
-        $sql = "QGQ_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
334
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
335
+		$table_name = 'esp_question_group_question';
336
+		$sql = "QGQ_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
337 337
 					QSG_ID INT UNSIGNED NOT NULL,
338 338
 					QST_ID INT UNSIGNED NOT NULL,
339 339
 					QGQ_order INT UNSIGNED NOT NULL DEFAULT 0,
340 340
 					PRIMARY KEY  (QGQ_ID) ";
341
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
342
-        $table_name = 'esp_question_option';
343
-        $sql = "QSO_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
341
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
342
+		$table_name = 'esp_question_option';
343
+		$sql = "QSO_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
344 344
 					QSO_value VARCHAR(255) NOT NULL,
345 345
 					QSO_desc TEXT NOT NULL,
346 346
 					QST_ID INT UNSIGNED NOT NULL,
347 347
 					QSO_order INT UNSIGNED NOT NULL DEFAULT 0,
348 348
 					QSO_deleted TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
349 349
 					PRIMARY KEY  (QSO_ID)";
350
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
351
-        $table_name = 'esp_registration';
352
-        $sql = "REG_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
350
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
351
+		$table_name = 'esp_registration';
352
+		$sql = "REG_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
353 353
 					  EVT_ID BIGINT(20) UNSIGNED NOT NULL,
354 354
 					  ATT_ID BIGINT(20) UNSIGNED NOT NULL,
355 355
 					  TXN_ID INT(10) UNSIGNED NOT NULL,
@@ -372,25 +372,25 @@  discard block
 block discarded – undo
372 372
 					  KEY STS_ID (STS_ID),
373 373
 					  KEY REG_url_link (REG_url_link),
374 374
 					  KEY REG_code (REG_code)";
375
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB ');
376
-        $table_name = 'esp_checkin';
377
-        $sql = "CHK_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
375
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB ');
376
+		$table_name = 'esp_checkin';
377
+		$sql = "CHK_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
378 378
 					REG_ID INT(10) UNSIGNED NOT NULL,
379 379
 					DTT_ID INT(10) UNSIGNED NOT NULL,
380 380
 					CHK_in TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
381 381
 					CHK_timestamp DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
382 382
 					PRIMARY KEY  (CHK_ID)";
383
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
384
-        $table_name = 'esp_state';
385
-        $sql = "STA_ID smallint(5) UNSIGNED NOT NULL AUTO_INCREMENT,
383
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
384
+		$table_name = 'esp_state';
385
+		$sql = "STA_ID smallint(5) UNSIGNED NOT NULL AUTO_INCREMENT,
386 386
 					  CNT_ISO VARCHAR(2) COLLATE utf8_bin NOT NULL,
387 387
 					  STA_abbrev VARCHAR(6) COLLATE utf8_bin NOT NULL,
388 388
 					  STA_name VARCHAR(100) COLLATE utf8_bin NOT NULL,
389 389
 					  STA_active TINYINT(1) DEFAULT '1',
390 390
 					  PRIMARY KEY  (STA_ID)";
391
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
392
-        $table_name = 'esp_status';
393
-        $sql = "STS_ID VARCHAR(3) COLLATE utf8_bin NOT NULL,
391
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
392
+		$table_name = 'esp_status';
393
+		$sql = "STS_ID VARCHAR(3) COLLATE utf8_bin NOT NULL,
394 394
 					  STS_code VARCHAR(45) COLLATE utf8_bin NOT NULL,
395 395
 					  STS_type set('event','registration','transaction','payment','email') COLLATE utf8_bin NOT NULL,
396 396
 					  STS_can_edit TINYINT(1) NOT NULL DEFAULT 0,
@@ -398,9 +398,9 @@  discard block
 block discarded – undo
398 398
 					  STS_open TINYINT(1) NOT NULL DEFAULT 1,
399 399
 					  UNIQUE KEY STS_ID_UNIQUE (STS_ID),
400 400
 					  KEY STS_type (STS_type)";
401
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
402
-        $table_name = 'esp_transaction';
403
-        $sql = "TXN_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
401
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
402
+		$table_name = 'esp_transaction';
403
+		$sql = "TXN_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
404 404
 					  TXN_timestamp DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
405 405
 					  TXN_total DECIMAL(10,3) DEFAULT '0.00',
406 406
 					  TXN_paid DECIMAL(10,3) NOT NULL DEFAULT '0.00',
@@ -410,9 +410,9 @@  discard block
 block discarded – undo
410 410
 					  PRIMARY KEY  (TXN_ID),
411 411
 					  KEY TXN_timestamp (TXN_timestamp),
412 412
 					  KEY STS_ID (STS_ID)";
413
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
414
-        $table_name = 'esp_venue_meta';
415
-        $sql = "VNUM_ID INT(11) NOT NULL AUTO_INCREMENT,
413
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
414
+		$table_name = 'esp_venue_meta';
415
+		$sql = "VNUM_ID INT(11) NOT NULL AUTO_INCREMENT,
416 416
 			VNU_ID BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
417 417
 			VNU_address VARCHAR(255) DEFAULT NULL,
418 418
 			VNU_address2 VARCHAR(255) DEFAULT NULL,
@@ -430,79 +430,79 @@  discard block
 block discarded – undo
430 430
 			PRIMARY KEY  (VNUM_ID),
431 431
 			KEY STA_ID (STA_ID),
432 432
 			KEY CNT_ISO (CNT_ISO)";
433
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
434
-        $script_with_defaults = EE_Registry::instance()->load_dms('Core_4_1_0');
435
-        //setting up the DEFAULT stats and countries is also essential for the data migrations to run
436
-        //(because many need to convert old string states to foreign keys into the states table)
437
-        $script_with_defaults->insert_default_states();
438
-        $script_with_defaults->insert_default_countries();
439
-        //setting up DEFAULT prices, price types, and tickets is also essential for the price migrations
440
-        $script_with_defaults->insert_default_price_types();
441
-        $script_with_defaults->insert_default_prices();
442
-        //but the schema on the tickets table has changed since 4.1, so use our DEFAULT ticket method instead of 4.1's
443
-        $this->insert_default_tickets();
444
-        //setting up the config wp option pretty well counts as a 'schema change', or at least should happen ehre
445
-        EE_Config::instance()->update_espresso_config(false, true);
446
-        return true;
447
-    }
448
-
449
-
450
-
451
-    /**
452
-     * @return boolean
453
-     */
454
-    public function schema_changes_after_migration()
455
-    {
456
-        return true;
457
-    }
458
-
459
-
460
-
461
-    public function migration_page_hooks()
462
-    {
463
-    }
464
-
465
-
466
-
467
-    /**
468
-     * insert DEFAULT ticket
469
-     * Almost identical to EE_DMS_Core_4_1_0::insert_default_tickets, except is aware of the TKT_required field
470
-     *
471
-     * @access public
472
-     * @static
473
-     * @return void
474
-     */
475
-    public function insert_default_tickets()
476
-    {
477
-        global $wpdb;
478
-        $ticket_table = $wpdb->prefix . "esp_ticket";
479
-        if ($this->_get_table_analysis()->tableExists($ticket_table)) {
480
-            $SQL = 'SELECT COUNT(TKT_ID) FROM ' . $ticket_table;
481
-            $tickets_exist = $wpdb->get_var($SQL);
482
-            if ( ! $tickets_exist) {
483
-                $SQL = "INSERT INTO $ticket_table
433
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
434
+		$script_with_defaults = EE_Registry::instance()->load_dms('Core_4_1_0');
435
+		//setting up the DEFAULT stats and countries is also essential for the data migrations to run
436
+		//(because many need to convert old string states to foreign keys into the states table)
437
+		$script_with_defaults->insert_default_states();
438
+		$script_with_defaults->insert_default_countries();
439
+		//setting up DEFAULT prices, price types, and tickets is also essential for the price migrations
440
+		$script_with_defaults->insert_default_price_types();
441
+		$script_with_defaults->insert_default_prices();
442
+		//but the schema on the tickets table has changed since 4.1, so use our DEFAULT ticket method instead of 4.1's
443
+		$this->insert_default_tickets();
444
+		//setting up the config wp option pretty well counts as a 'schema change', or at least should happen ehre
445
+		EE_Config::instance()->update_espresso_config(false, true);
446
+		return true;
447
+	}
448
+
449
+
450
+
451
+	/**
452
+	 * @return boolean
453
+	 */
454
+	public function schema_changes_after_migration()
455
+	{
456
+		return true;
457
+	}
458
+
459
+
460
+
461
+	public function migration_page_hooks()
462
+	{
463
+	}
464
+
465
+
466
+
467
+	/**
468
+	 * insert DEFAULT ticket
469
+	 * Almost identical to EE_DMS_Core_4_1_0::insert_default_tickets, except is aware of the TKT_required field
470
+	 *
471
+	 * @access public
472
+	 * @static
473
+	 * @return void
474
+	 */
475
+	public function insert_default_tickets()
476
+	{
477
+		global $wpdb;
478
+		$ticket_table = $wpdb->prefix . "esp_ticket";
479
+		if ($this->_get_table_analysis()->tableExists($ticket_table)) {
480
+			$SQL = 'SELECT COUNT(TKT_ID) FROM ' . $ticket_table;
481
+			$tickets_exist = $wpdb->get_var($SQL);
482
+			if ( ! $tickets_exist) {
483
+				$SQL = "INSERT INTO $ticket_table
484 484
 					( TKT_ID, TTM_ID, TKT_name, TKT_description, TKT_qty, TKT_sold, TKT_uses, TKT_required, 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
485 485
 					( 1, 0, '"
486
-                       . __("Free Ticket", "event_espresso")
487
-                       . "', '', 100, 0, -1, 0, 0, -1, 0.00, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0, 0, 1, 1, 0, 0);";
488
-                $SQL = apply_filters('FHEE__EE_DMS_4_1_0__insert_default_tickets__SQL', $SQL);
489
-                $wpdb->query($SQL);
490
-            }
491
-        }
492
-        $ticket_price_table = $wpdb->prefix . "esp_ticket_price";
493
-        if ($this->_get_table_analysis()->tableExists($ticket_price_table)) {
494
-            $SQL = 'SELECT COUNT(TKP_ID) FROM ' . $ticket_price_table;
495
-            $ticket_prc_exist = $wpdb->get_var($SQL);
496
-            if ( ! $ticket_prc_exist) {
497
-                $SQL = "INSERT INTO $ticket_price_table
486
+					   . __("Free Ticket", "event_espresso")
487
+					   . "', '', 100, 0, -1, 0, 0, -1, 0.00, '0000-00-00 00:00:00', '0000-00-00 00:00:00', 0, 0, 1, 1, 0, 0);";
488
+				$SQL = apply_filters('FHEE__EE_DMS_4_1_0__insert_default_tickets__SQL', $SQL);
489
+				$wpdb->query($SQL);
490
+			}
491
+		}
492
+		$ticket_price_table = $wpdb->prefix . "esp_ticket_price";
493
+		if ($this->_get_table_analysis()->tableExists($ticket_price_table)) {
494
+			$SQL = 'SELECT COUNT(TKP_ID) FROM ' . $ticket_price_table;
495
+			$ticket_prc_exist = $wpdb->get_var($SQL);
496
+			if ( ! $ticket_prc_exist) {
497
+				$SQL = "INSERT INTO $ticket_price_table
498 498
 				( TKP_ID, TKT_ID, PRC_ID ) VALUES
499 499
 				( 1, 1, 1 )
500 500
 				";
501
-                $SQL = apply_filters('FHEE__EE_DMS_4_1_0__insert_default_tickets__SQL__ticket_price', $SQL);
502
-                $wpdb->query($SQL);
503
-            }
504
-        }
505
-    }
501
+				$SQL = apply_filters('FHEE__EE_DMS_4_1_0__insert_default_tickets__SQL__ticket_price', $SQL);
502
+				$wpdb->query($SQL);
503
+			}
504
+		}
505
+	}
506 506
 
507 507
 }
508 508
 
Please login to merge, or discard this patch.
core/data_migration_scripts/EE_DMS_Core_4_8_0.dms.php 1 patch
Indentation   +355 added lines, -355 removed lines patch added patch discarded remove patch
@@ -17,9 +17,9 @@  discard block
 block discarded – undo
17 17
 $stages = glob(EE_CORE . 'data_migration_scripts/4_8_0_stages/*');
18 18
 $class_to_filepath = array();
19 19
 foreach ($stages as $filepath) {
20
-    $matches = array();
21
-    preg_match('~4_8_0_stages/(.*).dmsstage.php~', $filepath, $matches);
22
-    $class_to_filepath[$matches[1]] = $filepath;
20
+	$matches = array();
21
+	preg_match('~4_8_0_stages/(.*).dmsstage.php~', $filepath, $matches);
22
+	$class_to_filepath[$matches[1]] = $filepath;
23 23
 }
24 24
 //give addons a chance to autoload their stages too
25 25
 $class_to_filepath = apply_filters('FHEE__EE_DMS_4_8_0__autoloaded_stages', $class_to_filepath);
@@ -38,71 +38,71 @@  discard block
 block discarded – undo
38 38
 class EE_DMS_Core_4_8_0 extends EE_Data_Migration_Script_Base
39 39
 {
40 40
 
41
-    /**
42
-     * return EE_DMS_Core_4_8_0
43
-     *
44
-     * @param TableManager  $table_manager
45
-     * @param TableAnalysis $table_analysis
46
-     */
47
-    public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
48
-    {
49
-        $this->_pretty_name = esc_html__("Data Update to Event Espresso 4.8.0", "event_espresso");
50
-        $this->_priority = 10;
51
-        $this->_migration_stages = array(
52
-            new EE_DMS_4_8_0_pretax_totals(),
53
-            new EE_DMS_4_8_0_event_subtotals(),
54
-        );
55
-        parent::__construct($table_manager, $table_analysis);
56
-    }
41
+	/**
42
+	 * return EE_DMS_Core_4_8_0
43
+	 *
44
+	 * @param TableManager  $table_manager
45
+	 * @param TableAnalysis $table_analysis
46
+	 */
47
+	public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
48
+	{
49
+		$this->_pretty_name = esc_html__("Data Update to Event Espresso 4.8.0", "event_espresso");
50
+		$this->_priority = 10;
51
+		$this->_migration_stages = array(
52
+			new EE_DMS_4_8_0_pretax_totals(),
53
+			new EE_DMS_4_8_0_event_subtotals(),
54
+		);
55
+		parent::__construct($table_manager, $table_analysis);
56
+	}
57 57
 
58 58
 
59 59
 
60
-    /**
61
-     * Because this is being done at basically the same time as the MER-ready branch
62
-     * of core, it's possible people might have installed MEr-ready branch first,
63
-     * and then this one, in which case we still want to perform this migration,
64
-     * even though the version might not have increased
65
-     *
66
-     * @param array $version_array
67
-     * @return bool
68
-     */
69
-    public function can_migrate_from_version($version_array)
70
-    {
71
-        $version_string = $version_array['Core'];
72
-        if (version_compare($version_string, '4.8.0', '<=') && version_compare($version_string, '4.7.0', '>=')) {
60
+	/**
61
+	 * Because this is being done at basically the same time as the MER-ready branch
62
+	 * of core, it's possible people might have installed MEr-ready branch first,
63
+	 * and then this one, in which case we still want to perform this migration,
64
+	 * even though the version might not have increased
65
+	 *
66
+	 * @param array $version_array
67
+	 * @return bool
68
+	 */
69
+	public function can_migrate_from_version($version_array)
70
+	{
71
+		$version_string = $version_array['Core'];
72
+		if (version_compare($version_string, '4.8.0', '<=') && version_compare($version_string, '4.7.0', '>=')) {
73 73
 //			echo "$version_string can be migrated from";
74
-            return true;
75
-        } elseif ( ! $version_string) {
74
+			return true;
75
+		} elseif ( ! $version_string) {
76 76
 //			echo "no version string provided: $version_string";
77
-            //no version string provided... this must be pre 4.3
78
-            return false;//changed mind. dont want people thinking they should migrate yet because they cant
79
-        } else {
77
+			//no version string provided... this must be pre 4.3
78
+			return false;//changed mind. dont want people thinking they should migrate yet because they cant
79
+		} else {
80 80
 //			echo "$version_string doesnt apply";
81
-            return false;
82
-        }
83
-    }
81
+			return false;
82
+		}
83
+	}
84 84
 
85 85
 
86 86
 
87
-    /**
88
-     * @return bool
89
-     */
90
-    public function schema_changes_before_migration()
91
-    {
92
-        require_once(EE_HELPERS . 'EEH_Activation.helper.php');
93
-        $now_in_mysql = current_time('mysql', true);
94
-        require_once(EE_HELPERS . 'EEH_Activation.helper.php');
95
-        $table_name = 'esp_answer';
96
-        $sql = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
87
+	/**
88
+	 * @return bool
89
+	 */
90
+	public function schema_changes_before_migration()
91
+	{
92
+		require_once(EE_HELPERS . 'EEH_Activation.helper.php');
93
+		$now_in_mysql = current_time('mysql', true);
94
+		require_once(EE_HELPERS . 'EEH_Activation.helper.php');
95
+		$table_name = 'esp_answer';
96
+		$sql = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
97 97
 					REG_ID int(10) unsigned NOT NULL,
98 98
 					QST_ID int(10) unsigned NOT NULL,
99 99
 					ANS_value text NOT NULL,
100 100
 					PRIMARY KEY  (ANS_ID),
101 101
 					KEY REG_ID (REG_ID),
102 102
 					KEY QST_ID (QST_ID)";
103
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
104
-        $table_name = 'esp_attendee_meta';
105
-        $sql = "ATTM_ID int(10) unsigned NOT	NULL AUTO_INCREMENT,
103
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
104
+		$table_name = 'esp_attendee_meta';
105
+		$sql = "ATTM_ID int(10) unsigned NOT	NULL AUTO_INCREMENT,
106 106
 						ATT_ID bigint(20) unsigned NOT NULL,
107 107
 						ATT_fname varchar(45) NOT NULL,
108 108
 						ATT_lname varchar(45) NOT	NULL,
@@ -119,9 +119,9 @@  discard block
 block discarded – undo
119 119
 								KEY ATT_email (ATT_email),
120 120
 								KEY ATT_lname (ATT_lname),
121 121
 								KEY ATT_fname (ATT_fname)";
122
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
123
-        $table_name = 'esp_country';
124
-        $sql = "CNT_ISO varchar(2) collate utf8_bin NOT NULL,
122
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
123
+		$table_name = 'esp_country';
124
+		$sql = "CNT_ISO varchar(2) collate utf8_bin NOT NULL,
125 125
 					  CNT_ISO3 varchar(3) collate utf8_bin NOT NULL,
126 126
 					  RGN_ID tinyint(3) unsigned DEFAULT NULL,
127 127
 					  CNT_name varchar(45) collate utf8_bin NOT NULL,
@@ -137,25 +137,25 @@  discard block
 block discarded – undo
137 137
 					  CNT_is_EU tinyint(1) DEFAULT '0',
138 138
 					  CNT_active tinyint(1) DEFAULT '0',
139 139
 					  PRIMARY KEY  (CNT_ISO)";
140
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
141
-        $table_name = 'esp_currency';
142
-        $sql = "CUR_code varchar(6) collate utf8_bin NOT NULL,
140
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
141
+		$table_name = 'esp_currency';
142
+		$sql = "CUR_code varchar(6) collate utf8_bin NOT NULL,
143 143
 				CUR_single varchar(45) collate utf8_bin DEFAULT 'dollar',
144 144
 				CUR_plural varchar(45) collate utf8_bin DEFAULT 'dollars',
145 145
 				CUR_sign varchar(45) collate utf8_bin DEFAULT '$',
146 146
 				CUR_dec_plc varchar(1) collate utf8_bin NOT NULL DEFAULT '2',
147 147
 				CUR_active tinyint(1) DEFAULT '0',
148 148
 				PRIMARY KEY  (CUR_code)";
149
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
150
-        $table_name = 'esp_currency_payment_method';
151
-        $sql = "CPM_ID int(11) NOT NULL AUTO_INCREMENT,
149
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
150
+		$table_name = 'esp_currency_payment_method';
151
+		$sql = "CPM_ID int(11) NOT NULL AUTO_INCREMENT,
152 152
 				CUR_code varchar(6) collate utf8_bin NOT NULL,
153 153
 				PMD_ID int(11) NOT NULL,
154 154
 				PRIMARY KEY  (CPM_ID),
155 155
 				KEY PMD_ID (PMD_ID)";
156
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
157
-        $table_name = 'esp_datetime';
158
-        $sql = "DTT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
156
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
157
+		$table_name = 'esp_datetime';
158
+		$sql = "DTT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
159 159
 				  EVT_ID bigint(20) unsigned NOT NULL,
160 160
 				  DTT_name varchar(255) NOT NULL DEFAULT '',
161 161
 				  DTT_description text NOT NULL,
@@ -171,9 +171,9 @@  discard block
 block discarded – undo
171 171
 						KEY DTT_EVT_start (DTT_EVT_start),
172 172
 						KEY EVT_ID (EVT_ID),
173 173
 						KEY DTT_is_primary (DTT_is_primary)";
174
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
175
-        $table_name = 'esp_event_meta';
176
-        $sql = "
174
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
175
+		$table_name = 'esp_event_meta';
176
+		$sql = "
177 177
 			EVTM_ID int(10) NOT NULL AUTO_INCREMENT,
178 178
 			EVT_ID bigint(20) unsigned NOT NULL,
179 179
 			EVT_display_desc tinyint(1) unsigned NOT NULL DEFAULT 1,
@@ -189,34 +189,34 @@  discard block
 block discarded – undo
189 189
 			EVT_donations tinyint(1) NULL,
190 190
 			PRIMARY KEY  (EVTM_ID),
191 191
 			KEY EVT_ID (EVT_ID)";
192
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
193
-        $table_name = 'esp_event_question_group';
194
-        $sql = "EQG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
192
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
193
+		$table_name = 'esp_event_question_group';
194
+		$sql = "EQG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
195 195
 					EVT_ID bigint(20) unsigned NOT NULL,
196 196
 					QSG_ID int(10) unsigned NOT NULL,
197 197
 					EQG_primary tinyint(1) unsigned NOT NULL DEFAULT 0,
198 198
 					PRIMARY KEY  (EQG_ID),
199 199
 					KEY EVT_ID (EVT_ID),
200 200
 					KEY QSG_ID (QSG_ID)";
201
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
202
-        $table_name = 'esp_event_venue';
203
-        $sql = "EVV_ID int(11) NOT NULL AUTO_INCREMENT,
201
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
202
+		$table_name = 'esp_event_venue';
203
+		$sql = "EVV_ID int(11) NOT NULL AUTO_INCREMENT,
204 204
 				EVT_ID bigint(20) unsigned NOT NULL,
205 205
 				VNU_ID bigint(20) unsigned NOT NULL,
206 206
 				EVV_primary tinyint(1) unsigned NOT NULL DEFAULT 0,
207 207
 				PRIMARY KEY  (EVV_ID)";
208
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
209
-        $table_name = 'esp_extra_meta';
210
-        $sql = "EXM_ID int(11) NOT NULL AUTO_INCREMENT,
208
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
209
+		$table_name = 'esp_extra_meta';
210
+		$sql = "EXM_ID int(11) NOT NULL AUTO_INCREMENT,
211 211
 				OBJ_ID int(11) DEFAULT NULL,
212 212
 				EXM_type varchar(45) DEFAULT NULL,
213 213
 				EXM_key varchar(45) DEFAULT NULL,
214 214
 				EXM_value text,
215 215
 				PRIMARY KEY  (EXM_ID),
216 216
 				KEY EXM_type (EXM_type,OBJ_ID,EXM_key)";
217
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
218
-        $table_name = 'esp_extra_join';
219
-        $sql = "EXJ_ID int(11) NOT NULL AUTO_INCREMENT,
217
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
218
+		$table_name = 'esp_extra_join';
219
+		$sql = "EXJ_ID int(11) NOT NULL AUTO_INCREMENT,
220 220
 				EXJ_first_model_id varchar(6) NOT NULL,
221 221
 				EXJ_first_model_name varchar(20) NOT NULL,
222 222
 				EXJ_second_model_id varchar(6) NOT NULL,
@@ -224,9 +224,9 @@  discard block
 block discarded – undo
224 224
 				PRIMARY KEY  (EXJ_ID),
225 225
 				KEY first_model (EXJ_first_model_name,EXJ_first_model_id),
226 226
 				KEY second_model (EXJ_second_model_name,EXJ_second_model_id)";
227
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
228
-        $table_name = 'esp_line_item';
229
-        $sql = "LIN_ID int(11) NOT NULL AUTO_INCREMENT,
227
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
228
+		$table_name = 'esp_line_item';
229
+		$sql = "LIN_ID int(11) NOT NULL AUTO_INCREMENT,
230 230
 				LIN_code varchar(245) NOT NULL DEFAULT '',
231 231
 				TXN_ID int(11) DEFAULT NULL,
232 232
 				LIN_name varchar(245) NOT NULL DEFAULT '',
@@ -245,9 +245,9 @@  discard block
 block discarded – undo
245 245
 				PRIMARY KEY  (LIN_ID),
246 246
 				KEY LIN_code (LIN_code(191)),
247 247
 				KEY TXN_ID (TXN_ID)";
248
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
249
-        $table_name = 'esp_log';
250
-        $sql = "LOG_ID int(11) NOT NULL AUTO_INCREMENT,
248
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
249
+		$table_name = 'esp_log';
250
+		$sql = "LOG_ID int(11) NOT NULL AUTO_INCREMENT,
251 251
 				LOG_time datetime DEFAULT NULL,
252 252
 				OBJ_ID varchar(45) DEFAULT NULL,
253 253
 				OBJ_type varchar(45) DEFAULT NULL,
@@ -258,18 +258,18 @@  discard block
 block discarded – undo
258 258
 				KEY LOG_time (LOG_time),
259 259
 				KEY OBJ (OBJ_type,OBJ_ID),
260 260
 				KEY LOG_type (LOG_type)";
261
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
262
-        $table_name = 'esp_message_template';
263
-        $sql = "MTP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
261
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
262
+		$table_name = 'esp_message_template';
263
+		$sql = "MTP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
264 264
 					GRP_ID int(10) unsigned NOT NULL,
265 265
 					MTP_context varchar(50) NOT NULL,
266 266
 					MTP_template_field varchar(30) NOT NULL,
267 267
 					MTP_content text NOT NULL,
268 268
 					PRIMARY KEY  (MTP_ID),
269 269
 					KEY GRP_ID (GRP_ID)";
270
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
271
-        $table_name = 'esp_message_template_group';
272
-        $sql = "GRP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
270
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
271
+		$table_name = 'esp_message_template_group';
272
+		$sql = "GRP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
273 273
 					MTP_user_id int(10) NOT NULL DEFAULT '1',
274 274
 					MTP_name varchar(245) NOT NULL DEFAULT '',
275 275
 					MTP_description varchar(245) NOT NULL DEFAULT '',
@@ -281,17 +281,17 @@  discard block
 block discarded – undo
281 281
 					MTP_is_active tinyint(1) NOT NULL DEFAULT '1',
282 282
 					PRIMARY KEY  (GRP_ID),
283 283
 					KEY MTP_user_id (MTP_user_id)";
284
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
285
-        $table_name = 'esp_event_message_template';
286
-        $sql = "EMT_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
284
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
285
+		$table_name = 'esp_event_message_template';
286
+		$sql = "EMT_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
287 287
 					EVT_ID bigint(20) unsigned NOT NULL DEFAULT 0,
288 288
 					GRP_ID int(10) unsigned NOT NULL DEFAULT 0,
289 289
 					PRIMARY KEY  (EMT_ID),
290 290
 					KEY EVT_ID (EVT_ID),
291 291
 					KEY GRP_ID (GRP_ID)";
292
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
293
-        $table_name = 'esp_payment';
294
-        $sql = "PAY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
292
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
293
+		$table_name = 'esp_payment';
294
+		$sql = "PAY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
295 295
 					TXN_ID int(10) unsigned DEFAULT NULL,
296 296
 					STS_ID varchar(3) collate utf8_bin DEFAULT NULL,
297 297
 					PAY_timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
@@ -308,9 +308,9 @@  discard block
 block discarded – undo
308 308
 					PRIMARY KEY  (PAY_ID),
309 309
 					KEY PAY_timestamp (PAY_timestamp),
310 310
 					KEY TXN_ID (TXN_ID)";
311
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
312
-        $table_name = 'esp_payment_method';
313
-        $sql = "PMD_ID int(11) NOT NULL AUTO_INCREMENT,
311
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
312
+		$table_name = 'esp_payment_method';
313
+		$sql = "PMD_ID int(11) NOT NULL AUTO_INCREMENT,
314 314
 				PMD_type varchar(124) DEFAULT NULL,
315 315
 				PMD_name varchar(255) DEFAULT NULL,
316 316
 				PMD_desc text,
@@ -326,32 +326,32 @@  discard block
 block discarded – undo
326 326
 				PRIMARY KEY  (PMD_ID),
327 327
 				UNIQUE KEY PMD_slug_UNIQUE (PMD_slug),
328 328
 				KEY PMD_type (PMD_type)";
329
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
330
-        $table_name = "esp_ticket_price";
331
-        $sql = "TKP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
329
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
330
+		$table_name = "esp_ticket_price";
331
+		$sql = "TKP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
332 332
 					  TKT_ID int(10) unsigned NOT NULL,
333 333
 					  PRC_ID int(10) unsigned NOT NULL,
334 334
 					  PRIMARY KEY  (TKP_ID),
335 335
 					  KEY TKT_ID (TKT_ID),
336 336
 					  KEY PRC_ID (PRC_ID)";
337
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
338
-        $table_name = "esp_datetime_ticket";
339
-        $sql = "DTK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
337
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
338
+		$table_name = "esp_datetime_ticket";
339
+		$sql = "DTK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
340 340
 					  DTT_ID int(10) unsigned NOT NULL,
341 341
 					  TKT_ID int(10) unsigned NOT NULL,
342 342
 					  PRIMARY KEY  (DTK_ID),
343 343
 					  KEY DTT_ID (DTT_ID),
344 344
 					  KEY TKT_ID (TKT_ID)";
345
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
346
-        $table_name = "esp_ticket_template";
347
-        $sql = "TTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
345
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
346
+		$table_name = "esp_ticket_template";
347
+		$sql = "TTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
348 348
 					  TTM_name varchar(45) NOT NULL,
349 349
 					  TTM_description text,
350 350
 					  TTM_file varchar(45),
351 351
 					  PRIMARY KEY  (TTM_ID)";
352
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
353
-        $table_name = 'esp_question';
354
-        $sql = 'QST_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
352
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
353
+		$table_name = 'esp_question';
354
+		$sql = 'QST_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
355 355
 					QST_display_text text NOT NULL,
356 356
 					QST_admin_label varchar(255) NOT NULL,
357 357
 					QST_system varchar(25) NOT NULL DEFAULT "",
@@ -365,18 +365,18 @@  discard block
 block discarded – undo
365 365
 					QST_deleted tinyint(2) unsigned NOT NULL DEFAULT 0,
366 366
 					PRIMARY KEY  (QST_ID),
367 367
 					KEY QST_order (QST_order)';
368
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
369
-        $table_name = 'esp_question_group_question';
370
-        $sql = "QGQ_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
368
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
369
+		$table_name = 'esp_question_group_question';
370
+		$sql = "QGQ_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
371 371
 					QSG_ID int(10) unsigned NOT NULL,
372 372
 					QST_ID int(10) unsigned NOT NULL,
373 373
 					QGQ_order int(10) unsigned NOT NULL DEFAULT 0,
374 374
 					PRIMARY KEY  (QGQ_ID),
375 375
 					KEY QST_ID (QST_ID),
376 376
 					KEY QSG_ID_order (QSG_ID,QGQ_order)";
377
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
378
-        $table_name = 'esp_question_option';
379
-        $sql = "QSO_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
377
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
378
+		$table_name = 'esp_question_option';
379
+		$sql = "QSO_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
380 380
 					QSO_value varchar(255) NOT NULL,
381 381
 					QSO_desc text NOT NULL,
382 382
 					QST_ID int(10) unsigned NOT NULL,
@@ -386,9 +386,9 @@  discard block
 block discarded – undo
386 386
 					PRIMARY KEY  (QSO_ID),
387 387
 					KEY QST_ID (QST_ID),
388 388
 					KEY QSO_order (QSO_order)";
389
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
390
-        $table_name = 'esp_registration';
391
-        $sql = "REG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
389
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
390
+		$table_name = 'esp_registration';
391
+		$sql = "REG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
392 392
 					  EVT_ID bigint(20) unsigned NOT NULL,
393 393
 					  ATT_ID bigint(20) unsigned NOT NULL,
394 394
 					  TXN_ID int(10) unsigned NOT NULL,
@@ -412,18 +412,18 @@  discard block
 block discarded – undo
412 412
 					  KEY TKT_ID (TKT_ID),
413 413
 					  KEY EVT_ID (EVT_ID),
414 414
 					  KEY STS_ID (STS_ID)";
415
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
416
-        $table_name = 'esp_registration_payment';
417
-        $sql = "RPY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
415
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
416
+		$table_name = 'esp_registration_payment';
417
+		$sql = "RPY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
418 418
 					  REG_ID int(10) unsigned NOT NULL,
419 419
 					  PAY_ID int(10) unsigned NULL,
420 420
 					  RPY_amount decimal(10,3) NOT NULL DEFAULT '0.00',
421 421
 					  PRIMARY KEY  (RPY_ID),
422 422
 					  KEY REG_ID (REG_ID),
423 423
 					  KEY PAY_ID (PAY_ID)";
424
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
425
-        $table_name = 'esp_checkin';
426
-        $sql = "CHK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
424
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
425
+		$table_name = 'esp_checkin';
426
+		$sql = "CHK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
427 427
 					REG_ID int(10) unsigned NOT NULL,
428 428
 					DTT_ID int(10) unsigned NOT NULL,
429 429
 					CHK_in tinyint(1) unsigned NOT NULL DEFAULT 1,
@@ -431,9 +431,9 @@  discard block
 block discarded – undo
431 431
 					PRIMARY KEY  (CHK_ID),
432 432
 					KEY REG_ID (REG_ID),
433 433
 					KEY DTT_ID (DTT_ID)";
434
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
435
-        $table_name = 'esp_state';
436
-        $sql = "STA_ID smallint(5) unsigned NOT NULL AUTO_INCREMENT,
434
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
435
+		$table_name = 'esp_state';
436
+		$sql = "STA_ID smallint(5) unsigned NOT NULL AUTO_INCREMENT,
437 437
 					  CNT_ISO varchar(2) collate utf8_bin NOT NULL,
438 438
 					  STA_abbrev varchar(24) collate utf8_bin NOT NULL,
439 439
 					  STA_name varchar(100) collate utf8_bin NOT NULL,
@@ -441,9 +441,9 @@  discard block
 block discarded – undo
441 441
 					  PRIMARY KEY  (STA_ID),
442 442
 					  KEY STA_abbrev (STA_abbrev),
443 443
 					  KEY CNT_ISO (CNT_ISO)";
444
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
445
-        $table_name = 'esp_status';
446
-        $sql = "STS_ID varchar(3) NOT NULL,
444
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
445
+		$table_name = 'esp_status';
446
+		$sql = "STS_ID varchar(3) NOT NULL,
447 447
 					  STS_code varchar(45) NOT NULL,
448 448
 					  STS_type varchar(45) NOT NULL,
449 449
 					  STS_can_edit tinyint(1) NOT NULL DEFAULT 0,
@@ -451,9 +451,9 @@  discard block
 block discarded – undo
451 451
 					  STS_open tinyint(1) NOT NULL DEFAULT 1,
452 452
 					  UNIQUE KEY STS_ID_UNIQUE (STS_ID),
453 453
 					  KEY STS_type (STS_type)";
454
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
455
-        $table_name = 'esp_transaction';
456
-        $sql = "TXN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
454
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
455
+		$table_name = 'esp_transaction';
456
+		$sql = "TXN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
457 457
 					  TXN_timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
458 458
 					  TXN_total decimal(10,3) DEFAULT '0.00',
459 459
 					  TXN_paid decimal(10,3) NOT NULL DEFAULT '0.00',
@@ -465,9 +465,9 @@  discard block
 block discarded – undo
465 465
 					  PRIMARY KEY  (TXN_ID),
466 466
 					  KEY TXN_timestamp (TXN_timestamp),
467 467
 					  KEY STS_ID (STS_ID)";
468
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
469
-        $table_name = 'esp_venue_meta';
470
-        $sql = "VNUM_ID int(11) NOT NULL AUTO_INCREMENT,
468
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
469
+		$table_name = 'esp_venue_meta';
470
+		$sql = "VNUM_ID int(11) NOT NULL AUTO_INCREMENT,
471 471
 			VNU_ID bigint(20) unsigned NOT NULL DEFAULT 0,
472 472
 			VNU_address varchar(255) DEFAULT NULL,
473 473
 			VNU_address2 varchar(255) DEFAULT NULL,
@@ -486,10 +486,10 @@  discard block
 block discarded – undo
486 486
 			KEY VNU_ID (VNU_ID),
487 487
 			KEY STA_ID (STA_ID),
488 488
 			KEY CNT_ISO (CNT_ISO)";
489
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
490
-        //modified tables
491
-        $table_name = "esp_price";
492
-        $sql = "PRC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
489
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
490
+		//modified tables
491
+		$table_name = "esp_price";
492
+		$sql = "PRC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
493 493
 					  PRT_ID tinyint(3) unsigned NOT NULL,
494 494
 					  PRC_amount decimal(10,3) NOT NULL DEFAULT '0.00',
495 495
 					  PRC_name varchar(245) NOT NULL,
@@ -502,9 +502,9 @@  discard block
 block discarded – undo
502 502
 					  PRC_parent int(10) unsigned DEFAULT 0,
503 503
 					  PRIMARY KEY  (PRC_ID),
504 504
 					  KEY PRT_ID (PRT_ID)";
505
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
506
-        $table_name = "esp_price_type";
507
-        $sql = "PRT_ID tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
505
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
506
+		$table_name = "esp_price_type";
507
+		$sql = "PRT_ID tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
508 508
 				  PRT_name varchar(45) NOT NULL,
509 509
 				  PBT_ID tinyint(3) unsigned NOT NULL DEFAULT '1',
510 510
 				  PRT_is_percent tinyint(1) NOT NULL DEFAULT '0',
@@ -513,9 +513,9 @@  discard block
 block discarded – undo
513 513
 				  PRT_deleted tinyint(1) NOT NULL DEFAULT '0',
514 514
 				  UNIQUE KEY PRT_name_UNIQUE (PRT_name),
515 515
 				  PRIMARY KEY  (PRT_ID)";
516
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
517
-        $table_name = "esp_ticket";
518
-        $sql = "TKT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
516
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
517
+		$table_name = "esp_ticket";
518
+		$sql = "TKT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
519 519
 					  TTM_ID int(10) unsigned NOT NULL,
520 520
 					  TKT_name varchar(245) NOT NULL DEFAULT '',
521 521
 					  TKT_description text NOT NULL,
@@ -537,9 +537,9 @@  discard block
 block discarded – undo
537 537
 					  TKT_deleted tinyint(1) NOT NULL DEFAULT '0',
538 538
 					  PRIMARY KEY  (TKT_ID),
539 539
 					  KEY TKT_start_date (TKT_start_date)";
540
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
541
-        $table_name = 'esp_question_group';
542
-        $sql = 'QSG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
540
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
541
+		$table_name = 'esp_question_group';
542
+		$sql = 'QSG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
543 543
 					QSG_name varchar(255) NOT NULL,
544 544
 					QSG_identifier varchar(100) NOT NULL,
545 545
 					QSG_desc text NULL,
@@ -552,221 +552,221 @@  discard block
 block discarded – undo
552 552
 					PRIMARY KEY  (QSG_ID),
553 553
 					UNIQUE KEY QSG_identifier_UNIQUE (QSG_identifier),
554 554
 					KEY QSG_order (QSG_order)';
555
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
556
-        /** @var EE_DMS_Core_4_1_0 $script_4_1_defaults */
557
-        $script_4_1_defaults = EE_Registry::instance()->load_dms('Core_4_1_0');
558
-        //(because many need to convert old string states to foreign keys into the states table)
559
-        $script_4_1_defaults->insert_default_states();
560
-        $script_4_1_defaults->insert_default_countries();
561
-        /** @var EE_DMS_Core_4_5_0 $script_4_5_defaults */
562
-        $script_4_5_defaults = EE_Registry::instance()->load_dms('Core_4_5_0');
563
-        $script_4_5_defaults->insert_default_price_types();
564
-        $script_4_5_defaults->insert_default_prices();
565
-        $script_4_5_defaults->insert_default_tickets();
566
-        /** @var EE_DMS_Core_4_6_0 $script_4_6_defaults */
567
-        $script_4_6_defaults = EE_Registry::instance()->load_dms('Core_4_6_0');
568
-        $script_4_6_defaults->add_default_admin_only_payments();
569
-        $script_4_6_defaults->insert_default_currencies();
570
-        $this->verify_new_countries();
571
-        $this->verify_new_currencies();
572
-        return true;
573
-    }
555
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
556
+		/** @var EE_DMS_Core_4_1_0 $script_4_1_defaults */
557
+		$script_4_1_defaults = EE_Registry::instance()->load_dms('Core_4_1_0');
558
+		//(because many need to convert old string states to foreign keys into the states table)
559
+		$script_4_1_defaults->insert_default_states();
560
+		$script_4_1_defaults->insert_default_countries();
561
+		/** @var EE_DMS_Core_4_5_0 $script_4_5_defaults */
562
+		$script_4_5_defaults = EE_Registry::instance()->load_dms('Core_4_5_0');
563
+		$script_4_5_defaults->insert_default_price_types();
564
+		$script_4_5_defaults->insert_default_prices();
565
+		$script_4_5_defaults->insert_default_tickets();
566
+		/** @var EE_DMS_Core_4_6_0 $script_4_6_defaults */
567
+		$script_4_6_defaults = EE_Registry::instance()->load_dms('Core_4_6_0');
568
+		$script_4_6_defaults->add_default_admin_only_payments();
569
+		$script_4_6_defaults->insert_default_currencies();
570
+		$this->verify_new_countries();
571
+		$this->verify_new_currencies();
572
+		return true;
573
+	}
574 574
 
575 575
 
576 576
 
577
-    /**
578
-     * @return boolean
579
-     */
580
-    public function schema_changes_after_migration()
581
-    {
582
-        $this->fix_non_default_taxes();
583
-        //this is actually the same as the last DMS
584
-        /** @var EE_DMS_Core_4_7_0 $script_4_7_defaults */
585
-        $script_4_7_defaults = EE_Registry::instance()->load_dms('Core_4_7_0');
586
-        return $script_4_7_defaults->schema_changes_after_migration();
587
-    }
577
+	/**
578
+	 * @return boolean
579
+	 */
580
+	public function schema_changes_after_migration()
581
+	{
582
+		$this->fix_non_default_taxes();
583
+		//this is actually the same as the last DMS
584
+		/** @var EE_DMS_Core_4_7_0 $script_4_7_defaults */
585
+		$script_4_7_defaults = EE_Registry::instance()->load_dms('Core_4_7_0');
586
+		return $script_4_7_defaults->schema_changes_after_migration();
587
+	}
588 588
 
589 589
 
590 590
 
591
-    public function migration_page_hooks()
592
-    {
593
-    }
591
+	public function migration_page_hooks()
592
+	{
593
+	}
594 594
 
595 595
 
596 596
 
597
-    /**
598
-     * verifies each of the new countries exists that somehow we missed in 4.1
599
-     */
600
-    public function verify_new_countries()
601
-    {
602
-        //a list of countries (and specifically some which were missed in another list):https://gist.github.com/adhipg/1600028
603
-        //how many decimal places? https://en.wikipedia.org/wiki/ISO_4217
604
-        //currency symbols: http://www.xe.com/symbols.php
605
-        //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
606
-        //('AD', 'AND', 0, 'Andorra', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+376', 0, 0),
607
-        $newer_countries = array(
608
-            array('AX', 'ALA', 0, '&#197;land Islands', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+358', 1, 0),
609
-            array('BL', 'BLM', 0, 'Saint Barthelemy', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+590', 1, 0),
610
-            array('CW', 'CUW', 0, 'Curacao', 'ANG', 'Guilder', 'Guilders', 'ƒ', 1, 2, '+599', 1, 0),
611
-            array('GG', 'GGY', 0, 'Guernsey', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+44', 0, 0),
612
-            array('IM', 'IMN', 0, 'Isle of Man', 'GBP', 'Pound', 'Pounds', '£', 1, 2, '+44', 0, 0),
613
-            array('JE', 'JEY', 0, 'Jersey', 'GBP', 'Pound', 'Pounds', '£', 1, 2, '+44', 0, 0),
614
-            array('MF', 'MAF', 0, 'Saint Martin', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+590', 1, 0),
615
-            array('ME', 'MNE', 0, 'Montenegro', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+382', 0, 0),
616
-            array('RS', 'SRB', 0, 'Serbia', 'RSD', 'Dinar', 'Dinars', '', 0, 2, '+381', 1, 0),
617
-            array('SS', 'SSD', 0, 'South Sudan', 'SSP', 'Pound', 'Pounds', '£', 1, 2, '+211', 0, 0),
618
-            array('SX', 'SXM', 0, 'Sint Maarten', 'ANG', 'Guilder', 'Guilders', 'ƒ', 1, 2, '+1', 1, 0),
619
-            array('XK', 'XKX', 0, 'Kosovo', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+383', 0, 0),
620
-            array('YT', 'MYT', 0, 'Mayotte', 'EUR', 'Euro', 'Euros', '€', 0, 2, '+262', 1, 0),
621
-            array(
622
-                'BQ',
623
-                'BES',
624
-                0,
625
-                'Bonaire, Saint Eustatius and Saba',
626
-                'USD',
627
-                'Dollar',
628
-                'Dollars',
629
-                '$',
630
-                1,
631
-                2,
632
-                '+599',
633
-                0,
634
-                0,
635
-            ),
636
-            array('BV', 'BVT', 0, 'Bouvet Island', 'NOK', 'Krone', 'Krones', 'kr', 1, 2, '+47', 0, 0),
637
-            array('IO', 'IOT', 0, 'British Indian Ocean Territory', 'GBP', 'Pound', 'Pounds', '£', 1, 2, '+246', 0, 0),
638
-            array('CX', 'CXR', 0, 'Christmas Island', 'AUD', 'Dollar', 'Dollars', '$', 1, 2, '+61', 0, 0),
639
-            array('CC', 'CCK', 0, 'Cocos (Keeling) Islands', 'AUD', 'Dollar', 'Dollars', '$', 1, 2, '+891', 0, 0),
640
-            array(
641
-                'HM',
642
-                'HMD',
643
-                0,
644
-                'Heard Island and McDonald Islands',
645
-                'AUD',
646
-                'Dollar',
647
-                'Dollars',
648
-                '$',
649
-                1,
650
-                2,
651
-                '+891',
652
-                0,
653
-                0,
654
-            ),
655
-            array('PS', 'PSE', 0, 'Palestinian Territory', 'ILS', 'Shekel', 'Shekels', '₪', 1, 2, '+970', 0, 0),
656
-            array(
657
-                'GS',
658
-                'SGS',
659
-                0,
660
-                'South Georgia and the South Sandwich Islands',
661
-                'GBP',
662
-                'Pound',
663
-                'Pounds',
664
-                '£',
665
-                1,
666
-                2,
667
-                '+500',
668
-                0,
669
-                0,
670
-            ),
671
-            array('TL', 'TLS', 0, 'Timor-Leste', 'USD', 'Dollar', 'Dollars', '$', 1, 2, '+670', 0, 0),
672
-            array('TF', 'ATF', 0, 'French Southern Territories', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+262', 0, 0),
673
-            array(
674
-                'UM',
675
-                'UMI',
676
-                0,
677
-                'United States Minor Outlying Islands',
678
-                'USD',
679
-                'Dollar',
680
-                'Dollars',
681
-                '$',
682
-                1,
683
-                2,
684
-                '+1',
685
-                0,
686
-                0,
687
-            ),
688
-        );
689
-        global $wpdb;
690
-        $country_table = $wpdb->prefix . "esp_country";
691
-        $country_format = array(
692
-            "CNT_ISO"         => '%s',
693
-            "CNT_ISO3"        => '%s',
694
-            "RGN_ID"          => '%d',
695
-            "CNT_name"        => '%s',
696
-            "CNT_cur_code"    => '%s',
697
-            "CNT_cur_single"  => '%s',
698
-            "CNT_cur_plural"  => '%s',
699
-            "CNT_cur_sign"    => '%s',
700
-            "CNT_cur_sign_b4" => '%d',
701
-            "CNT_cur_dec_plc" => '%d',
702
-            "CNT_tel_code"    => '%s',
703
-            "CNT_is_EU"       => '%d',
704
-            "CNT_active"      => '%d',
705
-        );
706
-        if ($this->_get_table_analysis()->tableExists($country_table)) {
707
-            foreach ($newer_countries as $country) {
708
-                $SQL = "SELECT COUNT('CNT_ISO') FROM {$country_table} WHERE CNT_ISO='{$country[0]}' LIMIT 1";
709
-                $countries = $wpdb->get_var($SQL);
710
-                if ( ! $countries) {
711
-                    $wpdb->insert($country_table,
712
-                        array_combine(array_keys($country_format), $country),
713
-                        $country_format
714
-                    );
715
-                }
716
-            }
717
-        }
718
-    }
597
+	/**
598
+	 * verifies each of the new countries exists that somehow we missed in 4.1
599
+	 */
600
+	public function verify_new_countries()
601
+	{
602
+		//a list of countries (and specifically some which were missed in another list):https://gist.github.com/adhipg/1600028
603
+		//how many decimal places? https://en.wikipedia.org/wiki/ISO_4217
604
+		//currency symbols: http://www.xe.com/symbols.php
605
+		//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
606
+		//('AD', 'AND', 0, 'Andorra', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+376', 0, 0),
607
+		$newer_countries = array(
608
+			array('AX', 'ALA', 0, '&#197;land Islands', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+358', 1, 0),
609
+			array('BL', 'BLM', 0, 'Saint Barthelemy', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+590', 1, 0),
610
+			array('CW', 'CUW', 0, 'Curacao', 'ANG', 'Guilder', 'Guilders', 'ƒ', 1, 2, '+599', 1, 0),
611
+			array('GG', 'GGY', 0, 'Guernsey', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+44', 0, 0),
612
+			array('IM', 'IMN', 0, 'Isle of Man', 'GBP', 'Pound', 'Pounds', '£', 1, 2, '+44', 0, 0),
613
+			array('JE', 'JEY', 0, 'Jersey', 'GBP', 'Pound', 'Pounds', '£', 1, 2, '+44', 0, 0),
614
+			array('MF', 'MAF', 0, 'Saint Martin', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+590', 1, 0),
615
+			array('ME', 'MNE', 0, 'Montenegro', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+382', 0, 0),
616
+			array('RS', 'SRB', 0, 'Serbia', 'RSD', 'Dinar', 'Dinars', '', 0, 2, '+381', 1, 0),
617
+			array('SS', 'SSD', 0, 'South Sudan', 'SSP', 'Pound', 'Pounds', '£', 1, 2, '+211', 0, 0),
618
+			array('SX', 'SXM', 0, 'Sint Maarten', 'ANG', 'Guilder', 'Guilders', 'ƒ', 1, 2, '+1', 1, 0),
619
+			array('XK', 'XKX', 0, 'Kosovo', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+383', 0, 0),
620
+			array('YT', 'MYT', 0, 'Mayotte', 'EUR', 'Euro', 'Euros', '€', 0, 2, '+262', 1, 0),
621
+			array(
622
+				'BQ',
623
+				'BES',
624
+				0,
625
+				'Bonaire, Saint Eustatius and Saba',
626
+				'USD',
627
+				'Dollar',
628
+				'Dollars',
629
+				'$',
630
+				1,
631
+				2,
632
+				'+599',
633
+				0,
634
+				0,
635
+			),
636
+			array('BV', 'BVT', 0, 'Bouvet Island', 'NOK', 'Krone', 'Krones', 'kr', 1, 2, '+47', 0, 0),
637
+			array('IO', 'IOT', 0, 'British Indian Ocean Territory', 'GBP', 'Pound', 'Pounds', '£', 1, 2, '+246', 0, 0),
638
+			array('CX', 'CXR', 0, 'Christmas Island', 'AUD', 'Dollar', 'Dollars', '$', 1, 2, '+61', 0, 0),
639
+			array('CC', 'CCK', 0, 'Cocos (Keeling) Islands', 'AUD', 'Dollar', 'Dollars', '$', 1, 2, '+891', 0, 0),
640
+			array(
641
+				'HM',
642
+				'HMD',
643
+				0,
644
+				'Heard Island and McDonald Islands',
645
+				'AUD',
646
+				'Dollar',
647
+				'Dollars',
648
+				'$',
649
+				1,
650
+				2,
651
+				'+891',
652
+				0,
653
+				0,
654
+			),
655
+			array('PS', 'PSE', 0, 'Palestinian Territory', 'ILS', 'Shekel', 'Shekels', '₪', 1, 2, '+970', 0, 0),
656
+			array(
657
+				'GS',
658
+				'SGS',
659
+				0,
660
+				'South Georgia and the South Sandwich Islands',
661
+				'GBP',
662
+				'Pound',
663
+				'Pounds',
664
+				'£',
665
+				1,
666
+				2,
667
+				'+500',
668
+				0,
669
+				0,
670
+			),
671
+			array('TL', 'TLS', 0, 'Timor-Leste', 'USD', 'Dollar', 'Dollars', '$', 1, 2, '+670', 0, 0),
672
+			array('TF', 'ATF', 0, 'French Southern Territories', 'EUR', 'Euro', 'Euros', '€', 1, 2, '+262', 0, 0),
673
+			array(
674
+				'UM',
675
+				'UMI',
676
+				0,
677
+				'United States Minor Outlying Islands',
678
+				'USD',
679
+				'Dollar',
680
+				'Dollars',
681
+				'$',
682
+				1,
683
+				2,
684
+				'+1',
685
+				0,
686
+				0,
687
+			),
688
+		);
689
+		global $wpdb;
690
+		$country_table = $wpdb->prefix . "esp_country";
691
+		$country_format = array(
692
+			"CNT_ISO"         => '%s',
693
+			"CNT_ISO3"        => '%s',
694
+			"RGN_ID"          => '%d',
695
+			"CNT_name"        => '%s',
696
+			"CNT_cur_code"    => '%s',
697
+			"CNT_cur_single"  => '%s',
698
+			"CNT_cur_plural"  => '%s',
699
+			"CNT_cur_sign"    => '%s',
700
+			"CNT_cur_sign_b4" => '%d',
701
+			"CNT_cur_dec_plc" => '%d',
702
+			"CNT_tel_code"    => '%s',
703
+			"CNT_is_EU"       => '%d',
704
+			"CNT_active"      => '%d',
705
+		);
706
+		if ($this->_get_table_analysis()->tableExists($country_table)) {
707
+			foreach ($newer_countries as $country) {
708
+				$SQL = "SELECT COUNT('CNT_ISO') FROM {$country_table} WHERE CNT_ISO='{$country[0]}' LIMIT 1";
709
+				$countries = $wpdb->get_var($SQL);
710
+				if ( ! $countries) {
711
+					$wpdb->insert($country_table,
712
+						array_combine(array_keys($country_format), $country),
713
+						$country_format
714
+					);
715
+				}
716
+			}
717
+		}
718
+	}
719 719
 
720 720
 
721 721
 
722
-    /**
723
-     * verifies each of the new currencies exists that somehow we missed in 4.6
724
-     */
725
-    public function verify_new_currencies()
726
-    {
727
-        //a list of countries (and specifically some which were missed in another list):https://gist.github.com/adhipg/1600028
728
-        //how many decimal places? https://en.wikipedia.org/wiki/ISO_4217
729
-        //currency symbols: http://www.xe.com/symbols.php
730
-        // CUR_code, CUR_single, CUR_plural, CUR_sign, CUR_dec_plc, CUR_active
731
-        //( 'EUR',  'Euro',  'Euros',  '€',  2,1),
732
-        $newer_currencies = array(
733
-            array('RSD', 'Dinar', 'Dinars', '', 3, 1),
734
-        );
735
-        global $wpdb;
736
-        $currency_table = $wpdb->prefix . "esp_currency";
737
-        $currency_format = array(
738
-            "CUR_code"    => '%s',
739
-            "CUR_single"  => '%s',
740
-            "CUR_plural"  => '%s',
741
-            "CUR_sign"    => '%s',
742
-            "CUR_dec_plc" => '%d',
743
-            "CUR_active"  => '%d',
744
-        );
745
-        if ($this->_get_table_analysis()->tableExists($currency_table)) {
746
-            foreach ($newer_currencies as $currency) {
747
-                $SQL = "SELECT COUNT('CUR_code') FROM {$currency_table} WHERE CUR_code='{$currency[0]}' LIMIT 1";
748
-                $countries = $wpdb->get_var($SQL);
749
-                if ( ! $countries) {
750
-                    $wpdb->insert($currency_table,
751
-                        array_combine(array_keys($currency_format), $currency),
752
-                        $currency_format
753
-                    );
754
-                }
755
-            }
756
-        }
757
-    }
722
+	/**
723
+	 * verifies each of the new currencies exists that somehow we missed in 4.6
724
+	 */
725
+	public function verify_new_currencies()
726
+	{
727
+		//a list of countries (and specifically some which were missed in another list):https://gist.github.com/adhipg/1600028
728
+		//how many decimal places? https://en.wikipedia.org/wiki/ISO_4217
729
+		//currency symbols: http://www.xe.com/symbols.php
730
+		// CUR_code, CUR_single, CUR_plural, CUR_sign, CUR_dec_plc, CUR_active
731
+		//( 'EUR',  'Euro',  'Euros',  '€',  2,1),
732
+		$newer_currencies = array(
733
+			array('RSD', 'Dinar', 'Dinars', '', 3, 1),
734
+		);
735
+		global $wpdb;
736
+		$currency_table = $wpdb->prefix . "esp_currency";
737
+		$currency_format = array(
738
+			"CUR_code"    => '%s',
739
+			"CUR_single"  => '%s',
740
+			"CUR_plural"  => '%s',
741
+			"CUR_sign"    => '%s',
742
+			"CUR_dec_plc" => '%d',
743
+			"CUR_active"  => '%d',
744
+		);
745
+		if ($this->_get_table_analysis()->tableExists($currency_table)) {
746
+			foreach ($newer_currencies as $currency) {
747
+				$SQL = "SELECT COUNT('CUR_code') FROM {$currency_table} WHERE CUR_code='{$currency[0]}' LIMIT 1";
748
+				$countries = $wpdb->get_var($SQL);
749
+				if ( ! $countries) {
750
+					$wpdb->insert($currency_table,
751
+						array_combine(array_keys($currency_format), $currency),
752
+						$currency_format
753
+					);
754
+				}
755
+			}
756
+		}
757
+	}
758 758
 
759 759
 
760 760
 
761
-    /**
762
-     * addresses https://events.codebasehq.com/projects/event-espresso/tickets/8731
763
-     * which should just be a temporary issue for folks who installed 4.8.0-4.8.5;
764
-     * we should be able to stop doing this in 4.9
765
-     */
766
-    public function fix_non_default_taxes()
767
-    {
768
-        global $wpdb;
769
-        $query = $wpdb->prepare("UPDATE
761
+	/**
762
+	 * addresses https://events.codebasehq.com/projects/event-espresso/tickets/8731
763
+	 * which should just be a temporary issue for folks who installed 4.8.0-4.8.5;
764
+	 * we should be able to stop doing this in 4.9
765
+	 */
766
+	public function fix_non_default_taxes()
767
+	{
768
+		global $wpdb;
769
+		$query = $wpdb->prepare("UPDATE
770 770
 				{$wpdb->prefix}esp_price p INNER JOIN
771 771
 				{$wpdb->prefix}esp_price_type pt ON p.PRT_ID = pt.PRT_ID
772 772
 			SET
@@ -775,6 +775,6 @@  discard block
 block discarded – undo
775 775
 				p.PRC_is_default = 0 AND
776 776
 				pt.PBT_ID = %d
777 777
 					", EEM_Price_Type::base_type_tax);
778
-        $wpdb->query($query);
779
-    }
778
+		$wpdb->query($query);
779
+	}
780 780
 }
Please login to merge, or discard this patch.
admin_pages/maintenance/templates/ee_data_reset_and_delete.template.php 1 patch
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -7,14 +7,14 @@  discard block
 block discarded – undo
7 7
 /** @var string $delete_db_url */
8 8
 ?>
9 9
 <h2>
10
-	<?php esc_html_e( 'Reset/Delete Data for Event Espresso', 'event_espresso' );?>
10
+	<?php esc_html_e('Reset/Delete Data for Event Espresso', 'event_espresso'); ?>
11 11
 </h2>
12 12
 <br />
13 13
 
14 14
 <!-- reset DB url is here. Just need to make it look pretty and unhide it-->
15 15
 <div class="padding">
16
-	<h4 class="espresso-header"><span class="dashicons dashicons-update ee-icon-size-22"></span><?php esc_html_e('Reset Event Espresso Capabilities', 'event_espresso');?></h4>
17
-	<p><?php esc_html_e('Use this to reset the capabilities on WP roles to the defaults as defined via EE_Capabilities.  Note this reset does not REMOVE any existing capabilities, it just ensures that all the defaults are ADDED to the roles.', 'event_espresso');?></p>
16
+	<h4 class="espresso-header"><span class="dashicons dashicons-update ee-icon-size-22"></span><?php esc_html_e('Reset Event Espresso Capabilities', 'event_espresso'); ?></h4>
17
+	<p><?php esc_html_e('Use this to reset the capabilities on WP roles to the defaults as defined via EE_Capabilities.  Note this reset does not REMOVE any existing capabilities, it just ensures that all the defaults are ADDED to the roles.', 'event_espresso'); ?></p>
18 18
 	<div class="float-right"><?php echo $reset_capabilities_button; ?></div>
19 19
 	<div class="clear"></div>
20 20
 </div>
@@ -22,24 +22,24 @@  discard block
 block discarded – undo
22 22
 <br />
23 23
 
24 24
 <div class="padding">
25
-	<h4 class="espresso-header"><span class="dashicons dashicons-update ee-icon-size-22"></span><?php esc_html_e('Reset Event Espresso Tables', 'event_espresso');?></h4>
26
-	<p><?php esc_html_e('Use this to reset Event Espresso Data and return your site to how it was just after first activating Event Espresso.', 'event_espresso');?></p>
27
-	<div class="float-right"><a class="button button-primary" href="<?php echo $reset_db_url;?>"><?php esc_html_e('Reset Event Espresso Tables', 'event_espresso');?></a></div>
25
+	<h4 class="espresso-header"><span class="dashicons dashicons-update ee-icon-size-22"></span><?php esc_html_e('Reset Event Espresso Tables', 'event_espresso'); ?></h4>
26
+	<p><?php esc_html_e('Use this to reset Event Espresso Data and return your site to how it was just after first activating Event Espresso.', 'event_espresso'); ?></p>
27
+	<div class="float-right"><a class="button button-primary" href="<?php echo $reset_db_url; ?>"><?php esc_html_e('Reset Event Espresso Tables', 'event_espresso'); ?></a></div>
28 28
 	<div class="clear"></div>
29 29
 </div>
30 30
 <br />
31 31
 <br />
32 32
 
33 33
 <div class="padding">
34
-	<h4 class="espresso-header"><span class="dashicons dashicons-post-trash ee-icon-size-22"></span><?php esc_html_e('Permanently Delete ALL Event Espresso Tables and Data', 'event_espresso');?></h4>
35
-	<p><?php esc_html_e('If you know for certain that you will no longer be using Event Espresso and you wish to remove ALL traces of the plugin from your system, then perform the following steps.', 'event_espresso');?></p>
36
-	<p class="important-notice"><?php printf( esc_html__('Please note: %sThis is permanent and can NOT be undone.%s', 'event_espresso'), '<strong>', '</strong>' ); ?><br/></p>
34
+	<h4 class="espresso-header"><span class="dashicons dashicons-post-trash ee-icon-size-22"></span><?php esc_html_e('Permanently Delete ALL Event Espresso Tables and Data', 'event_espresso'); ?></h4>
35
+	<p><?php esc_html_e('If you know for certain that you will no longer be using Event Espresso and you wish to remove ALL traces of the plugin from your system, then perform the following steps.', 'event_espresso'); ?></p>
36
+	<p class="important-notice"><?php printf(esc_html__('Please note: %sThis is permanent and can NOT be undone.%s', 'event_espresso'), '<strong>', '</strong>'); ?><br/></p>
37 37
 	<ol>
38
-		<li><?php  printf( esc_html__('First, click the button below to permanently delete all Event Espresso tables, records, and options from your WordPress database . If you receive a "500 Internal Server Error" or a blank white screen, it means the server has timed out due to the large number of records being updated. This is not a cause for concern. Simply %1$srefresh the page%2$s and the Database Update will continue where it left off.', 'event_espresso'), '<strong>', '</strong>' );?></li>
39
-		<li><?php printf( esc_html__('Then, locate Event Espresso on the WordPress Plugins page, and click on %sDelete%s', 'event_espresso'), '<strong>', '</strong>' ); ?></li>
40
-        <li><?php printf( esc_html__('Once you are on the Delete Plugin page, click on %sYes, Delete these files and data%s', 'event_espresso'), '<strong>', '</strong>' ); ?></li>
38
+		<li><?php  printf(esc_html__('First, click the button below to permanently delete all Event Espresso tables, records, and options from your WordPress database . If you receive a "500 Internal Server Error" or a blank white screen, it means the server has timed out due to the large number of records being updated. This is not a cause for concern. Simply %1$srefresh the page%2$s and the Database Update will continue where it left off.', 'event_espresso'), '<strong>', '</strong>'); ?></li>
39
+		<li><?php printf(esc_html__('Then, locate Event Espresso on the WordPress Plugins page, and click on %sDelete%s', 'event_espresso'), '<strong>', '</strong>'); ?></li>
40
+        <li><?php printf(esc_html__('Once you are on the Delete Plugin page, click on %sYes, Delete these files and data%s', 'event_espresso'), '<strong>', '</strong>'); ?></li>
41 41
 	</ol>
42
-	<div class="float-right"><a href="<?php echo $delete_db_url; ?>" id="delete-all-data-btn" class="button-primary"><?php esc_html_e('Permanently Delete All Event Espresso Data', 'event_espresso');?></a></div>
42
+	<div class="float-right"><a href="<?php echo $delete_db_url; ?>" id="delete-all-data-btn" class="button-primary"><?php esc_html_e('Permanently Delete All Event Espresso Data', 'event_espresso'); ?></a></div>
43 43
 	<div class="clear"></div>
44 44
 </div>
45 45
 <br/>
Please login to merge, or discard this patch.
core/EE_Cron_Tasks.core.php 2 patches
Indentation   +358 added lines, -358 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
 /**
@@ -12,363 +12,363 @@  discard block
 block discarded – undo
12 12
 class EE_Cron_Tasks extends EE_Base
13 13
 {
14 14
 
15
-    /**
16
-     * WordPress doesn't allow duplicate crons within 10 minutes of the original,
17
-     * so we'll set our retry time for just over 10 minutes to avoid that
18
-     */
19
-    const reschedule_timeout = 605;
20
-
21
-
22
-    /**
23
-     * @var EE_Cron_Tasks
24
-     */
25
-    private static $_instance;
26
-
27
-
28
-    /**
29
-     * @return EE_Cron_Tasks
30
-     */
31
-    public static function instance()
32
-    {
33
-        if ( ! self::$_instance instanceof EE_Cron_Tasks) {
34
-            self::$_instance = new self();
35
-        }
36
-        return self::$_instance;
37
-    }
38
-
39
-
40
-    /**
41
-     * @access private
42
-     * @return EE_Cron_Tasks
43
-     */
44
-    private function __construct()
45
-    {
46
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
47
-        // verify that WP Cron is enabled
48
-        if (
49
-            defined('DISABLE_WP_CRON')
50
-            && DISABLE_WP_CRON
51
-            && is_admin()
52
-            && ! get_option('ee_disabled_wp_cron_check')
53
-        ) {
54
-            /**
55
-             * This needs to be delayed until after the config is loaded because EE_Cron_Tasks is constructed before
56
-             * config is loaded.
57
-             * This is intentionally using a anonymous function so that its not easily de-registered.  Client code
58
-             * wanting to not have this functionality can just register its own action at a priority after this one to
59
-             * reverse any changes.
60
-             */
61
-            add_action('AHEE__EE_System__load_core_configuration__complete', function () {
62
-                EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request = true;
63
-                EE_Registry::instance()->NET_CFG->update_config(true, false);
64
-                add_option('ee_disabled_wp_cron_check', 1, '', false);
65
-            });
66
-        }
67
-        // UPDATE TRANSACTION WITH PAYMENT
68
-        add_action(
69
-            'AHEE__EE_Cron_Tasks__update_transaction_with_payment_2',
70
-            array('EE_Cron_Tasks', 'setup_update_for_transaction_with_payment'),
71
-            10, 2
72
-        );
73
-        // FINALIZE ABANDONED TRANSACTIONS
74
-        add_action(
75
-            'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
76
-            array('EE_Cron_Tasks', 'check_for_abandoned_transactions'),
77
-            10, 1
78
-        );
79
-        // CLEAN OUT JUNK TRANSACTIONS AND RELATED DATA
80
-        add_action(
81
-            'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
82
-            array('EE_Cron_Tasks', 'clean_out_junk_transactions')
83
-        );
84
-        // logging
85
-        add_action(
86
-            'AHEE__EE_System__load_core_configuration__complete',
87
-            array('EE_Cron_Tasks', 'log_scheduled_ee_crons')
88
-        );
89
-        EE_Registry::instance()->load_lib('Messages_Scheduler');
90
-    }
91
-
92
-
93
-    /**
94
-     * @access protected
95
-     * @return void
96
-     */
97
-    public static function log_scheduled_ee_crons()
98
-    {
99
-        $ee_crons = array(
100
-            'AHEE__EE_Cron_Tasks__update_transaction_with_payment',
101
-            'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
102
-            'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
103
-        );
104
-        $crons    = get_option('cron');
105
-        if ( ! is_array($crons)) {
106
-            return;
107
-        }
108
-        foreach ($crons as $timestamp => $cron) {
109
-            foreach ($ee_crons as $ee_cron) {
110
-                if (isset($cron[$ee_cron])) {
111
-                    do_action('AHEE_log', __CLASS__, __FUNCTION__, $ee_cron, 'scheduled EE cron');
112
-                    foreach ($cron[$ee_cron] as $ee_cron_details) {
113
-                        if ( ! empty($ee_cron_details['args'])) {
114
-                            do_action('AHEE_log', __CLASS__, __FUNCTION__, print_r($ee_cron_details['args'], true),
115
-                                "$ee_cron args");
116
-                        }
117
-                    }
118
-                }
119
-            }
120
-        }
121
-    }
122
-
123
-
124
-
125
-
126
-    /****************  UPDATE TRANSACTION WITH PAYMENT ****************/
127
-
128
-
129
-    /**
130
-     * array of TXN IDs and the payment
131
-     *
132
-     * @var array
133
-     */
134
-    protected static $_update_transactions_with_payment = array();
135
-
136
-
137
-    /**
138
-     * schedule_update_transaction_with_payment
139
-     * sets a wp_schedule_single_event() for updating any TXNs that may
140
-     * require updating due to recently received payments
141
-     *
142
-     * @param int $timestamp
143
-     * @param int $TXN_ID
144
-     * @param int $PAY_ID
145
-     */
146
-    public static function schedule_update_transaction_with_payment(
147
-        $timestamp,
148
-        $TXN_ID,
149
-        $PAY_ID
150
-    ) {
151
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
152
-        // validate $TXN_ID and $timestamp
153
-        $TXN_ID    = absint($TXN_ID);
154
-        $timestamp = absint($timestamp);
155
-        if ($TXN_ID && $timestamp) {
156
-            wp_schedule_single_event(
157
-                $timestamp,
158
-                'AHEE__EE_Cron_Tasks__update_transaction_with_payment_2',
159
-                array($TXN_ID, $PAY_ID)
160
-            );
161
-        }
162
-    }
163
-
164
-
165
-    /**
166
-     * setup_update_for_transaction_with_payment
167
-     * this is the callback for the action hook:
168
-     * 'AHEE__EE_Cron_Tasks__update_transaction_with_payment'
169
-     * which is setup by EE_Cron_Tasks::schedule_update_transaction_with_payment().
170
-     * The passed TXN_ID and associated payment gets added to an array, and then
171
-     * the EE_Cron_Tasks::update_transaction_with_payment() function is hooked into
172
-     * 'shutdown' which will actually handle the processing of any
173
-     * transactions requiring updating, because doing so now would be too early
174
-     * and the required resources may not be available
175
-     *
176
-     * @param int $TXN_ID
177
-     * @param int $PAY_ID
178
-     */
179
-    public static function setup_update_for_transaction_with_payment($TXN_ID = 0, $PAY_ID = 0)
180
-    {
181
-        do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
182
-        if (absint($TXN_ID)) {
183
-            self::$_update_transactions_with_payment[$TXN_ID] = $PAY_ID;
184
-            add_action(
185
-                'shutdown',
186
-                array('EE_Cron_Tasks', 'update_transaction_with_payment'),
187
-                5
188
-            );
189
-        }
190
-    }
191
-
192
-
193
-    /**
194
-     * update_transaction_with_payment
195
-     * loops through the self::$_abandoned_transactions array
196
-     * and attempts to finalize any TXNs that have not been completed
197
-     * but have had their sessions expired, most likely due to a user not
198
-     * returning from an off-site payment gateway
199
-     *
200
-     * @throws \EE_Error
201
-     */
202
-    public static function update_transaction_with_payment()
203
-    {
204
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
205
-        // are there any TXNs that need cleaning up ?
206
-        if ( ! empty(self::$_update_transactions_with_payment)) {
207
-            /** @type EE_Payment_Processor $payment_processor */
208
-            $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
209
-            // set revisit flag for payment processor
210
-            $payment_processor->set_revisit(false);
211
-            // load EEM_Transaction
212
-            EE_Registry::instance()->load_model('Transaction');
213
-            foreach (self::$_update_transactions_with_payment as $TXN_ID => $PAY_ID) {
214
-                // reschedule the cron if we can't hit the db right now
215
-                if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
216
-                    // reset cron job for updating the TXN
217
-                    EE_Cron_Tasks::schedule_update_transaction_with_payment(
218
-                        time() + EE_Cron_Tasks::reschedule_timeout,
219
-                        $TXN_ID,
220
-                        $PAY_ID
221
-                    );
222
-                    continue;
223
-                }
224
-                $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
225
-                $payment     = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
226
-                // verify transaction
227
-                if ($transaction instanceof EE_Transaction && $payment instanceof EE_Payment) {
228
-                    // now try to update the TXN with any payments
229
-                    $payment_processor->update_txn_based_on_payment($transaction, $payment, true, true);
230
-                }
231
-                unset(self::$_update_transactions_with_payment[$TXN_ID]);
232
-            }
233
-        }
234
-    }
235
-
236
-
237
-
238
-    /************  END OF UPDATE TRANSACTION WITH PAYMENT  ************/
239
-
240
-
241
-    /*****************  FINALIZE ABANDONED TRANSACTIONS *****************/
242
-
243
-
244
-    /**
245
-     * array of TXN IDs
246
-     *
247
-     * @var array
248
-     */
249
-    protected static $_abandoned_transactions = array();
250
-
251
-
252
-    /**
253
-     * schedule_finalize_abandoned_transactions_check
254
-     * sets a wp_schedule_single_event() for finalizing any TXNs that may
255
-     * have been abandoned during the registration process
256
-     *
257
-     * @param int $timestamp
258
-     * @param int $TXN_ID
259
-     */
260
-    public static function schedule_finalize_abandoned_transactions_check(
261
-        $timestamp,
262
-        $TXN_ID
263
-    ) {
264
-        // validate $TXN_ID and $timestamp
265
-        $TXN_ID    = absint($TXN_ID);
266
-        $timestamp = absint($timestamp);
267
-        do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
268
-        if ($TXN_ID && $timestamp) {
269
-            wp_schedule_single_event(
270
-                $timestamp,
271
-                'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
272
-                array($TXN_ID)
273
-            );
274
-        }
275
-    }
276
-
277
-
278
-    /**
279
-     * check_for_abandoned_transactions
280
-     * this is the callback for the action hook:
281
-     * 'AHEE__EE_Cron_Tasks__espresso_finalize_abandoned_transactions'
282
-     * which is utilized by wp_schedule_single_event()
283
-     * in EE_SPCO_Reg_Step_Payment_Options::_post_payment_processing().
284
-     * The passed TXN_ID gets added to an array, and then the
285
-     * espresso_finalize_abandoned_transactions() function is hooked into
286
-     * 'AHEE__EE_System__core_loaded_and_ready' which will actually handle the
287
-     * processing of any abandoned transactions, because doing so now would be
288
-     * too early and the required resources may not be available
289
-     *
290
-     * @param int $TXN_ID
291
-     */
292
-    public static function check_for_abandoned_transactions($TXN_ID = 0)
293
-    {
294
-        do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
295
-        if (absint($TXN_ID)) {
296
-            self::$_abandoned_transactions[] = $TXN_ID;
297
-            add_action(
298
-                'shutdown',
299
-                array('EE_Cron_Tasks', 'finalize_abandoned_transactions'),
300
-                5
301
-            );
302
-        }
303
-    }
304
-
305
-
306
-    /**
307
-     * finalize_abandoned_transactions
308
-     * loops through the self::$_abandoned_transactions array
309
-     * and attempts to finalize any TXNs that have not been completed
310
-     * but have had their sessions expired, most likely due to a user not
311
-     * returning from an off-site payment gateway
312
-     *
313
-     * @throws \EE_Error
314
-     */
315
-    public static function finalize_abandoned_transactions()
316
-    {
317
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
318
-        // are there any TXNs that need cleaning up ?
319
-        if ( ! empty(self::$_abandoned_transactions)) {
320
-            /** @type EE_Transaction_Processor $transaction_processor */
321
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
322
-            // set revisit flag for txn processor
323
-            $transaction_processor->set_revisit(false);
324
-            /** @type EE_Payment_Processor $payment_processor */
325
-            $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
326
-            // load EEM_Transaction
327
-            EE_Registry::instance()->load_model('Transaction');
328
-            foreach (self::$_abandoned_transactions as $TXN_ID) {
329
-                do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
330
-                // reschedule the cron if we can't hit the db right now
331
-                if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
332
-                    // reset cron job for finalizing the TXN
333
-                    EE_Cron_Tasks::schedule_finalize_abandoned_transactions_check(
334
-                        time() + EE_Cron_Tasks::reschedule_timeout,
335
-                        $TXN_ID
336
-                    );
337
-                    continue;
338
-                }
339
-                $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
340
-                // verify transaction
341
-                if ($transaction instanceof EE_Transaction) {
342
-                    // don't finalize the TXN if it has already been completed
343
-                    if ($transaction->all_reg_steps_completed() === true) {
344
-                        continue;
345
-                    }
346
-                    // let's simulate an IPN here which will trigger any notifications that need to go out
347
-                    $payment_processor->update_txn_based_on_payment($transaction, $transaction->last_payment(), true,
348
-                        true);
349
-                }
350
-                unset(self::$_abandoned_transactions[$TXN_ID]);
351
-            }
352
-        }
353
-    }
354
-
355
-
356
-
357
-    /*************  END OF FINALIZE ABANDONED TRANSACTIONS  *************/
358
-
359
-
360
-    /************* START CLEAN UP BOT TRANSACTIONS **********************/
361
-
362
-    //when a transaction is initially made, schedule this check.
363
-    //if it has NO REG data by the time it has expired, forget about it
364
-    public static function clean_out_junk_transactions()
365
-    {
366
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
367
-            EEM_Transaction::instance('')->delete_junk_transactions();
368
-            EEM_Registration::instance('')->delete_registrations_with_no_transaction();
369
-            EEM_Line_Item::instance('')->delete_line_items_with_no_transaction();
370
-        }
371
-    }
15
+	/**
16
+	 * WordPress doesn't allow duplicate crons within 10 minutes of the original,
17
+	 * so we'll set our retry time for just over 10 minutes to avoid that
18
+	 */
19
+	const reschedule_timeout = 605;
20
+
21
+
22
+	/**
23
+	 * @var EE_Cron_Tasks
24
+	 */
25
+	private static $_instance;
26
+
27
+
28
+	/**
29
+	 * @return EE_Cron_Tasks
30
+	 */
31
+	public static function instance()
32
+	{
33
+		if ( ! self::$_instance instanceof EE_Cron_Tasks) {
34
+			self::$_instance = new self();
35
+		}
36
+		return self::$_instance;
37
+	}
38
+
39
+
40
+	/**
41
+	 * @access private
42
+	 * @return EE_Cron_Tasks
43
+	 */
44
+	private function __construct()
45
+	{
46
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
47
+		// verify that WP Cron is enabled
48
+		if (
49
+			defined('DISABLE_WP_CRON')
50
+			&& DISABLE_WP_CRON
51
+			&& is_admin()
52
+			&& ! get_option('ee_disabled_wp_cron_check')
53
+		) {
54
+			/**
55
+			 * This needs to be delayed until after the config is loaded because EE_Cron_Tasks is constructed before
56
+			 * config is loaded.
57
+			 * This is intentionally using a anonymous function so that its not easily de-registered.  Client code
58
+			 * wanting to not have this functionality can just register its own action at a priority after this one to
59
+			 * reverse any changes.
60
+			 */
61
+			add_action('AHEE__EE_System__load_core_configuration__complete', function () {
62
+				EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request = true;
63
+				EE_Registry::instance()->NET_CFG->update_config(true, false);
64
+				add_option('ee_disabled_wp_cron_check', 1, '', false);
65
+			});
66
+		}
67
+		// UPDATE TRANSACTION WITH PAYMENT
68
+		add_action(
69
+			'AHEE__EE_Cron_Tasks__update_transaction_with_payment_2',
70
+			array('EE_Cron_Tasks', 'setup_update_for_transaction_with_payment'),
71
+			10, 2
72
+		);
73
+		// FINALIZE ABANDONED TRANSACTIONS
74
+		add_action(
75
+			'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
76
+			array('EE_Cron_Tasks', 'check_for_abandoned_transactions'),
77
+			10, 1
78
+		);
79
+		// CLEAN OUT JUNK TRANSACTIONS AND RELATED DATA
80
+		add_action(
81
+			'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
82
+			array('EE_Cron_Tasks', 'clean_out_junk_transactions')
83
+		);
84
+		// logging
85
+		add_action(
86
+			'AHEE__EE_System__load_core_configuration__complete',
87
+			array('EE_Cron_Tasks', 'log_scheduled_ee_crons')
88
+		);
89
+		EE_Registry::instance()->load_lib('Messages_Scheduler');
90
+	}
91
+
92
+
93
+	/**
94
+	 * @access protected
95
+	 * @return void
96
+	 */
97
+	public static function log_scheduled_ee_crons()
98
+	{
99
+		$ee_crons = array(
100
+			'AHEE__EE_Cron_Tasks__update_transaction_with_payment',
101
+			'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
102
+			'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
103
+		);
104
+		$crons    = get_option('cron');
105
+		if ( ! is_array($crons)) {
106
+			return;
107
+		}
108
+		foreach ($crons as $timestamp => $cron) {
109
+			foreach ($ee_crons as $ee_cron) {
110
+				if (isset($cron[$ee_cron])) {
111
+					do_action('AHEE_log', __CLASS__, __FUNCTION__, $ee_cron, 'scheduled EE cron');
112
+					foreach ($cron[$ee_cron] as $ee_cron_details) {
113
+						if ( ! empty($ee_cron_details['args'])) {
114
+							do_action('AHEE_log', __CLASS__, __FUNCTION__, print_r($ee_cron_details['args'], true),
115
+								"$ee_cron args");
116
+						}
117
+					}
118
+				}
119
+			}
120
+		}
121
+	}
122
+
123
+
124
+
125
+
126
+	/****************  UPDATE TRANSACTION WITH PAYMENT ****************/
127
+
128
+
129
+	/**
130
+	 * array of TXN IDs and the payment
131
+	 *
132
+	 * @var array
133
+	 */
134
+	protected static $_update_transactions_with_payment = array();
135
+
136
+
137
+	/**
138
+	 * schedule_update_transaction_with_payment
139
+	 * sets a wp_schedule_single_event() for updating any TXNs that may
140
+	 * require updating due to recently received payments
141
+	 *
142
+	 * @param int $timestamp
143
+	 * @param int $TXN_ID
144
+	 * @param int $PAY_ID
145
+	 */
146
+	public static function schedule_update_transaction_with_payment(
147
+		$timestamp,
148
+		$TXN_ID,
149
+		$PAY_ID
150
+	) {
151
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
152
+		// validate $TXN_ID and $timestamp
153
+		$TXN_ID    = absint($TXN_ID);
154
+		$timestamp = absint($timestamp);
155
+		if ($TXN_ID && $timestamp) {
156
+			wp_schedule_single_event(
157
+				$timestamp,
158
+				'AHEE__EE_Cron_Tasks__update_transaction_with_payment_2',
159
+				array($TXN_ID, $PAY_ID)
160
+			);
161
+		}
162
+	}
163
+
164
+
165
+	/**
166
+	 * setup_update_for_transaction_with_payment
167
+	 * this is the callback for the action hook:
168
+	 * 'AHEE__EE_Cron_Tasks__update_transaction_with_payment'
169
+	 * which is setup by EE_Cron_Tasks::schedule_update_transaction_with_payment().
170
+	 * The passed TXN_ID and associated payment gets added to an array, and then
171
+	 * the EE_Cron_Tasks::update_transaction_with_payment() function is hooked into
172
+	 * 'shutdown' which will actually handle the processing of any
173
+	 * transactions requiring updating, because doing so now would be too early
174
+	 * and the required resources may not be available
175
+	 *
176
+	 * @param int $TXN_ID
177
+	 * @param int $PAY_ID
178
+	 */
179
+	public static function setup_update_for_transaction_with_payment($TXN_ID = 0, $PAY_ID = 0)
180
+	{
181
+		do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
182
+		if (absint($TXN_ID)) {
183
+			self::$_update_transactions_with_payment[$TXN_ID] = $PAY_ID;
184
+			add_action(
185
+				'shutdown',
186
+				array('EE_Cron_Tasks', 'update_transaction_with_payment'),
187
+				5
188
+			);
189
+		}
190
+	}
191
+
192
+
193
+	/**
194
+	 * update_transaction_with_payment
195
+	 * loops through the self::$_abandoned_transactions array
196
+	 * and attempts to finalize any TXNs that have not been completed
197
+	 * but have had their sessions expired, most likely due to a user not
198
+	 * returning from an off-site payment gateway
199
+	 *
200
+	 * @throws \EE_Error
201
+	 */
202
+	public static function update_transaction_with_payment()
203
+	{
204
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
205
+		// are there any TXNs that need cleaning up ?
206
+		if ( ! empty(self::$_update_transactions_with_payment)) {
207
+			/** @type EE_Payment_Processor $payment_processor */
208
+			$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
209
+			// set revisit flag for payment processor
210
+			$payment_processor->set_revisit(false);
211
+			// load EEM_Transaction
212
+			EE_Registry::instance()->load_model('Transaction');
213
+			foreach (self::$_update_transactions_with_payment as $TXN_ID => $PAY_ID) {
214
+				// reschedule the cron if we can't hit the db right now
215
+				if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
216
+					// reset cron job for updating the TXN
217
+					EE_Cron_Tasks::schedule_update_transaction_with_payment(
218
+						time() + EE_Cron_Tasks::reschedule_timeout,
219
+						$TXN_ID,
220
+						$PAY_ID
221
+					);
222
+					continue;
223
+				}
224
+				$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
225
+				$payment     = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
226
+				// verify transaction
227
+				if ($transaction instanceof EE_Transaction && $payment instanceof EE_Payment) {
228
+					// now try to update the TXN with any payments
229
+					$payment_processor->update_txn_based_on_payment($transaction, $payment, true, true);
230
+				}
231
+				unset(self::$_update_transactions_with_payment[$TXN_ID]);
232
+			}
233
+		}
234
+	}
235
+
236
+
237
+
238
+	/************  END OF UPDATE TRANSACTION WITH PAYMENT  ************/
239
+
240
+
241
+	/*****************  FINALIZE ABANDONED TRANSACTIONS *****************/
242
+
243
+
244
+	/**
245
+	 * array of TXN IDs
246
+	 *
247
+	 * @var array
248
+	 */
249
+	protected static $_abandoned_transactions = array();
250
+
251
+
252
+	/**
253
+	 * schedule_finalize_abandoned_transactions_check
254
+	 * sets a wp_schedule_single_event() for finalizing any TXNs that may
255
+	 * have been abandoned during the registration process
256
+	 *
257
+	 * @param int $timestamp
258
+	 * @param int $TXN_ID
259
+	 */
260
+	public static function schedule_finalize_abandoned_transactions_check(
261
+		$timestamp,
262
+		$TXN_ID
263
+	) {
264
+		// validate $TXN_ID and $timestamp
265
+		$TXN_ID    = absint($TXN_ID);
266
+		$timestamp = absint($timestamp);
267
+		do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
268
+		if ($TXN_ID && $timestamp) {
269
+			wp_schedule_single_event(
270
+				$timestamp,
271
+				'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
272
+				array($TXN_ID)
273
+			);
274
+		}
275
+	}
276
+
277
+
278
+	/**
279
+	 * check_for_abandoned_transactions
280
+	 * this is the callback for the action hook:
281
+	 * 'AHEE__EE_Cron_Tasks__espresso_finalize_abandoned_transactions'
282
+	 * which is utilized by wp_schedule_single_event()
283
+	 * in EE_SPCO_Reg_Step_Payment_Options::_post_payment_processing().
284
+	 * The passed TXN_ID gets added to an array, and then the
285
+	 * espresso_finalize_abandoned_transactions() function is hooked into
286
+	 * 'AHEE__EE_System__core_loaded_and_ready' which will actually handle the
287
+	 * processing of any abandoned transactions, because doing so now would be
288
+	 * too early and the required resources may not be available
289
+	 *
290
+	 * @param int $TXN_ID
291
+	 */
292
+	public static function check_for_abandoned_transactions($TXN_ID = 0)
293
+	{
294
+		do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
295
+		if (absint($TXN_ID)) {
296
+			self::$_abandoned_transactions[] = $TXN_ID;
297
+			add_action(
298
+				'shutdown',
299
+				array('EE_Cron_Tasks', 'finalize_abandoned_transactions'),
300
+				5
301
+			);
302
+		}
303
+	}
304
+
305
+
306
+	/**
307
+	 * finalize_abandoned_transactions
308
+	 * loops through the self::$_abandoned_transactions array
309
+	 * and attempts to finalize any TXNs that have not been completed
310
+	 * but have had their sessions expired, most likely due to a user not
311
+	 * returning from an off-site payment gateway
312
+	 *
313
+	 * @throws \EE_Error
314
+	 */
315
+	public static function finalize_abandoned_transactions()
316
+	{
317
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
318
+		// are there any TXNs that need cleaning up ?
319
+		if ( ! empty(self::$_abandoned_transactions)) {
320
+			/** @type EE_Transaction_Processor $transaction_processor */
321
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
322
+			// set revisit flag for txn processor
323
+			$transaction_processor->set_revisit(false);
324
+			/** @type EE_Payment_Processor $payment_processor */
325
+			$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
326
+			// load EEM_Transaction
327
+			EE_Registry::instance()->load_model('Transaction');
328
+			foreach (self::$_abandoned_transactions as $TXN_ID) {
329
+				do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
330
+				// reschedule the cron if we can't hit the db right now
331
+				if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
332
+					// reset cron job for finalizing the TXN
333
+					EE_Cron_Tasks::schedule_finalize_abandoned_transactions_check(
334
+						time() + EE_Cron_Tasks::reschedule_timeout,
335
+						$TXN_ID
336
+					);
337
+					continue;
338
+				}
339
+				$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
340
+				// verify transaction
341
+				if ($transaction instanceof EE_Transaction) {
342
+					// don't finalize the TXN if it has already been completed
343
+					if ($transaction->all_reg_steps_completed() === true) {
344
+						continue;
345
+					}
346
+					// let's simulate an IPN here which will trigger any notifications that need to go out
347
+					$payment_processor->update_txn_based_on_payment($transaction, $transaction->last_payment(), true,
348
+						true);
349
+				}
350
+				unset(self::$_abandoned_transactions[$TXN_ID]);
351
+			}
352
+		}
353
+	}
354
+
355
+
356
+
357
+	/*************  END OF FINALIZE ABANDONED TRANSACTIONS  *************/
358
+
359
+
360
+	/************* START CLEAN UP BOT TRANSACTIONS **********************/
361
+
362
+	//when a transaction is initially made, schedule this check.
363
+	//if it has NO REG data by the time it has expired, forget about it
364
+	public static function clean_out_junk_transactions()
365
+	{
366
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
367
+			EEM_Transaction::instance('')->delete_junk_transactions();
368
+			EEM_Registration::instance('')->delete_registrations_with_no_transaction();
369
+			EEM_Line_Item::instance('')->delete_line_items_with_no_transaction();
370
+		}
371
+	}
372 372
 
373 373
 
374 374
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
              * wanting to not have this functionality can just register its own action at a priority after this one to
59 59
              * reverse any changes.
60 60
              */
61
-            add_action('AHEE__EE_System__load_core_configuration__complete', function () {
61
+            add_action('AHEE__EE_System__load_core_configuration__complete', function() {
62 62
                 EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request = true;
63 63
                 EE_Registry::instance()->NET_CFG->update_config(true, false);
64 64
                 add_option('ee_disabled_wp_cron_check', 1, '', false);
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
             'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
102 102
             'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
103 103
         );
104
-        $crons    = get_option('cron');
104
+        $crons = get_option('cron');
105 105
         if ( ! is_array($crons)) {
106 106
             return;
107 107
         }
Please login to merge, or discard this patch.
core/libraries/payment_methods/EE_Payment_Method_Manager.lib.php 2 patches
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
     protected function _register_payment_methods()
83 83
     {
84 84
         // grab list of installed modules
85
-        $pm_to_register = glob(EE_PAYMENT_METHODS . '*', GLOB_ONLYDIR);
85
+        $pm_to_register = glob(EE_PAYMENT_METHODS.'*', GLOB_ONLYDIR);
86 86
         // filter list of modules to register
87 87
         $pm_to_register = apply_filters('FHEE__EE_Payment_Method_Manager__register_payment_methods__payment_methods_to_register',
88 88
             $pm_to_register);
@@ -118,30 +118,30 @@  discard block
 block discarded – undo
118 118
         // create classname from module directory name
119 119
         $module = str_replace(' ', '_', str_replace('_', ' ', $module_dir));
120 120
         // add class prefix
121
-        $module_class = 'EE_PMT_' . $module;
121
+        $module_class = 'EE_PMT_'.$module;
122 122
         // does the module exist ?
123
-        if ( ! is_readable($payment_method_path . DS . $module_class . $module_ext)) {
123
+        if ( ! is_readable($payment_method_path.DS.$module_class.$module_ext)) {
124 124
             $msg = sprintf(__('The requested %s payment method file could not be found or is not readable due to file permissions.',
125 125
                 'event_espresso'), $module);
126
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
126
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
127 127
             return false;
128 128
         }
129 129
         if (WP_DEBUG === true) {
130 130
             EEH_Debug_Tools::instance()->start_timer();
131 131
         }
132 132
         // load the module class file
133
-        require_once($payment_method_path . DS . $module_class . $module_ext);
133
+        require_once($payment_method_path.DS.$module_class.$module_ext);
134 134
         if (WP_DEBUG === true) {
135 135
             EEH_Debug_Tools::instance()->stop_timer("Requiring payment method $module_class");
136 136
         }
137 137
         // verify that class exists
138 138
         if ( ! class_exists($module_class)) {
139 139
             $msg = sprintf(__('The requested %s module class does not exist.', 'event_espresso'), $module_class);
140
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
140
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
141 141
             return false;
142 142
         }
143 143
         // add to array of registered modules
144
-        $this->_payment_method_types[$module] = $payment_method_path . DS . $module_class . $module_ext;
144
+        $this->_payment_method_types[$module] = $payment_method_path.DS.$module_class.$module_ext;
145 145
         return true;
146 146
     }
147 147
 
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
     public function payment_method_class_from_type($type)
231 231
     {
232 232
         $this->maybe_register_payment_methods();
233
-        return "EE_PMT_" . $type;
233
+        return "EE_PMT_".$type;
234 234
     }
235 235
 
236 236
 
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
                 sprintf(
276 276
                     __('Note, when the invoice payment method is activated, the invoice message type, html messenger, and pdf messenger are activated as well for the %1$smessages system%2$s.',
277 277
                         'event_espresso'),
278
-                    '<a href="' . admin_url('admin.php?page=espresso_messages') . '">',
278
+                    '<a href="'.admin_url('admin.php?page=espresso_messages').'">',
279 279
                     '</a>'
280 280
                 )
281 281
             );
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
                 'PMD_type'       => $pm_type_obj->system_name(),
301 301
                 'PMD_name'       => $pm_type_obj->pretty_name(),
302 302
                 'PMD_admin_name' => $pm_type_obj->pretty_name(),
303
-                'PMD_slug'       => $pm_type_obj->system_name(),//automatically converted to slug
303
+                'PMD_slug'       => $pm_type_obj->system_name(), //automatically converted to slug
304 304
                 'PMD_wp_user'    => $current_user->ID,
305 305
                 'PMD_order'      => EEM_Payment_Method::instance()->count(
306 306
                         array(array('PMD_type' => array('!=', 'Admin_Only')))
Please login to merge, or discard this patch.
Indentation   +407 added lines, -407 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
 
@@ -17,407 +17,407 @@  discard block
 block discarded – undo
17 17
 class EE_Payment_Method_Manager
18 18
 {
19 19
 
20
-    /**
21
-     *    instance of the EE_Payment_Method_Manager object
22
-     *
23
-     * @var    $_instance
24
-     * @access    private
25
-     */
26
-    private static $_instance;
27
-
28
-    /**
29
-     * @var array keys are classnames without 'EE_PMT_', values are their filepaths
30
-     */
31
-    protected $_payment_method_types = array();
32
-
33
-
34
-
35
-    /**
36
-     * @singleton method used to instantiate class object
37
-     * @access    public
38
-     * @return EE_Payment_Method_Manager instance
39
-     */
40
-    public static function instance()
41
-    {
42
-        // check if class object is instantiated, and instantiated properly
43
-        if ( ! self::$_instance instanceof EE_Payment_Method_Manager) {
44
-            self::$_instance = new self();
45
-        }
46
-        EE_Registry::instance()->load_lib('PMT_Base');
47
-        return self::$_instance;
48
-    }
49
-
50
-
51
-
52
-    /**
53
-     * Resets the instance and returns a new one
54
-     *
55
-     * @return EE_Payment_Method_Manager
56
-     */
57
-    public static function reset()
58
-    {
59
-        self::$_instance = null;
60
-        return self::instance();
61
-    }
62
-
63
-
64
-
65
-    /**
66
-     * If necessary, re-register payment methods
67
-     *
68
-     * @param boolean $force_recheck whether to recheck for payment method types,
69
-     *                               or just re-use the PMTs we found last time we checked during this request (if
70
-     *                               we have not yet checked during this request, then we need to check anyways)
71
-     */
72
-    public function maybe_register_payment_methods($force_recheck = false)
73
-    {
74
-        if ( ! $this->_payment_method_types || $force_recheck) {
75
-            $this->_register_payment_methods();
76
-            //if in admin lets ensure caps are set.
77
-            if (is_admin()) {
78
-                add_filter('FHEE__EE_Capabilities__init_caps_map__caps', array($this, 'add_payment_method_caps'));
79
-                EE_Registry::instance()->CAP->init_caps();
80
-            }
81
-        }
82
-    }
83
-
84
-
85
-
86
-    /**
87
-     *        register_payment_methods
88
-     *
89
-     * @return array
90
-     */
91
-    protected function _register_payment_methods()
92
-    {
93
-        // grab list of installed modules
94
-        $pm_to_register = glob(EE_PAYMENT_METHODS . '*', GLOB_ONLYDIR);
95
-        // filter list of modules to register
96
-        $pm_to_register = apply_filters('FHEE__EE_Payment_Method_Manager__register_payment_methods__payment_methods_to_register',
97
-            $pm_to_register);
98
-        // loop through folders
99
-        foreach ($pm_to_register as $pm_path) {
100
-            $this->register_payment_method($pm_path);
101
-        }
102
-        do_action('FHEE__EE_Payment_Method_Manager__register_payment_methods__registered_payment_methods');
103
-        // filter list of installed modules
104
-        //keep them organized alphabetically by the payment method type's name
105
-        ksort($this->_payment_method_types);
106
-        return apply_filters('FHEE__EE_Payment_Method_Manager__register_payment_methods__installed_payment_methods',
107
-            $this->_payment_method_types);
108
-    }
109
-
110
-
111
-
112
-    /**
113
-     *    register_payment_method- makes core aware of this payment method
114
-     *
115
-     * @access public
116
-     * @param string $payment_method_path - full path up to and including payment method folder
117
-     * @return boolean
118
-     */
119
-    public function register_payment_method($payment_method_path = '')
120
-    {
121
-        do_action('AHEE__EE_Payment_Method_Manager__register_payment_method__begin', $payment_method_path);
122
-        $module_ext = '.pm.php';
123
-        // make all separators match
124
-        $payment_method_path = rtrim(str_replace('/\\', DS, $payment_method_path), DS);
125
-        // grab and sanitize module name
126
-        $module_dir = basename($payment_method_path);
127
-        // create classname from module directory name
128
-        $module = str_replace(' ', '_', str_replace('_', ' ', $module_dir));
129
-        // add class prefix
130
-        $module_class = 'EE_PMT_' . $module;
131
-        // does the module exist ?
132
-        if ( ! is_readable($payment_method_path . DS . $module_class . $module_ext)) {
133
-            $msg = sprintf(__('The requested %s payment method file could not be found or is not readable due to file permissions.',
134
-                'event_espresso'), $module);
135
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
136
-            return false;
137
-        }
138
-        if (WP_DEBUG === true) {
139
-            EEH_Debug_Tools::instance()->start_timer();
140
-        }
141
-        // load the module class file
142
-        require_once($payment_method_path . DS . $module_class . $module_ext);
143
-        if (WP_DEBUG === true) {
144
-            EEH_Debug_Tools::instance()->stop_timer("Requiring payment method $module_class");
145
-        }
146
-        // verify that class exists
147
-        if ( ! class_exists($module_class)) {
148
-            $msg = sprintf(__('The requested %s module class does not exist.', 'event_espresso'), $module_class);
149
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
150
-            return false;
151
-        }
152
-        // add to array of registered modules
153
-        $this->_payment_method_types[$module] = $payment_method_path . DS . $module_class . $module_ext;
154
-        return true;
155
-    }
156
-
157
-
158
-
159
-    /**
160
-     * Checks if a payment method has been registered, and if so includes it
161
-     *
162
-     * @param string  $payment_method_name like 'Paypal_Pro', (ie classname without the prefix 'EEPM_')
163
-     * @param boolean $force_recheck       whether to force re-checking for new payment method types
164
-     * @return boolean
165
-     */
166
-    public function payment_method_type_exists($payment_method_name, $force_recheck = false)
167
-    {
168
-        if (
169
-            $force_recheck
170
-            || ! is_array($this->_payment_method_types)
171
-            || ! isset($this->_payment_method_types[$payment_method_name])
172
-        ) {
173
-            $this->maybe_register_payment_methods($force_recheck);
174
-        }
175
-        if (isset($this->_payment_method_types[$payment_method_name])) {
176
-            require_once($this->_payment_method_types[$payment_method_name]);
177
-            return true;
178
-        } else {
179
-            return false;
180
-        }
181
-    }
182
-
183
-
184
-
185
-    /**
186
-     * Returns all the classnames of the various payment method types
187
-     *
188
-     * @param boolean $with_prefixes TRUE: get payment method type classnames; false just their 'names'
189
-     *                               (what you'd find in wp_esp_payment_method.PMD_type)
190
-     * @param boolean $force_recheck whether to force re-checking for new payment method types
191
-     * @return array
192
-     */
193
-    public function payment_method_type_names($with_prefixes = false, $force_recheck = false)
194
-    {
195
-        $this->maybe_register_payment_methods($force_recheck);
196
-        if ($with_prefixes) {
197
-            $classnames = array_keys($this->_payment_method_types);
198
-            $payment_methods = array();
199
-            foreach ($classnames as $classname) {
200
-                $payment_methods[] = $this->payment_method_class_from_type($classname);
201
-            }
202
-            return $payment_methods;
203
-        } else {
204
-            return array_keys($this->_payment_method_types);
205
-        }
206
-    }
207
-
208
-
209
-
210
-    /**
211
-     * Gets an object of each payment method type, none of which are bound to a
212
-     * payment method instance
213
-     *
214
-     * @param boolean $force_recheck whether to force re-checking for new payment method types
215
-     * @return EE_PMT_Base[]
216
-     */
217
-    public function payment_method_types($force_recheck = false)
218
-    {
219
-        $this->maybe_register_payment_methods($force_recheck);
220
-        $pmt_objs = array();
221
-        foreach ($this->payment_method_type_names(true) as $classname) {
222
-            $pmt_objs[] = new $classname;
223
-        }
224
-        return $pmt_objs;
225
-    }
226
-
227
-
228
-
229
-    /**
230
-     * Changes the payment method's classname into the payment method type's name
231
-     * (as used on the payment method's table's PMD_type field)
232
-     *
233
-     * @param string $classname
234
-     * @return string
235
-     */
236
-    public function payment_method_type_sans_class_prefix($classname)
237
-    {
238
-        return str_replace("EE_PMT_", "", $classname);
239
-    }
240
-
241
-
242
-
243
-    /**
244
-     * Does the opposite of payment-method_type_sans_prefix
245
-     *
246
-     * @param string $type
247
-     * @return string
248
-     */
249
-    public function payment_method_class_from_type($type)
250
-    {
251
-        $this->maybe_register_payment_methods();
252
-        return "EE_PMT_" . $type;
253
-    }
254
-
255
-
256
-
257
-    /**
258
-     * Activates a payment method of the given type.
259
-     *
260
-     * @param string $payment_method_type the PMT_type; for EE_PMT_Invoice this would be 'Invoice'
261
-     * @return \EE_Payment_Method
262
-     * @throws \EE_Error
263
-     */
264
-    public function activate_a_payment_method_of_type($payment_method_type)
265
-    {
266
-        $payment_method = EEM_Payment_Method::instance()->get_one_of_type($payment_method_type);
267
-        if ( ! $payment_method instanceof EE_Payment_Method) {
268
-            $pm_type_class = $this->payment_method_class_from_type($payment_method_type);
269
-            if (class_exists($pm_type_class)) {
270
-                /** @var $pm_type_obj EE_PMT_Base */
271
-                $pm_type_obj = new $pm_type_class;
272
-                $payment_method = EEM_Payment_Method::instance()->get_one_by_slug($pm_type_obj->system_name());
273
-                if ( ! $payment_method) {
274
-                    $payment_method = $this->create_payment_method_of_type($pm_type_obj);
275
-                }
276
-                $payment_method->set_type($payment_method_type);
277
-                $this->initialize_payment_method($payment_method);
278
-            } else {
279
-                throw new EE_Error(
280
-                    sprintf(
281
-                        __('There is no payment method of type %1$s, so it could not be activated', 'event_espresso'),
282
-                        $pm_type_class)
283
-                );
284
-            }
285
-        }
286
-        $payment_method->set_active();
287
-        $payment_method->save();
288
-        $this->set_usable_currencies_on_payment_method($payment_method);
289
-        if ($payment_method->type() === 'Invoice') {
290
-            /** @type EE_Message_Resource_Manager $message_resource_manager */
291
-            $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
292
-            $message_resource_manager->ensure_message_type_is_active('invoice', 'html');
293
-            $message_resource_manager->ensure_messenger_is_active('pdf');
294
-            EE_Error::add_persistent_admin_notice(
295
-                'invoice_pm_requirements_notice',
296
-                sprintf(
297
-                    __('The Invoice payment method has been activated. It requires the invoice message type, html messenger, and pdf messenger be activated as well for the %1$smessages system%2$s, so it has been automatically verified that they are also active.',
298
-                        'event_espresso'),
299
-                    '<a href="' . admin_url('admin.php?page=espresso_messages') . '">',
300
-                    '</a>'
301
-                ),
302
-                true
303
-            );
304
-        }
305
-        return $payment_method;
306
-    }
307
-
308
-
309
-
310
-    /**
311
-     * Creates a payment method of the specified type. Does not save it.
312
-     *
313
-     * @global WP_User    $current_user
314
-     * @param EE_PMT_Base $pm_type_obj
315
-     * @return EE_Payment_Method
316
-     * @throws \EE_Error
317
-     */
318
-    public function create_payment_method_of_type($pm_type_obj)
319
-    {
320
-        global $current_user;
321
-        $payment_method = EE_Payment_Method::new_instance(
322
-            array(
323
-                'PMD_type'       => $pm_type_obj->system_name(),
324
-                'PMD_name'       => $pm_type_obj->pretty_name(),
325
-                'PMD_admin_name' => $pm_type_obj->pretty_name(),
326
-                'PMD_slug'       => $pm_type_obj->system_name(),//automatically converted to slug
327
-                'PMD_wp_user'    => $current_user->ID,
328
-                'PMD_order'      => EEM_Payment_Method::instance()->count(
329
-                        array(array('PMD_type' => array('!=', 'Admin_Only')))
330
-                    ) * 10,
331
-            )
332
-        );
333
-        return $payment_method;
334
-    }
335
-
336
-
337
-
338
-    /**
339
-     * Sets the initial payment method properties (including extra meta)
340
-     *
341
-     * @param EE_Payment_Method $payment_method
342
-     * @return EE_Payment_Method
343
-     * @throws \EE_Error
344
-     */
345
-    public function initialize_payment_method($payment_method)
346
-    {
347
-        $pm_type_obj = $payment_method->type_obj();
348
-        $payment_method->set_description($pm_type_obj->default_description());
349
-        if ( ! $payment_method->button_url()) {
350
-            $payment_method->set_button_url($pm_type_obj->default_button_url());
351
-        }
352
-        //now add setup its default extra meta properties
353
-        $extra_metas = $pm_type_obj->settings_form()->extra_meta_inputs();
354
-        if ( ! empty($extra_metas)) {
355
-            //verify the payment method has an ID before adding extra meta
356
-            if ( ! $payment_method->ID()) {
357
-                $payment_method->save();
358
-            }
359
-            foreach ($extra_metas as $meta_name => $input) {
360
-                $payment_method->update_extra_meta($meta_name, $input->raw_value());
361
-            }
362
-        }
363
-        return $payment_method;
364
-    }
365
-
366
-
367
-
368
-    /**
369
-     * Makes sure the payment method is related to the specified payment method
370
-     *
371
-     * @param EE_Payment_Method $payment_method
372
-     * @return EE_Payment_Method
373
-     * @throws \EE_Error
374
-     */
375
-    public function set_usable_currencies_on_payment_method($payment_method)
376
-    {
377
-        foreach ($payment_method->get_all_usable_currencies() as $currency_obj) {
378
-            $payment_method->_add_relation_to($currency_obj, 'Currency');
379
-        }
380
-        return $payment_method;
381
-    }
382
-
383
-
384
-
385
-    /**
386
-     * Deactivates a payment method of the given payment method slug.
387
-     *
388
-     * @param string $payment_method_slug The slug for the payment method to deactivate.
389
-     * @return int count of rows updated.
390
-     */
391
-    public function deactivate_payment_method($payment_method_slug)
392
-    {
393
-        EE_Log::instance()->log(
394
-            __FILE__,
395
-            __FUNCTION__,
396
-            sprintf(
397
-                __('Payment method with slug %1$s is being deactivated by site admin', 'event_espresso'),
398
-                $payment_method_slug
399
-            ),
400
-            'payment_method_change'
401
-        );
402
-        $count_updated = EEM_Payment_Method::instance()->update(
403
-            array('PMD_scope' => array()),
404
-            array(array('PMD_slug' => $payment_method_slug))
405
-        );
406
-        return $count_updated;
407
-    }
408
-
409
-
410
-
411
-    /**
412
-     * callback for FHEE__EE_Capabilities__init_caps_map__caps filter to add dynamic payment method
413
-     * access caps.
414
-     *
415
-     * @param array $caps capabilities being filtered
416
-     * @return array
417
-     */
418
-    public function add_payment_method_caps($caps)
419
-    {
420
-        /* add dynamic caps from payment methods
20
+	/**
21
+	 *    instance of the EE_Payment_Method_Manager object
22
+	 *
23
+	 * @var    $_instance
24
+	 * @access    private
25
+	 */
26
+	private static $_instance;
27
+
28
+	/**
29
+	 * @var array keys are classnames without 'EE_PMT_', values are their filepaths
30
+	 */
31
+	protected $_payment_method_types = array();
32
+
33
+
34
+
35
+	/**
36
+	 * @singleton method used to instantiate class object
37
+	 * @access    public
38
+	 * @return EE_Payment_Method_Manager instance
39
+	 */
40
+	public static function instance()
41
+	{
42
+		// check if class object is instantiated, and instantiated properly
43
+		if ( ! self::$_instance instanceof EE_Payment_Method_Manager) {
44
+			self::$_instance = new self();
45
+		}
46
+		EE_Registry::instance()->load_lib('PMT_Base');
47
+		return self::$_instance;
48
+	}
49
+
50
+
51
+
52
+	/**
53
+	 * Resets the instance and returns a new one
54
+	 *
55
+	 * @return EE_Payment_Method_Manager
56
+	 */
57
+	public static function reset()
58
+	{
59
+		self::$_instance = null;
60
+		return self::instance();
61
+	}
62
+
63
+
64
+
65
+	/**
66
+	 * If necessary, re-register payment methods
67
+	 *
68
+	 * @param boolean $force_recheck whether to recheck for payment method types,
69
+	 *                               or just re-use the PMTs we found last time we checked during this request (if
70
+	 *                               we have not yet checked during this request, then we need to check anyways)
71
+	 */
72
+	public function maybe_register_payment_methods($force_recheck = false)
73
+	{
74
+		if ( ! $this->_payment_method_types || $force_recheck) {
75
+			$this->_register_payment_methods();
76
+			//if in admin lets ensure caps are set.
77
+			if (is_admin()) {
78
+				add_filter('FHEE__EE_Capabilities__init_caps_map__caps', array($this, 'add_payment_method_caps'));
79
+				EE_Registry::instance()->CAP->init_caps();
80
+			}
81
+		}
82
+	}
83
+
84
+
85
+
86
+	/**
87
+	 *        register_payment_methods
88
+	 *
89
+	 * @return array
90
+	 */
91
+	protected function _register_payment_methods()
92
+	{
93
+		// grab list of installed modules
94
+		$pm_to_register = glob(EE_PAYMENT_METHODS . '*', GLOB_ONLYDIR);
95
+		// filter list of modules to register
96
+		$pm_to_register = apply_filters('FHEE__EE_Payment_Method_Manager__register_payment_methods__payment_methods_to_register',
97
+			$pm_to_register);
98
+		// loop through folders
99
+		foreach ($pm_to_register as $pm_path) {
100
+			$this->register_payment_method($pm_path);
101
+		}
102
+		do_action('FHEE__EE_Payment_Method_Manager__register_payment_methods__registered_payment_methods');
103
+		// filter list of installed modules
104
+		//keep them organized alphabetically by the payment method type's name
105
+		ksort($this->_payment_method_types);
106
+		return apply_filters('FHEE__EE_Payment_Method_Manager__register_payment_methods__installed_payment_methods',
107
+			$this->_payment_method_types);
108
+	}
109
+
110
+
111
+
112
+	/**
113
+	 *    register_payment_method- makes core aware of this payment method
114
+	 *
115
+	 * @access public
116
+	 * @param string $payment_method_path - full path up to and including payment method folder
117
+	 * @return boolean
118
+	 */
119
+	public function register_payment_method($payment_method_path = '')
120
+	{
121
+		do_action('AHEE__EE_Payment_Method_Manager__register_payment_method__begin', $payment_method_path);
122
+		$module_ext = '.pm.php';
123
+		// make all separators match
124
+		$payment_method_path = rtrim(str_replace('/\\', DS, $payment_method_path), DS);
125
+		// grab and sanitize module name
126
+		$module_dir = basename($payment_method_path);
127
+		// create classname from module directory name
128
+		$module = str_replace(' ', '_', str_replace('_', ' ', $module_dir));
129
+		// add class prefix
130
+		$module_class = 'EE_PMT_' . $module;
131
+		// does the module exist ?
132
+		if ( ! is_readable($payment_method_path . DS . $module_class . $module_ext)) {
133
+			$msg = sprintf(__('The requested %s payment method file could not be found or is not readable due to file permissions.',
134
+				'event_espresso'), $module);
135
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
136
+			return false;
137
+		}
138
+		if (WP_DEBUG === true) {
139
+			EEH_Debug_Tools::instance()->start_timer();
140
+		}
141
+		// load the module class file
142
+		require_once($payment_method_path . DS . $module_class . $module_ext);
143
+		if (WP_DEBUG === true) {
144
+			EEH_Debug_Tools::instance()->stop_timer("Requiring payment method $module_class");
145
+		}
146
+		// verify that class exists
147
+		if ( ! class_exists($module_class)) {
148
+			$msg = sprintf(__('The requested %s module class does not exist.', 'event_espresso'), $module_class);
149
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
150
+			return false;
151
+		}
152
+		// add to array of registered modules
153
+		$this->_payment_method_types[$module] = $payment_method_path . DS . $module_class . $module_ext;
154
+		return true;
155
+	}
156
+
157
+
158
+
159
+	/**
160
+	 * Checks if a payment method has been registered, and if so includes it
161
+	 *
162
+	 * @param string  $payment_method_name like 'Paypal_Pro', (ie classname without the prefix 'EEPM_')
163
+	 * @param boolean $force_recheck       whether to force re-checking for new payment method types
164
+	 * @return boolean
165
+	 */
166
+	public function payment_method_type_exists($payment_method_name, $force_recheck = false)
167
+	{
168
+		if (
169
+			$force_recheck
170
+			|| ! is_array($this->_payment_method_types)
171
+			|| ! isset($this->_payment_method_types[$payment_method_name])
172
+		) {
173
+			$this->maybe_register_payment_methods($force_recheck);
174
+		}
175
+		if (isset($this->_payment_method_types[$payment_method_name])) {
176
+			require_once($this->_payment_method_types[$payment_method_name]);
177
+			return true;
178
+		} else {
179
+			return false;
180
+		}
181
+	}
182
+
183
+
184
+
185
+	/**
186
+	 * Returns all the classnames of the various payment method types
187
+	 *
188
+	 * @param boolean $with_prefixes TRUE: get payment method type classnames; false just their 'names'
189
+	 *                               (what you'd find in wp_esp_payment_method.PMD_type)
190
+	 * @param boolean $force_recheck whether to force re-checking for new payment method types
191
+	 * @return array
192
+	 */
193
+	public function payment_method_type_names($with_prefixes = false, $force_recheck = false)
194
+	{
195
+		$this->maybe_register_payment_methods($force_recheck);
196
+		if ($with_prefixes) {
197
+			$classnames = array_keys($this->_payment_method_types);
198
+			$payment_methods = array();
199
+			foreach ($classnames as $classname) {
200
+				$payment_methods[] = $this->payment_method_class_from_type($classname);
201
+			}
202
+			return $payment_methods;
203
+		} else {
204
+			return array_keys($this->_payment_method_types);
205
+		}
206
+	}
207
+
208
+
209
+
210
+	/**
211
+	 * Gets an object of each payment method type, none of which are bound to a
212
+	 * payment method instance
213
+	 *
214
+	 * @param boolean $force_recheck whether to force re-checking for new payment method types
215
+	 * @return EE_PMT_Base[]
216
+	 */
217
+	public function payment_method_types($force_recheck = false)
218
+	{
219
+		$this->maybe_register_payment_methods($force_recheck);
220
+		$pmt_objs = array();
221
+		foreach ($this->payment_method_type_names(true) as $classname) {
222
+			$pmt_objs[] = new $classname;
223
+		}
224
+		return $pmt_objs;
225
+	}
226
+
227
+
228
+
229
+	/**
230
+	 * Changes the payment method's classname into the payment method type's name
231
+	 * (as used on the payment method's table's PMD_type field)
232
+	 *
233
+	 * @param string $classname
234
+	 * @return string
235
+	 */
236
+	public function payment_method_type_sans_class_prefix($classname)
237
+	{
238
+		return str_replace("EE_PMT_", "", $classname);
239
+	}
240
+
241
+
242
+
243
+	/**
244
+	 * Does the opposite of payment-method_type_sans_prefix
245
+	 *
246
+	 * @param string $type
247
+	 * @return string
248
+	 */
249
+	public function payment_method_class_from_type($type)
250
+	{
251
+		$this->maybe_register_payment_methods();
252
+		return "EE_PMT_" . $type;
253
+	}
254
+
255
+
256
+
257
+	/**
258
+	 * Activates a payment method of the given type.
259
+	 *
260
+	 * @param string $payment_method_type the PMT_type; for EE_PMT_Invoice this would be 'Invoice'
261
+	 * @return \EE_Payment_Method
262
+	 * @throws \EE_Error
263
+	 */
264
+	public function activate_a_payment_method_of_type($payment_method_type)
265
+	{
266
+		$payment_method = EEM_Payment_Method::instance()->get_one_of_type($payment_method_type);
267
+		if ( ! $payment_method instanceof EE_Payment_Method) {
268
+			$pm_type_class = $this->payment_method_class_from_type($payment_method_type);
269
+			if (class_exists($pm_type_class)) {
270
+				/** @var $pm_type_obj EE_PMT_Base */
271
+				$pm_type_obj = new $pm_type_class;
272
+				$payment_method = EEM_Payment_Method::instance()->get_one_by_slug($pm_type_obj->system_name());
273
+				if ( ! $payment_method) {
274
+					$payment_method = $this->create_payment_method_of_type($pm_type_obj);
275
+				}
276
+				$payment_method->set_type($payment_method_type);
277
+				$this->initialize_payment_method($payment_method);
278
+			} else {
279
+				throw new EE_Error(
280
+					sprintf(
281
+						__('There is no payment method of type %1$s, so it could not be activated', 'event_espresso'),
282
+						$pm_type_class)
283
+				);
284
+			}
285
+		}
286
+		$payment_method->set_active();
287
+		$payment_method->save();
288
+		$this->set_usable_currencies_on_payment_method($payment_method);
289
+		if ($payment_method->type() === 'Invoice') {
290
+			/** @type EE_Message_Resource_Manager $message_resource_manager */
291
+			$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
292
+			$message_resource_manager->ensure_message_type_is_active('invoice', 'html');
293
+			$message_resource_manager->ensure_messenger_is_active('pdf');
294
+			EE_Error::add_persistent_admin_notice(
295
+				'invoice_pm_requirements_notice',
296
+				sprintf(
297
+					__('The Invoice payment method has been activated. It requires the invoice message type, html messenger, and pdf messenger be activated as well for the %1$smessages system%2$s, so it has been automatically verified that they are also active.',
298
+						'event_espresso'),
299
+					'<a href="' . admin_url('admin.php?page=espresso_messages') . '">',
300
+					'</a>'
301
+				),
302
+				true
303
+			);
304
+		}
305
+		return $payment_method;
306
+	}
307
+
308
+
309
+
310
+	/**
311
+	 * Creates a payment method of the specified type. Does not save it.
312
+	 *
313
+	 * @global WP_User    $current_user
314
+	 * @param EE_PMT_Base $pm_type_obj
315
+	 * @return EE_Payment_Method
316
+	 * @throws \EE_Error
317
+	 */
318
+	public function create_payment_method_of_type($pm_type_obj)
319
+	{
320
+		global $current_user;
321
+		$payment_method = EE_Payment_Method::new_instance(
322
+			array(
323
+				'PMD_type'       => $pm_type_obj->system_name(),
324
+				'PMD_name'       => $pm_type_obj->pretty_name(),
325
+				'PMD_admin_name' => $pm_type_obj->pretty_name(),
326
+				'PMD_slug'       => $pm_type_obj->system_name(),//automatically converted to slug
327
+				'PMD_wp_user'    => $current_user->ID,
328
+				'PMD_order'      => EEM_Payment_Method::instance()->count(
329
+						array(array('PMD_type' => array('!=', 'Admin_Only')))
330
+					) * 10,
331
+			)
332
+		);
333
+		return $payment_method;
334
+	}
335
+
336
+
337
+
338
+	/**
339
+	 * Sets the initial payment method properties (including extra meta)
340
+	 *
341
+	 * @param EE_Payment_Method $payment_method
342
+	 * @return EE_Payment_Method
343
+	 * @throws \EE_Error
344
+	 */
345
+	public function initialize_payment_method($payment_method)
346
+	{
347
+		$pm_type_obj = $payment_method->type_obj();
348
+		$payment_method->set_description($pm_type_obj->default_description());
349
+		if ( ! $payment_method->button_url()) {
350
+			$payment_method->set_button_url($pm_type_obj->default_button_url());
351
+		}
352
+		//now add setup its default extra meta properties
353
+		$extra_metas = $pm_type_obj->settings_form()->extra_meta_inputs();
354
+		if ( ! empty($extra_metas)) {
355
+			//verify the payment method has an ID before adding extra meta
356
+			if ( ! $payment_method->ID()) {
357
+				$payment_method->save();
358
+			}
359
+			foreach ($extra_metas as $meta_name => $input) {
360
+				$payment_method->update_extra_meta($meta_name, $input->raw_value());
361
+			}
362
+		}
363
+		return $payment_method;
364
+	}
365
+
366
+
367
+
368
+	/**
369
+	 * Makes sure the payment method is related to the specified payment method
370
+	 *
371
+	 * @param EE_Payment_Method $payment_method
372
+	 * @return EE_Payment_Method
373
+	 * @throws \EE_Error
374
+	 */
375
+	public function set_usable_currencies_on_payment_method($payment_method)
376
+	{
377
+		foreach ($payment_method->get_all_usable_currencies() as $currency_obj) {
378
+			$payment_method->_add_relation_to($currency_obj, 'Currency');
379
+		}
380
+		return $payment_method;
381
+	}
382
+
383
+
384
+
385
+	/**
386
+	 * Deactivates a payment method of the given payment method slug.
387
+	 *
388
+	 * @param string $payment_method_slug The slug for the payment method to deactivate.
389
+	 * @return int count of rows updated.
390
+	 */
391
+	public function deactivate_payment_method($payment_method_slug)
392
+	{
393
+		EE_Log::instance()->log(
394
+			__FILE__,
395
+			__FUNCTION__,
396
+			sprintf(
397
+				__('Payment method with slug %1$s is being deactivated by site admin', 'event_espresso'),
398
+				$payment_method_slug
399
+			),
400
+			'payment_method_change'
401
+		);
402
+		$count_updated = EEM_Payment_Method::instance()->update(
403
+			array('PMD_scope' => array()),
404
+			array(array('PMD_slug' => $payment_method_slug))
405
+		);
406
+		return $count_updated;
407
+	}
408
+
409
+
410
+
411
+	/**
412
+	 * callback for FHEE__EE_Capabilities__init_caps_map__caps filter to add dynamic payment method
413
+	 * access caps.
414
+	 *
415
+	 * @param array $caps capabilities being filtered
416
+	 * @return array
417
+	 */
418
+	public function add_payment_method_caps($caps)
419
+	{
420
+		/* add dynamic caps from payment methods
421 421
          * at the time of writing, october 20 2014, these are the caps added:
422 422
          * ee_payment_method_admin_only
423 423
          * ee_payment_method_aim
@@ -431,10 +431,10 @@  discard block
 block discarded – undo
431 431
          * their related capability automatically added too, so long as they are
432 432
          * registered properly using EE_Register_Payment_Method::register()
433 433
          */
434
-        foreach ($this->payment_method_types() as $payment_method_type_obj) {
435
-            $caps['administrator'][] = $payment_method_type_obj->cap_name();
436
-        }
437
-        return $caps;
438
-    }
434
+		foreach ($this->payment_method_types() as $payment_method_type_obj) {
435
+			$caps['administrator'][] = $payment_method_type_obj->cap_name();
436
+		}
437
+		return $caps;
438
+	}
439 439
 
440 440
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 3 patches
Doc Comments   +8 added lines, -7 removed lines patch added patch discarded remove patch
@@ -865,7 +865,7 @@  discard block
 block discarded – undo
865 865
      *
866 866
      * @param null  $field_to_order_by  What field is being used as the reference point.
867 867
      * @param array $query_params       Any additional conditions on the query.
868
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
868
+     * @param string  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
869 869
      *                                  you can indicate just the columns you want returned
870 870
      * @return array|EE_Base_Class
871 871
      * @throws \EE_Error
@@ -890,7 +890,7 @@  discard block
 block discarded – undo
890 890
      *
891 891
      * @param null  $field_to_order_by  What field is being used as the reference point.
892 892
      * @param array $query_params       Any additional conditions on the query.
893
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
893
+     * @param string  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
894 894
      *                                  you can indicate just the column you want returned
895 895
      * @return array|EE_Base_Class
896 896
      * @throws \EE_Error
@@ -963,7 +963,7 @@  discard block
 block discarded – undo
963 963
      * This method simply returns the RAW unprocessed value for the given property in this class
964 964
      *
965 965
      * @param  string $field_name A valid fieldname
966
-     * @return mixed              Whatever the raw value stored on the property is.
966
+     * @return integer|null              Whatever the raw value stored on the property is.
967 967
      * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
968 968
      */
969 969
     public function get_raw($field_name)
@@ -1258,7 +1258,7 @@  discard block
 block discarded – undo
1258 1258
      * sets the time on a datetime property
1259 1259
      *
1260 1260
      * @access protected
1261
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1261
+     * @param string $time      a valid time string for php datetime functions (or DateTime object)
1262 1262
      * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1263 1263
      * @throws \EE_Error
1264 1264
      */
@@ -1273,7 +1273,7 @@  discard block
 block discarded – undo
1273 1273
      * sets the date on a datetime property
1274 1274
      *
1275 1275
      * @access protected
1276
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1276
+     * @param string $date      a valid date string for php datetime functions ( or DateTime object)
1277 1277
      * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1278 1278
      * @throws \EE_Error
1279 1279
      */
@@ -1331,6 +1331,7 @@  discard block
 block discarded – undo
1331 1331
      * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1332 1332
      * @param string               $prepend    You can include something to prepend on the timestamp
1333 1333
      * @param string               $append     You can include something to append on the timestamp
1334
+     * @param string $args
1334 1335
      * @throws EE_Error
1335 1336
      * @return string timestamp
1336 1337
      */
@@ -1701,7 +1702,7 @@  discard block
 block discarded – undo
1701 1702
      *
1702 1703
      * @param  array  $props_n_values   incoming array of properties and their values
1703 1704
      * @param  string $classname        the classname of the child class
1704
-     * @param null    $timezone
1705
+     * @param string|null    $timezone
1705 1706
      * @param array   $date_formats     incoming date_formats in an array where the first value is the
1706 1707
      *                                  date_format and the second value is the time format
1707 1708
      * @return mixed (EE_Base_Class|bool)
@@ -1779,7 +1780,7 @@  discard block
 block discarded – undo
1779 1780
      * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1780 1781
      *
1781 1782
      * @param string $model_classname
1782
-     * @param null   $timezone
1783
+     * @param string|null   $timezone
1783 1784
      * @return EEM_Base
1784 1785
      */
1785 1786
     protected static function _get_model_instance_with_name($model_classname, $timezone = null)
Please login to merge, or discard this patch.
Indentation   +2552 added lines, -2552 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 do_action('AHEE_log', __FILE__, ' FILE LOADED', '');
5 5
 
@@ -25,2557 +25,2557 @@  discard block
 block discarded – undo
25 25
 abstract class EE_Base_Class
26 26
 {
27 27
 
28
-    /**
29
-     * This is an array of the original properties and values provided during construction
30
-     * of this model object. (keys are model field names, values are their values).
31
-     * This list is important to remember so that when we are merging data from the db, we know
32
-     * which values to override and which to not override.
33
-     *
34
-     * @var array
35
-     */
36
-    protected $_props_n_values_provided_in_constructor;
37
-
38
-    /**
39
-     * Timezone
40
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.  This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT all
41
-     * EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have access to it.
42
-     *
43
-     * @var string
44
-     */
45
-    protected $_timezone;
46
-
47
-
48
-
49
-    /**
50
-     * date format
51
-     * pattern or format for displaying dates
52
-     *
53
-     * @var string $_dt_frmt
54
-     */
55
-    protected $_dt_frmt;
56
-
57
-
58
-
59
-    /**
60
-     * time format
61
-     * pattern or format for displaying time
62
-     *
63
-     * @var string $_tm_frmt
64
-     */
65
-    protected $_tm_frmt;
66
-
67
-
68
-
69
-    /**
70
-     * This property is for holding a cached array of object properties indexed by property name as the key.
71
-     * The purpose of this is for setting a cache on properties that may have calculated values after a prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having to recalculate.
72
-     * Used by _set_cached_property() and _get_cached_property() methods.
73
-     *
74
-     * @var array
75
-     */
76
-    protected $_cached_properties = array();
77
-
78
-    /**
79
-     * An array containing keys of the related model, and values are either an array of related mode objects or a single
80
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the relation
81
-     * is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object, all others have an array)
82
-     *
83
-     * @var array
84
-     */
85
-    protected $_model_relations = array();
86
-
87
-    /**
88
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
89
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
90
-     *
91
-     * @var array
92
-     */
93
-    protected $_fields = array();
94
-
95
-    /**
96
-     * @var boolean indicating whether or not this model object is intended to ever be saved
97
-     * For example, we might create model objects intended to only be used for the duration
98
-     * of this request and to be thrown away, and if they were accidentally saved
99
-     * it would be a bug.
100
-     */
101
-    protected $_allow_persist = true;
102
-
103
-
104
-
105
-    /**
106
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children play nice
107
-     *
108
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd layer of the model's _fields array, (eg, EVT_ID, TXN_amount, QST_name, etc) and values are their values
109
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the corresponding db model or not.
110
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to be in when instantiating a EE_Base_Class object.
111
-     * @param array   $date_formats                            An array of date formats to set on construct where first
112
-     *                                                         value is the date_format and second value is the time
113
-     *                                                         format.
114
-     * @throws EE_Error
115
-     */
116
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
117
-    {
118
-        $className = get_class($this);
119
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
120
-        $model = $this->get_model();
121
-        $model_fields = $model->field_settings(false);
122
-        // ensure $fieldValues is an array
123
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
124
-        // EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
125
-        // verify client code has not passed any invalid field names
126
-        foreach ($fieldValues as $field_name => $field_value) {
127
-            if ( ! isset($model_fields[$field_name])) {
128
-                throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s", "event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
129
-            }
130
-        }
131
-        // EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
132
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
133
-        if ( ! empty($date_formats) && is_array($date_formats)) {
134
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
135
-        } else {
136
-            //set default formats for date and time
137
-            $this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
138
-            $this->_tm_frmt = (string)get_option('time_format', 'g:i a');
139
-        }
140
-        //if db model is instantiating
141
-        if ($bydb) {
142
-            //client code has indicated these field values are from the database
143
-            foreach ($model_fields as $fieldName => $field) {
144
-                $this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
145
-            }
146
-        } else {
147
-            //we're constructing a brand
148
-            //new instance of the model object. Generally, this means we'll need to do more field validation
149
-            foreach ($model_fields as $fieldName => $field) {
150
-                $this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
151
-            }
152
-        }
153
-        //remember what values were passed to this constructor
154
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
155
-        //remember in entity mapper
156
-        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
157
-            $model->add_to_entity_map($this);
158
-        }
159
-        //setup all the relations
160
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
161
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
162
-                $this->_model_relations[$relation_name] = null;
163
-            } else {
164
-                $this->_model_relations[$relation_name] = array();
165
-            }
166
-        }
167
-        /**
168
-         * Action done at the end of each model object construction
169
-         *
170
-         * @param EE_Base_Class $this the model object just created
171
-         */
172
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
173
-    }
174
-
175
-
176
-
177
-    /**
178
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
179
-     *
180
-     * @return boolean
181
-     */
182
-    public function allow_persist()
183
-    {
184
-        return $this->_allow_persist;
185
-    }
186
-
187
-
188
-
189
-    /**
190
-     * Sets whether or not this model object should be allowed to be saved to the DB.
191
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
192
-     * you got new information that somehow made you change your mind.
193
-     *
194
-     * @param boolean $allow_persist
195
-     * @return boolean
196
-     */
197
-    public function set_allow_persist($allow_persist)
198
-    {
199
-        return $this->_allow_persist = $allow_persist;
200
-    }
201
-
202
-
203
-
204
-    /**
205
-     * Gets the field's original value when this object was constructed during this request.
206
-     * This can be helpful when determining if a model object has changed or not
207
-     *
208
-     * @param string $field_name
209
-     * @return mixed|null
210
-     * @throws \EE_Error
211
-     */
212
-    public function get_original($field_name)
213
-    {
214
-        if (isset($this->_props_n_values_provided_in_constructor[$field_name])
215
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
216
-        ) {
217
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
218
-        } else {
219
-            return null;
220
-        }
221
-    }
222
-
223
-
224
-
225
-    /**
226
-     * @param EE_Base_Class $obj
227
-     * @return string
228
-     */
229
-    public function get_class($obj)
230
-    {
231
-        return get_class($obj);
232
-    }
233
-
234
-
235
-
236
-    /**
237
-     * Overrides parent because parent expects old models.
238
-     * This also doesn't do any validation, and won't work for serialized arrays
239
-     *
240
-     * @param    string $field_name
241
-     * @param    mixed  $field_value
242
-     * @param bool      $use_default
243
-     * @throws \EE_Error
244
-     */
245
-    public function set($field_name, $field_value, $use_default = false)
246
-    {
247
-        $field_obj = $this->get_model()->field_settings_for($field_name);
248
-        if ($field_obj instanceof EE_Model_Field_Base) {
249
-            //			if ( method_exists( $field_obj, 'set_timezone' )) {
250
-            if ($field_obj instanceof EE_Datetime_Field) {
251
-                $field_obj->set_timezone($this->_timezone);
252
-                $field_obj->set_date_format($this->_dt_frmt);
253
-                $field_obj->set_time_format($this->_tm_frmt);
254
-            }
255
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
256
-            //should the value be null?
257
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
258
-                $this->_fields[$field_name] = $field_obj->get_default_value();
259
-                /**
260
-                 * To save having to refactor all the models, if a default value is used for a
261
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
262
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
263
-                 * object.
264
-                 *
265
-                 * @since 4.6.10+
266
-                 */
267
-                if (
268
-                    $field_obj instanceof EE_Datetime_Field
269
-                    && $this->_fields[$field_name] !== null
270
-                    && ! $this->_fields[$field_name] instanceof DateTime
271
-                ) {
272
-                    empty($this->_fields[$field_name])
273
-                        ? $this->set($field_name, time())
274
-                        : $this->set($field_name, $this->_fields[$field_name]);
275
-                }
276
-            } else {
277
-                $this->_fields[$field_name] = $holder_of_value;
278
-            }
279
-            //if we're not in the constructor...
280
-            //now check if what we set was a primary key
281
-            if (
282
-                //note: props_n_values_provided_in_constructor is only set at the END of the constructor
283
-                $this->_props_n_values_provided_in_constructor
284
-                && $field_value
285
-                && $field_name === self::_get_primary_key_name(get_class($this))
286
-            ) {
287
-                //if so, we want all this object's fields to be filled either with
288
-                //what we've explicitly set on this model
289
-                //or what we have in the db
290
-                // echo "setting primary key!";
291
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
292
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
293
-                foreach ($fields_on_model as $field_obj) {
294
-                    if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
295
-                         && $field_obj->get_name() !== $field_name
296
-                    ) {
297
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
298
-                    }
299
-                }
300
-                //oh this model object has an ID? well make sure its in the entity mapper
301
-                $this->get_model()->add_to_entity_map($this);
302
-            }
303
-            //let's unset any cache for this field_name from the $_cached_properties property.
304
-            $this->_clear_cached_property($field_name);
305
-        } else {
306
-            throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s", "event_espresso"), $field_name));
307
-        }
308
-    }
309
-
310
-
311
-
312
-    /**
313
-     * This sets the field value on the db column if it exists for the given $column_name or
314
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
315
-     *
316
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
317
-     * @param string $field_name  Must be the exact column name.
318
-     * @param mixed  $field_value The value to set.
319
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
320
-     * @throws \EE_Error
321
-     */
322
-    public function set_field_or_extra_meta($field_name, $field_value)
323
-    {
324
-        if ($this->get_model()->has_field($field_name)) {
325
-            $this->set($field_name, $field_value);
326
-            return true;
327
-        } else {
328
-            //ensure this object is saved first so that extra meta can be properly related.
329
-            $this->save();
330
-            return $this->update_extra_meta($field_name, $field_value);
331
-        }
332
-    }
333
-
334
-
335
-
336
-    /**
337
-     * This retrieves the value of the db column set on this class or if that's not present
338
-     * it will attempt to retrieve from extra_meta if found.
339
-     * Example Usage:
340
-     * Via EE_Message child class:
341
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
342
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
343
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
344
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
345
-     * value for those extra fields dynamically via the EE_message object.
346
-     *
347
-     * @param  string $field_name expecting the fully qualified field name.
348
-     * @return mixed|null  value for the field if found.  null if not found.
349
-     * @throws \EE_Error
350
-     */
351
-    public function get_field_or_extra_meta($field_name)
352
-    {
353
-        if ($this->get_model()->has_field($field_name)) {
354
-            $column_value = $this->get($field_name);
355
-        } else {
356
-            //This isn't a column in the main table, let's see if it is in the extra meta.
357
-            $column_value = $this->get_extra_meta($field_name, true, null);
358
-        }
359
-        return $column_value;
360
-    }
361
-
362
-
363
-
364
-    /**
365
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally for being able to reference what timezone we are running conversions on when converting TO the internal timezone (UTC
366
-     * Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is available to all child classes that may be using the EE_Datetime_Field for a field data type.
367
-     *
368
-     * @access public
369
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
370
-     * @return void
371
-     * @throws \EE_Error
372
-     */
373
-    public function set_timezone($timezone = '')
374
-    {
375
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
376
-        //make sure we clear all cached properties because they won't be relevant now
377
-        $this->_clear_cached_properties();
378
-        //make sure we update field settings and the date for all EE_Datetime_Fields
379
-        $model_fields = $this->get_model()->field_settings(false);
380
-        foreach ($model_fields as $field_name => $field_obj) {
381
-            if ($field_obj instanceof EE_Datetime_Field) {
382
-                $field_obj->set_timezone($this->_timezone);
383
-                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
384
-                    $this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
385
-                }
386
-            }
387
-        }
388
-    }
389
-
390
-
391
-
392
-    /**
393
-     * This just returns whatever is set for the current timezone.
394
-     *
395
-     * @access public
396
-     * @return string timezone string
397
-     */
398
-    public function get_timezone()
399
-    {
400
-        return $this->_timezone;
401
-    }
402
-
403
-
404
-
405
-    /**
406
-     * This sets the internal date format to what is sent in to be used as the new default for the class
407
-     * internally instead of wp set date format options
408
-     *
409
-     * @since 4.6
410
-     * @param string $format should be a format recognizable by PHP date() functions.
411
-     */
412
-    public function set_date_format($format)
413
-    {
414
-        $this->_dt_frmt = $format;
415
-        //clear cached_properties because they won't be relevant now.
416
-        $this->_clear_cached_properties();
417
-    }
418
-
419
-
420
-
421
-    /**
422
-     * This sets the internal time format string to what is sent in to be used as the new default for the
423
-     * class internally instead of wp set time format options.
424
-     *
425
-     * @since 4.6
426
-     * @param string $format should be a format recognizable by PHP date() functions.
427
-     */
428
-    public function set_time_format($format)
429
-    {
430
-        $this->_tm_frmt = $format;
431
-        //clear cached_properties because they won't be relevant now.
432
-        $this->_clear_cached_properties();
433
-    }
434
-
435
-
436
-
437
-    /**
438
-     * This returns the current internal set format for the date and time formats.
439
-     *
440
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array where the
441
-     *                             first value is the date format and the second value is the time format.
442
-     * @return mixed string|array
443
-     */
444
-    public function get_format($full = true)
445
-    {
446
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
447
-    }
448
-
449
-
450
-
451
-    /**
452
-     * cache
453
-     * stores the passed model object on the current model object.
454
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
455
-     *
456
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg 'Registration' associated with this model object
457
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction, that could be a payment or a registration)
458
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many items which will be stored in an array on this object
459
-     * @throws EE_Error
460
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one related thing, no array)
461
-     */
462
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
463
-    {
464
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
465
-        if ( ! $object_to_cache instanceof EE_Base_Class) {
466
-            return false;
467
-        }
468
-        // also get "how" the object is related, or throw an error
469
-        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
470
-            throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'), $relationName, get_class($this)));
471
-        }
472
-        // how many things are related ?
473
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
474
-            // if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
475
-            // so for these model objects just set it to be cached
476
-            $this->_model_relations[$relationName] = $object_to_cache;
477
-            $return = true;
478
-        } else {
479
-            // otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
480
-            // eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
481
-            if ( ! is_array($this->_model_relations[$relationName])) {
482
-                // if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
483
-                $this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class ? array($this->_model_relations[$relationName]) : array();
484
-            }
485
-            // first check for a cache_id which is normally empty
486
-            if ( ! empty($cache_id)) {
487
-                // if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
488
-                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
489
-                $return = $cache_id;
490
-            } elseif ($object_to_cache->ID()) {
491
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
492
-                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
493
-                $return = $object_to_cache->ID();
494
-            } else {
495
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
496
-                $this->_model_relations[$relationName][] = $object_to_cache;
497
-                // move the internal pointer to the end of the array
498
-                end($this->_model_relations[$relationName]);
499
-                // and grab the key so that we can return it
500
-                $return = key($this->_model_relations[$relationName]);
501
-            }
502
-        }
503
-        return $return;
504
-    }
505
-
506
-
507
-
508
-    /**
509
-     * For adding an item to the cached_properties property.
510
-     *
511
-     * @access protected
512
-     * @param string      $fieldname the property item the corresponding value is for.
513
-     * @param mixed       $value     The value we are caching.
514
-     * @param string|null $cache_type
515
-     * @return void
516
-     * @throws \EE_Error
517
-     */
518
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
519
-    {
520
-        //first make sure this property exists
521
-        $this->get_model()->field_settings_for($fieldname);
522
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
523
-        $this->_cached_properties[$fieldname][$cache_type] = $value;
524
-    }
525
-
526
-
527
-
528
-    /**
529
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
530
-     * This also SETS the cache if we return the actual property!
531
-     *
532
-     * @param string $fieldname        the name of the property we're trying to retrieve
533
-     * @param bool   $pretty
534
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
535
-     *                                 (in cases where the same property may be used for different outputs
536
-     *                                 - i.e. datetime, money etc.)
537
-     *                                 It can also accept certain pre-defined "schema" strings
538
-     *                                 to define how to output the property.
539
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
540
-     * @return mixed                   whatever the value for the property is we're retrieving
541
-     * @throws \EE_Error
542
-     */
543
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
544
-    {
545
-        //verify the field exists
546
-        $this->get_model()->field_settings_for($fieldname);
547
-        $cache_type = $pretty ? 'pretty' : 'standard';
548
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
549
-        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
550
-            return $this->_cached_properties[$fieldname][$cache_type];
551
-        }
552
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
553
-        if ($field_obj instanceof EE_Model_Field_Base) {
554
-            /**
555
-             * maybe this is EE_Datetime_Field.  If so we need to make sure timezone and
556
-             * formats are correct.
557
-             */
558
-            if ($field_obj instanceof EE_Datetime_Field) {
559
-                $field_obj->set_timezone($this->_timezone);
560
-                $field_obj->set_date_format($this->_dt_frmt, $pretty);
561
-                $field_obj->set_time_format($this->_tm_frmt, $pretty);
562
-            }
563
-            if ( ! isset($this->_fields[$fieldname])) {
564
-                $this->_fields[$fieldname] = null;
565
-            }
566
-            $value = $pretty
567
-                ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
568
-                : $field_obj->prepare_for_get($this->_fields[$fieldname]);
569
-            $this->_set_cached_property($fieldname, $value, $cache_type);
570
-            return $value;
571
-        }
572
-        return null;
573
-    }
574
-
575
-
576
-
577
-    /**
578
-     * This just takes care of clearing out the cached_properties
579
-     *
580
-     * @return void
581
-     */
582
-    protected function _clear_cached_properties()
583
-    {
584
-        $this->_cached_properties = array();
585
-    }
586
-
587
-
588
-
589
-    /**
590
-     * This just clears out ONE property if it exists in the cache
591
-     *
592
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
593
-     * @return void
594
-     */
595
-    protected function _clear_cached_property($property_name)
596
-    {
597
-        if (isset($this->_cached_properties[$property_name])) {
598
-            unset($this->_cached_properties[$property_name]);
599
-        }
600
-    }
601
-
602
-
603
-
604
-    /**
605
-     * Ensures that this related thing is a model object.
606
-     *
607
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
608
-     * @param string $model_name   name of the related thing, eg 'Attendee',
609
-     * @return EE_Base_Class
610
-     * @throws \EE_Error
611
-     */
612
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
613
-    {
614
-        $other_model_instance = self::_get_model_instance_with_name(
615
-            self::_get_model_classname($model_name),
616
-            $this->_timezone
617
-        );
618
-        return $other_model_instance->ensure_is_obj($object_or_id);
619
-    }
620
-
621
-
622
-
623
-    /**
624
-     * Forgets the cached model of the given relation Name. So the next time we request it,
625
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
626
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
627
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
628
-     *
629
-     * @param string $relationName                         one of the keys in the _model_relations array on the model. Eg 'Registration'
630
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
631
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only has 1 object anyways (ie, it's a BelongsToRelation)
632
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if this is HasMany or HABTM.
633
-     * @throws EE_Error
634
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a relation from all
635
-     */
636
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
637
-    {
638
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
639
-        $index_in_cache = '';
640
-        if ( ! $relationship_to_model) {
641
-            throw new EE_Error(
642
-                sprintf(
643
-                    __("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
644
-                    $relationName,
645
-                    get_class($this)
646
-                )
647
-            );
648
-        }
649
-        if ($clear_all) {
650
-            $obj_removed = true;
651
-            $this->_model_relations[$relationName] = null;
652
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
653
-            $obj_removed = $this->_model_relations[$relationName];
654
-            $this->_model_relations[$relationName] = null;
655
-        } else {
656
-            if ($object_to_remove_or_index_into_array instanceof EE_Base_Class && $object_to_remove_or_index_into_array->ID()) {
657
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
658
-                if (is_array($this->_model_relations[$relationName]) && ! isset($this->_model_relations[$relationName][$index_in_cache])) {
659
-                    $index_found_at = null;
660
-                    //find this object in the array even though it has a different key
661
-                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
662
-                        if (
663
-                            $obj instanceof EE_Base_Class
664
-                            && (
665
-                                $obj == $object_to_remove_or_index_into_array
666
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
667
-                            )
668
-                        ) {
669
-                            $index_found_at = $index;
670
-                            break;
671
-                        }
672
-                    }
673
-                    if ($index_found_at) {
674
-                        $index_in_cache = $index_found_at;
675
-                    } else {
676
-                        //it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
677
-                        //if it wasn't in it to begin with. So we're done
678
-                        return $object_to_remove_or_index_into_array;
679
-                    }
680
-                }
681
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
682
-                //so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
683
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
684
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
685
-                        $index_in_cache = $index;
686
-                    }
687
-                }
688
-            } else {
689
-                $index_in_cache = $object_to_remove_or_index_into_array;
690
-            }
691
-            //supposedly we've found it. But it could just be that the client code
692
-            //provided a bad index/object
693
-            if (
694
-            isset(
695
-                $this->_model_relations[$relationName],
696
-                $this->_model_relations[$relationName][$index_in_cache]
697
-            )
698
-            ) {
699
-                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
700
-                unset($this->_model_relations[$relationName][$index_in_cache]);
701
-            } else {
702
-                //that thing was never cached anyways.
703
-                $obj_removed = null;
704
-            }
705
-        }
706
-        return $obj_removed;
707
-    }
708
-
709
-
710
-
711
-    /**
712
-     * update_cache_after_object_save
713
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has obtained after being saved to the db
714
-     *
715
-     * @param string         $relationName       - the type of object that is cached
716
-     * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
717
-     * @param string         $current_cache_id   - the ID that was used when originally caching the object
718
-     * @return boolean TRUE on success, FALSE on fail
719
-     * @throws \EE_Error
720
-     */
721
-    public function update_cache_after_object_save($relationName, EE_Base_Class $newly_saved_object, $current_cache_id = '')
722
-    {
723
-        // verify that incoming object is of the correct type
724
-        $obj_class = 'EE_' . $relationName;
725
-        if ($newly_saved_object instanceof $obj_class) {
726
-            /* @type EE_Base_Class $newly_saved_object */
727
-            // now get the type of relation
728
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
729
-            // if this is a 1:1 relationship
730
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
731
-                // then just replace the cached object with the newly saved object
732
-                $this->_model_relations[$relationName] = $newly_saved_object;
733
-                return true;
734
-                // or if it's some kind of sordid feral polyamorous relationship...
735
-            } elseif (is_array($this->_model_relations[$relationName]) && isset($this->_model_relations[$relationName][$current_cache_id])) {
736
-                // then remove the current cached item
737
-                unset($this->_model_relations[$relationName][$current_cache_id]);
738
-                // and cache the newly saved object using it's new ID
739
-                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
740
-                return true;
741
-            }
742
-        }
743
-        return false;
744
-    }
745
-
746
-
747
-
748
-    /**
749
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
750
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
751
-     *
752
-     * @param string $relationName
753
-     * @return EE_Base_Class
754
-     */
755
-    public function get_one_from_cache($relationName)
756
-    {
757
-        $cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : null;
758
-        if (is_array($cached_array_or_object)) {
759
-            return array_shift($cached_array_or_object);
760
-        } else {
761
-            return $cached_array_or_object;
762
-        }
763
-    }
764
-
765
-
766
-
767
-    /**
768
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
769
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
770
-     *
771
-     * @param string $relationName
772
-     * @throws \EE_Error
773
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
774
-     */
775
-    public function get_all_from_cache($relationName)
776
-    {
777
-        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
778
-        // if the result is not an array, but exists, make it an array
779
-        $objects = is_array($objects) ? $objects : array($objects);
780
-        //bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
781
-        //basically, if this model object was stored in the session, and these cached model objects
782
-        //already have IDs, let's make sure they're in their model's entity mapper
783
-        //otherwise we will have duplicates next time we call
784
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
785
-        $model = EE_Registry::instance()->load_model($relationName);
786
-        foreach ($objects as $model_object) {
787
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
788
-                //ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
789
-                if ($model_object->ID()) {
790
-                    $model->add_to_entity_map($model_object);
791
-                }
792
-            } else {
793
-                throw new EE_Error(
794
-                    sprintf(
795
-                        __(
796
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
797
-                            'event_espresso'
798
-                        ),
799
-                        $relationName,
800
-                        gettype($model_object)
801
-                    )
802
-                );
803
-            }
804
-        }
805
-        return $objects;
806
-    }
807
-
808
-
809
-
810
-    /**
811
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
812
-     * matching the given query conditions.
813
-     *
814
-     * @param null  $field_to_order_by  What field is being used as the reference point.
815
-     * @param int   $limit              How many objects to return.
816
-     * @param array $query_params       Any additional conditions on the query.
817
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
818
-     *                                  you can indicate just the columns you want returned
819
-     * @return array|EE_Base_Class[]
820
-     * @throws \EE_Error
821
-     */
822
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
823
-    {
824
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
825
-            ? $this->get_model()->get_primary_key_field()->get_name()
826
-            : $field_to_order_by;
827
-        $current_value = ! empty($field) ? $this->get($field) : null;
828
-        if (empty($field) || empty($current_value)) {
829
-            return array();
830
-        }
831
-        return $this->get_model()->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
832
-    }
833
-
834
-
835
-
836
-    /**
837
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
838
-     * matching the given query conditions.
839
-     *
840
-     * @param null  $field_to_order_by  What field is being used as the reference point.
841
-     * @param int   $limit              How many objects to return.
842
-     * @param array $query_params       Any additional conditions on the query.
843
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
844
-     *                                  you can indicate just the columns you want returned
845
-     * @return array|EE_Base_Class[]
846
-     * @throws \EE_Error
847
-     */
848
-    public function previous_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
849
-    {
850
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
851
-            ? $this->get_model()->get_primary_key_field()->get_name()
852
-            : $field_to_order_by;
853
-        $current_value = ! empty($field) ? $this->get($field) : null;
854
-        if (empty($field) || empty($current_value)) {
855
-            return array();
856
-        }
857
-        return $this->get_model()->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
858
-    }
859
-
860
-
861
-
862
-    /**
863
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
864
-     * matching the given query conditions.
865
-     *
866
-     * @param null  $field_to_order_by  What field is being used as the reference point.
867
-     * @param array $query_params       Any additional conditions on the query.
868
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
869
-     *                                  you can indicate just the columns you want returned
870
-     * @return array|EE_Base_Class
871
-     * @throws \EE_Error
872
-     */
873
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
874
-    {
875
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
876
-            ? $this->get_model()->get_primary_key_field()->get_name()
877
-            : $field_to_order_by;
878
-        $current_value = ! empty($field) ? $this->get($field) : null;
879
-        if (empty($field) || empty($current_value)) {
880
-            return array();
881
-        }
882
-        return $this->get_model()->next($current_value, $field, $query_params, $columns_to_select);
883
-    }
884
-
885
-
886
-
887
-    /**
888
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
889
-     * matching the given query conditions.
890
-     *
891
-     * @param null  $field_to_order_by  What field is being used as the reference point.
892
-     * @param array $query_params       Any additional conditions on the query.
893
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
894
-     *                                  you can indicate just the column you want returned
895
-     * @return array|EE_Base_Class
896
-     * @throws \EE_Error
897
-     */
898
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
899
-    {
900
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
901
-            ? $this->get_model()->get_primary_key_field()->get_name()
902
-            : $field_to_order_by;
903
-        $current_value = ! empty($field) ? $this->get($field) : null;
904
-        if (empty($field) || empty($current_value)) {
905
-            return array();
906
-        }
907
-        return $this->get_model()->previous($current_value, $field, $query_params, $columns_to_select);
908
-    }
909
-
910
-
911
-
912
-    /**
913
-     * Overrides parent because parent expects old models.
914
-     * This also doesn't do any validation, and won't work for serialized arrays
915
-     *
916
-     * @param string $field_name
917
-     * @param mixed  $field_value_from_db
918
-     * @throws \EE_Error
919
-     */
920
-    public function set_from_db($field_name, $field_value_from_db)
921
-    {
922
-        $field_obj = $this->get_model()->field_settings_for($field_name);
923
-        if ($field_obj instanceof EE_Model_Field_Base) {
924
-            //you would think the DB has no NULLs for non-null label fields right? wrong!
925
-            //eg, a CPT model object could have an entry in the posts table, but no
926
-            //entry in the meta table. Meaning that all its columns in the meta table
927
-            //are null! yikes! so when we find one like that, use defaults for its meta columns
928
-            if ($field_value_from_db === null) {
929
-                if ($field_obj->is_nullable()) {
930
-                    //if the field allows nulls, then let it be null
931
-                    $field_value = null;
932
-                } else {
933
-                    $field_value = $field_obj->get_default_value();
934
-                }
935
-            } else {
936
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
937
-            }
938
-            $this->_fields[$field_name] = $field_value;
939
-            $this->_clear_cached_property($field_name);
940
-        }
941
-    }
942
-
943
-
944
-
945
-    /**
946
-     * verifies that the specified field is of the correct type
947
-     *
948
-     * @param string $field_name
949
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
950
-     *                                (in cases where the same property may be used for different outputs
951
-     *                                - i.e. datetime, money etc.)
952
-     * @return mixed
953
-     * @throws \EE_Error
954
-     */
955
-    public function get($field_name, $extra_cache_ref = null)
956
-    {
957
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
958
-    }
959
-
960
-
961
-
962
-    /**
963
-     * This method simply returns the RAW unprocessed value for the given property in this class
964
-     *
965
-     * @param  string $field_name A valid fieldname
966
-     * @return mixed              Whatever the raw value stored on the property is.
967
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
968
-     */
969
-    public function get_raw($field_name)
970
-    {
971
-        $field_settings = $this->get_model()->field_settings_for($field_name);
972
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
973
-            ? $this->_fields[$field_name]->format('U')
974
-            : $this->_fields[$field_name];
975
-    }
976
-
977
-
978
-
979
-    /**
980
-     * This is used to return the internal DateTime object used for a field that is a
981
-     * EE_Datetime_Field.
982
-     *
983
-     * @param string $field_name               The field name retrieving the DateTime object.
984
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
985
-     * @throws \EE_Error
986
-     *                                         an error is set and false returned.  If the field IS an
987
-     *                                         EE_Datetime_Field and but the field value is null, then
988
-     *                                         just null is returned (because that indicates that likely
989
-     *                                         this field is nullable).
990
-     */
991
-    public function get_DateTime_object($field_name)
992
-    {
993
-        $field_settings = $this->get_model()->field_settings_for($field_name);
994
-        if ( ! $field_settings instanceof EE_Datetime_Field) {
995
-            EE_Error::add_error(
996
-                sprintf(
997
-                    __(
998
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
999
-                        'event_espresso'
1000
-                    ),
1001
-                    $field_name
1002
-                ),
1003
-                __FILE__,
1004
-                __FUNCTION__,
1005
-                __LINE__
1006
-            );
1007
-            return false;
1008
-        }
1009
-        return $this->_fields[$field_name];
1010
-    }
1011
-
1012
-
1013
-
1014
-    /**
1015
-     * To be used in template to immediately echo out the value, and format it for output.
1016
-     * Eg, should call stripslashes and whatnot before echoing
1017
-     *
1018
-     * @param string $field_name      the name of the field as it appears in the DB
1019
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1020
-     *                                (in cases where the same property may be used for different outputs
1021
-     *                                - i.e. datetime, money etc.)
1022
-     * @return void
1023
-     * @throws \EE_Error
1024
-     */
1025
-    public function e($field_name, $extra_cache_ref = null)
1026
-    {
1027
-        echo $this->get_pretty($field_name, $extra_cache_ref);
1028
-    }
1029
-
1030
-
1031
-
1032
-    /**
1033
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1034
-     * can be easily used as the value of form input.
1035
-     *
1036
-     * @param string $field_name
1037
-     * @return void
1038
-     * @throws \EE_Error
1039
-     */
1040
-    public function f($field_name)
1041
-    {
1042
-        $this->e($field_name, 'form_input');
1043
-    }
1044
-
1045
-
1046
-
1047
-    /**
1048
-     * @param string $field_name
1049
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1050
-     *                                (in cases where the same property may be used for different outputs
1051
-     *                                - i.e. datetime, money etc.)
1052
-     * @return mixed
1053
-     * @throws \EE_Error
1054
-     */
1055
-    public function get_pretty($field_name, $extra_cache_ref = null)
1056
-    {
1057
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1058
-    }
1059
-
1060
-
1061
-
1062
-    /**
1063
-     * This simply returns the datetime for the given field name
1064
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1065
-     * (and the equivalent e_date, e_time, e_datetime).
1066
-     *
1067
-     * @access   protected
1068
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1069
-     * @param string   $dt_frmt      valid datetime format used for date
1070
-     *                               (if '' then we just use the default on the field,
1071
-     *                               if NULL we use the last-used format)
1072
-     * @param string   $tm_frmt      Same as above except this is for time format
1073
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1074
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1075
-     * @return void|string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1076
-     *                               if field is not a valid dtt field, or void if echoing
1077
-     * @throws \EE_Error
1078
-     */
1079
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1080
-    {
1081
-        $in_dt_frmt = empty($dt_frmt) ? $this->_dt_frmt : $dt_frmt;
1082
-        $in_tm_frmt = empty($tm_frmt) ? $this->_tm_frmt : $tm_frmt;
1083
-        //validate field for datetime and returns field settings if valid.
1084
-        $field = $this->_get_dtt_field_settings($field_name);
1085
-        //clear cached property if either formats are not null.
1086
-        if ($dt_frmt !== null || $tm_frmt !== null) {
1087
-            $this->_clear_cached_property($field_name);
1088
-            //reset format properties because they are used in get()
1089
-            $this->_dt_frmt = $in_dt_frmt;
1090
-            $this->_tm_frmt = $in_tm_frmt;
1091
-        }
1092
-        if ($echo) {
1093
-            $field->set_pretty_date_format($in_dt_frmt);
1094
-        } else {
1095
-            $field->set_date_format($in_dt_frmt);
1096
-        }
1097
-        if ($echo) {
1098
-            $field->set_pretty_time_format($in_tm_frmt);
1099
-        } else {
1100
-            $field->set_time_format($in_tm_frmt);
1101
-        }
1102
-        //set timezone in field object
1103
-        $field->set_timezone($this->_timezone);
1104
-        //set the output returned
1105
-        switch ($date_or_time) {
1106
-            case 'D' :
1107
-                $field->set_date_time_output('date');
1108
-                break;
1109
-            case 'T' :
1110
-                $field->set_date_time_output('time');
1111
-                break;
1112
-            default :
1113
-                $field->set_date_time_output();
1114
-        }
1115
-        if ($echo) {
1116
-            $this->e($field_name, $date_or_time);
1117
-            return '';
1118
-        }
1119
-        return $this->get($field_name, $date_or_time);
1120
-    }
1121
-
1122
-
1123
-
1124
-    /**
1125
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the other echoes
1126
-     * the pretty value for dtt)
1127
-     *
1128
-     * @param  string $field_name name of model object datetime field holding the value
1129
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1130
-     * @return string            datetime value formatted
1131
-     * @throws \EE_Error
1132
-     */
1133
-    public function get_date($field_name, $format = null)
1134
-    {
1135
-        return $this->_get_datetime($field_name, $format, null, 'D');
1136
-    }
1137
-
1138
-
1139
-
1140
-    /**
1141
-     * @param      $field_name
1142
-     * @param null $format
1143
-     * @throws \EE_Error
1144
-     */
1145
-    public function e_date($field_name, $format = null)
1146
-    {
1147
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1148
-    }
1149
-
1150
-
1151
-
1152
-    /**
1153
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the other echoes
1154
-     * the pretty value for dtt)
1155
-     *
1156
-     * @param  string $field_name name of model object datetime field holding the value
1157
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1158
-     * @return string             datetime value formatted
1159
-     * @throws \EE_Error
1160
-     */
1161
-    public function get_time($field_name, $format = null)
1162
-    {
1163
-        return $this->_get_datetime($field_name, null, $format, 'T');
1164
-    }
1165
-
1166
-
1167
-
1168
-    /**
1169
-     * @param      $field_name
1170
-     * @param null $format
1171
-     * @throws \EE_Error
1172
-     */
1173
-    public function e_time($field_name, $format = null)
1174
-    {
1175
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1176
-    }
1177
-
1178
-
1179
-
1180
-    /**
1181
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the other
1182
-     * echoes the pretty value for dtt)
1183
-     *
1184
-     * @param  string $field_name name of model object datetime field holding the value
1185
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1186
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1187
-     * @return string             datetime value formatted
1188
-     * @throws \EE_Error
1189
-     */
1190
-    public function get_datetime($field_name, $dt_frmt = null, $tm_frmt = null)
1191
-    {
1192
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1193
-    }
1194
-
1195
-
1196
-
1197
-    /**
1198
-     * @param      $field_name
1199
-     * @param null $dt_frmt
1200
-     * @param null $tm_frmt
1201
-     * @throws \EE_Error
1202
-     */
1203
-    public function e_datetime($field_name, $dt_frmt = null, $tm_frmt = null)
1204
-    {
1205
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1206
-    }
1207
-
1208
-
1209
-
1210
-    /**
1211
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1212
-     *
1213
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1214
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format on the object will be used.
1215
-     * @return string Date and time string in set locale or false if no field exists for the given
1216
-     * @throws \EE_Error
1217
-     *                           field name.
1218
-     */
1219
-    public function get_i18n_datetime($field_name, $format = null)
1220
-    {
1221
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1222
-        return date_i18n(
1223
-            $format,
1224
-            EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1225
-        );
1226
-    }
1227
-
1228
-
1229
-
1230
-    /**
1231
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is thrown.
1232
-     *
1233
-     * @param  string $field_name The field name being checked
1234
-     * @throws EE_Error
1235
-     * @return EE_Datetime_Field
1236
-     */
1237
-    protected function _get_dtt_field_settings($field_name)
1238
-    {
1239
-        $field = $this->get_model()->field_settings_for($field_name);
1240
-        //check if field is dtt
1241
-        if ($field instanceof EE_Datetime_Field) {
1242
-            return $field;
1243
-        } else {
1244
-            throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1245
-                'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1246
-        }
1247
-    }
1248
-
1249
-
1250
-
1251
-
1252
-    /**
1253
-     * NOTE ABOUT BELOW:
1254
-     * These convenience date and time setters are for setting date and time independently.  In other words you might want to change the time on a datetime_field but leave the date the same (or vice versa).
1255
-     * IF on the other hand you want to set both date and time at the same time, you can just use the models default set($fieldname,$value) method and make sure you send the entire datetime value for setting.
1256
-     */
1257
-    /**
1258
-     * sets the time on a datetime property
1259
-     *
1260
-     * @access protected
1261
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1262
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1263
-     * @throws \EE_Error
1264
-     */
1265
-    protected function _set_time_for($time, $fieldname)
1266
-    {
1267
-        $this->_set_date_time('T', $time, $fieldname);
1268
-    }
1269
-
1270
-
1271
-
1272
-    /**
1273
-     * sets the date on a datetime property
1274
-     *
1275
-     * @access protected
1276
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1277
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1278
-     * @throws \EE_Error
1279
-     */
1280
-    protected function _set_date_for($date, $fieldname)
1281
-    {
1282
-        $this->_set_date_time('D', $date, $fieldname);
1283
-    }
1284
-
1285
-
1286
-
1287
-    /**
1288
-     * This takes care of setting a date or time independently on a given model object property. This method also verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1289
-     *
1290
-     * @access protected
1291
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1292
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1293
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a EE_Datetime_Field property)
1294
-     * @throws \EE_Error
1295
-     */
1296
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1297
-    {
1298
-        $field = $this->_get_dtt_field_settings($fieldname);
1299
-        $field->set_timezone($this->_timezone);
1300
-        $field->set_date_format($this->_dt_frmt);
1301
-        $field->set_time_format($this->_tm_frmt);
1302
-        switch ($what) {
1303
-            case 'T' :
1304
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1305
-                    $datetime_value,
1306
-                    $this->_fields[$fieldname]
1307
-                );
1308
-                break;
1309
-            case 'D' :
1310
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1311
-                    $datetime_value,
1312
-                    $this->_fields[$fieldname]
1313
-                );
1314
-                break;
1315
-            case 'B' :
1316
-                $this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1317
-                break;
1318
-        }
1319
-        $this->_clear_cached_property($fieldname);
1320
-    }
1321
-
1322
-
1323
-
1324
-    /**
1325
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different than the timezone set for the website.
1326
-     * NOTE, this currently only works well with methods that return values.  If you use it with methods that echo values the $_timestamp property may not get reset to its original value and that could lead to some unexpected results!
1327
-     *
1328
-     * @access public
1329
-     * @param string               $field_name This is the name of the field on the object that contains the date/time value being returned.
1330
-     * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1331
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1332
-     * @param string               $prepend    You can include something to prepend on the timestamp
1333
-     * @param string               $append     You can include something to append on the timestamp
1334
-     * @throws EE_Error
1335
-     * @return string timestamp
1336
-     */
1337
-    public function display_in_my_timezone($field_name, $callback = 'get_datetime', $args = null, $prepend = '', $append = '')
1338
-    {
1339
-        $timezone = EEH_DTT_Helper::get_timezone();
1340
-        if ($timezone === $this->_timezone) {
1341
-            return '';
1342
-        }
1343
-        $original_timezone = $this->_timezone;
1344
-        $this->set_timezone($timezone);
1345
-        $fn = (array)$field_name;
1346
-        $args = array_merge($fn, (array)$args);
1347
-        if ( ! method_exists($this, $callback)) {
1348
-            throw new EE_Error(
1349
-                sprintf(
1350
-                    __(
1351
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1352
-                        'event_espresso'
1353
-                    ),
1354
-                    $callback
1355
-                )
1356
-            );
1357
-        }
1358
-        $args = (array)$args;
1359
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1360
-        $this->set_timezone($original_timezone);
1361
-        return $return;
1362
-    }
1363
-
1364
-
1365
-
1366
-    /**
1367
-     * Deletes this model object.
1368
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should override
1369
-     * `EE_Base_Class::_delete` NOT this class.
1370
-     *
1371
-     * @return boolean | int
1372
-     * @throws \EE_Error
1373
-     */
1374
-    public function delete()
1375
-    {
1376
-        /**
1377
-         * Called just before the `EE_Base_Class::_delete` method call.
1378
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1379
-         * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1380
-         * soft deletes (trash) the object and does not permanently delete it.
1381
-         *
1382
-         * @param EE_Base_Class $model_object about to be 'deleted'
1383
-         */
1384
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1385
-        $result = $this->_delete();
1386
-        /**
1387
-         * Called just after the `EE_Base_Class::_delete` method call.
1388
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1389
-         * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1390
-         * soft deletes (trash) the object and does not permanently delete it.
1391
-         *
1392
-         * @param EE_Base_Class $model_object that was just 'deleted'
1393
-         * @param boolean       $result
1394
-         */
1395
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1396
-        return $result;
1397
-    }
1398
-
1399
-
1400
-
1401
-    /**
1402
-     * Calls the specific delete method for the instantiated class.
1403
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override default
1404
-     * functionality for "delete" (which is to call `permanently_delete`) should override this method NOT `EE_Base_Class::delete`
1405
-     *
1406
-     * @return bool|int
1407
-     * @throws \EE_Error
1408
-     */
1409
-    protected function _delete()
1410
-    {
1411
-        return $this->delete_permanently();
1412
-    }
1413
-
1414
-
1415
-
1416
-    /**
1417
-     * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an error)
1418
-     *
1419
-     * @return bool | int
1420
-     * @throws \EE_Error
1421
-     */
1422
-    public function delete_permanently()
1423
-    {
1424
-        /**
1425
-         * Called just before HARD deleting a model object
1426
-         *
1427
-         * @param EE_Base_Class $model_object about to be 'deleted'
1428
-         */
1429
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1430
-        $model = $this->get_model();
1431
-        $result = $model->delete_permanently_by_ID($this->ID());
1432
-        $this->refresh_cache_of_related_objects();
1433
-        /**
1434
-         * Called just after HARD deleting a model object
1435
-         *
1436
-         * @param EE_Base_Class $model_object that was just 'deleted'
1437
-         * @param boolean       $result
1438
-         */
1439
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1440
-        return $result;
1441
-    }
1442
-
1443
-
1444
-
1445
-    /**
1446
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1447
-     * related model objects
1448
-     *
1449
-     * @throws \EE_Error
1450
-     */
1451
-    public function refresh_cache_of_related_objects()
1452
-    {
1453
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1454
-            if ( ! empty($this->_model_relations[$relation_name])) {
1455
-                $related_objects = $this->_model_relations[$relation_name];
1456
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1457
-                    //this relation only stores a single model object, not an array
1458
-                    //but let's make it consistent
1459
-                    $related_objects = array($related_objects);
1460
-                }
1461
-                foreach ($related_objects as $related_object) {
1462
-                    //only refresh their cache if they're in memory
1463
-                    if ($related_object instanceof EE_Base_Class) {
1464
-                        $related_object->clear_cache($this->get_model()->get_this_model_name(), $this);
1465
-                    }
1466
-                }
1467
-            }
1468
-        }
1469
-    }
1470
-
1471
-
1472
-
1473
-    /**
1474
-     *        Saves this object to the database. An array may be supplied to set some values on this
1475
-     * object just before saving.
1476
-     *
1477
-     * @access public
1478
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1479
-     *                                 if provided during the save() method (often client code will change the fields' values before calling save)
1480
-     * @throws \EE_Error
1481
-     * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1482
-     *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1483
-     */
1484
-    public function save($set_cols_n_values = array())
1485
-    {
1486
-        /**
1487
-         * Filters the fields we're about to save on the model object
1488
-         *
1489
-         * @param array         $set_cols_n_values
1490
-         * @param EE_Base_Class $model_object
1491
-         */
1492
-        $set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values, $this);
1493
-        //set attributes as provided in $set_cols_n_values
1494
-        foreach ($set_cols_n_values as $column => $value) {
1495
-            $this->set($column, $value);
1496
-        }
1497
-        /**
1498
-         * Saving a model object.
1499
-         * Before we perform a save, this action is fired.
1500
-         *
1501
-         * @param EE_Base_Class $model_object the model object about to be saved.
1502
-         */
1503
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1504
-        if ( ! $this->allow_persist()) {
1505
-            return 0;
1506
-        }
1507
-        //now get current attribute values
1508
-        $save_cols_n_values = $this->_fields;
1509
-        //if the object already has an ID, update it. Otherwise, insert it
1510
-        //also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1511
-        $old_assumption_concerning_value_preparation = $this->get_model()->get_assumption_concerning_values_already_prepared_by_model_object();
1512
-        $this->get_model()->assume_values_already_prepared_by_model_object(true);
1513
-        //does this model have an autoincrement PK?
1514
-        if ($this->get_model()->has_primary_key_field()) {
1515
-            if ($this->get_model()->get_primary_key_field()->is_auto_increment()) {
1516
-                //ok check if it's set, if so: update; if not, insert
1517
-                if ( ! empty($save_cols_n_values[self::_get_primary_key_name(get_class($this))])) {
1518
-                    $results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1519
-                } else {
1520
-                    unset($save_cols_n_values[self::_get_primary_key_name(get_class($this))]);
1521
-                    $results = $this->get_model()->insert($save_cols_n_values);
1522
-                    if ($results) {
1523
-                        //if successful, set the primary key
1524
-                        //but don't use the normal SET method, because it will check if
1525
-                        //an item with the same ID exists in the mapper & db, then
1526
-                        //will find it in the db (because we just added it) and THAT object
1527
-                        //will get added to the mapper before we can add this one!
1528
-                        //but if we just avoid using the SET method, all that headache can be avoided
1529
-                        $pk_field_name = self::_get_primary_key_name(get_class($this));
1530
-                        $this->_fields[$pk_field_name] = $results;
1531
-                        $this->_clear_cached_property($pk_field_name);
1532
-                        $this->get_model()->add_to_entity_map($this);
1533
-                        $this->_update_cached_related_model_objs_fks();
1534
-                    }
1535
-                }
1536
-            } else {//PK is NOT auto-increment
1537
-                //so check if one like it already exists in the db
1538
-                if ($this->get_model()->exists_by_ID($this->ID())) {
1539
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1540
-                        throw new EE_Error(
1541
-                            sprintf(
1542
-                                __('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1543
-                                    'event_espresso'),
1544
-                                get_class($this),
1545
-                                get_class($this->get_model()) . '::instance()->add_to_entity_map()',
1546
-                                get_class($this->get_model()) . '::instance()->get_one_by_ID()',
1547
-                                '<br />'
1548
-                            )
1549
-                        );
1550
-                    }
1551
-                    $results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1552
-                } else {
1553
-                    $results = $this->get_model()->insert($save_cols_n_values);
1554
-                    $this->_update_cached_related_model_objs_fks();
1555
-                }
1556
-            }
1557
-        } else {//there is NO primary key
1558
-            $already_in_db = false;
1559
-            foreach ($this->get_model()->unique_indexes() as $index) {
1560
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1561
-                if ($this->get_model()->exists(array($uniqueness_where_params))) {
1562
-                    $already_in_db = true;
1563
-                }
1564
-            }
1565
-            if ($already_in_db) {
1566
-                $combined_pk_fields_n_values = array_intersect_key($save_cols_n_values, $this->get_model()->get_combined_primary_key_fields());
1567
-                $results = $this->get_model()->update($save_cols_n_values, $combined_pk_fields_n_values);
1568
-            } else {
1569
-                $results = $this->get_model()->insert($save_cols_n_values);
1570
-            }
1571
-        }
1572
-        //restore the old assumption about values being prepared by the model object
1573
-        $this->get_model()->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1574
-        /**
1575
-         * After saving the model object this action is called
1576
-         *
1577
-         * @param EE_Base_Class $model_object which was just saved
1578
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1579
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1580
-         */
1581
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1582
-        return $results;
1583
-    }
1584
-
1585
-
1586
-
1587
-    /**
1588
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1589
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB is consistent)
1590
-     * Especially useful in case we JUST added this model object ot the database
1591
-     * and we want to let its cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on
1592
-     * the transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether or not they exist in the DB (if they do, their DB records will be automatically updated)
1593
-     *
1594
-     * @return void
1595
-     * @throws \EE_Error
1596
-     */
1597
-    protected function _update_cached_related_model_objs_fks()
1598
-    {
1599
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1600
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1601
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1602
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1603
-                        $this->get_model()->get_this_model_name()
1604
-                    );
1605
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1606
-                    if ($related_model_obj_in_cache->ID()) {
1607
-                        $related_model_obj_in_cache->save();
1608
-                    }
1609
-                }
1610
-            }
1611
-        }
1612
-    }
1613
-
1614
-
1615
-
1616
-    /**
1617
-     * Saves this model object and its NEW cached relations to the database.
1618
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1619
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1620
-     * because otherwise, there's a potential for infinite looping of saving
1621
-     * Saves the cached related model objects, and ensures the relation between them
1622
-     * and this object and properly setup
1623
-     *
1624
-     * @return int ID of new model object on save; 0 on failure+
1625
-     * @throws \EE_Error
1626
-     */
1627
-    public function save_new_cached_related_model_objs()
1628
-    {
1629
-        //make sure this has been saved
1630
-        if ( ! $this->ID()) {
1631
-            $id = $this->save();
1632
-        } else {
1633
-            $id = $this->ID();
1634
-        }
1635
-        //now save all the NEW cached model objects  (ie they don't exist in the DB)
1636
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1637
-            if ($this->_model_relations[$relationName]) {
1638
-                //is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1639
-                //or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1640
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1641
-                    //add a relation to that relation type (which saves the appropriate thing in the process)
1642
-                    //but ONLY if it DOES NOT exist in the DB
1643
-                    /* @var $related_model_obj EE_Base_Class */
1644
-                    $related_model_obj = $this->_model_relations[$relationName];
1645
-                    //					if( ! $related_model_obj->ID()){
1646
-                    $this->_add_relation_to($related_model_obj, $relationName);
1647
-                    $related_model_obj->save_new_cached_related_model_objs();
1648
-                    //					}
1649
-                } else {
1650
-                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1651
-                        //add a relation to that relation type (which saves the appropriate thing in the process)
1652
-                        //but ONLY if it DOES NOT exist in the DB
1653
-                        //						if( ! $related_model_obj->ID()){
1654
-                        $this->_add_relation_to($related_model_obj, $relationName);
1655
-                        $related_model_obj->save_new_cached_related_model_objs();
1656
-                        //						}
1657
-                    }
1658
-                }
1659
-            }
1660
-        }
1661
-        return $id;
1662
-    }
1663
-
1664
-
1665
-
1666
-    /**
1667
-     * for getting a model while instantiated.
1668
-     *
1669
-     * @return \EEM_Base | \EEM_CPT_Base
1670
-     */
1671
-    public function get_model()
1672
-    {
1673
-        $modelName = self::_get_model_classname(get_class($this));
1674
-        return self::_get_model_instance_with_name($modelName, $this->_timezone);
1675
-    }
1676
-
1677
-
1678
-
1679
-    /**
1680
-     * @param $props_n_values
1681
-     * @param $classname
1682
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1683
-     * @throws \EE_Error
1684
-     */
1685
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1686
-    {
1687
-        //TODO: will not work for Term_Relationships because they have no PK!
1688
-        $primary_id_ref = self::_get_primary_key_name($classname);
1689
-        if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1690
-            $id = $props_n_values[$primary_id_ref];
1691
-            return self::_get_model($classname)->get_from_entity_map($id);
1692
-        }
1693
-        return false;
1694
-    }
1695
-
1696
-
1697
-
1698
-    /**
1699
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for the primary key (if present in incoming values).
1700
-     * If there is a key in the incoming array that matches the primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not we return false.
1701
-     *
1702
-     * @param  array  $props_n_values   incoming array of properties and their values
1703
-     * @param  string $classname        the classname of the child class
1704
-     * @param null    $timezone
1705
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
1706
-     *                                  date_format and the second value is the time format
1707
-     * @return mixed (EE_Base_Class|bool)
1708
-     * @throws \EE_Error
1709
-     */
1710
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1711
-    {
1712
-        $existing = null;
1713
-        if (self::_get_model($classname)->has_primary_key_field()) {
1714
-            $primary_id_ref = self::_get_primary_key_name($classname);
1715
-            if (array_key_exists($primary_id_ref, $props_n_values)
1716
-                && ! empty($props_n_values[$primary_id_ref])
1717
-            ) {
1718
-                $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1719
-                    $props_n_values[$primary_id_ref]
1720
-                );
1721
-            }
1722
-        } elseif (self::_get_model($classname, $timezone)->has_all_combined_primary_key_fields($props_n_values)) {
1723
-            //no primary key on this model, but there's still a matching item in the DB
1724
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1725
-                self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1726
-            );
1727
-        }
1728
-        if ($existing) {
1729
-            //set date formats if present before setting values
1730
-            if ( ! empty($date_formats) && is_array($date_formats)) {
1731
-                $existing->set_date_format($date_formats[0]);
1732
-                $existing->set_time_format($date_formats[1]);
1733
-            } else {
1734
-                //set default formats for date and time
1735
-                $existing->set_date_format(get_option('date_format'));
1736
-                $existing->set_time_format(get_option('time_format'));
1737
-            }
1738
-            foreach ($props_n_values as $property => $field_value) {
1739
-                $existing->set($property, $field_value);
1740
-            }
1741
-            return $existing;
1742
-        } else {
1743
-            return false;
1744
-        }
1745
-    }
1746
-
1747
-
1748
-
1749
-    /**
1750
-     * Gets the EEM_*_Model for this class
1751
-     *
1752
-     * @access public now, as this is more convenient
1753
-     * @param      $classname
1754
-     * @param null $timezone
1755
-     * @throws EE_Error
1756
-     * @return EEM_Base
1757
-     */
1758
-    protected static function _get_model($classname, $timezone = null)
1759
-    {
1760
-        //find model for this class
1761
-        if ( ! $classname) {
1762
-            throw new EE_Error(
1763
-                sprintf(
1764
-                    __(
1765
-                        "What were you thinking calling _get_model(%s)?? You need to specify the class name",
1766
-                        "event_espresso"
1767
-                    ),
1768
-                    $classname
1769
-                )
1770
-            );
1771
-        }
1772
-        $modelName = self::_get_model_classname($classname);
1773
-        return self::_get_model_instance_with_name($modelName, $timezone);
1774
-    }
1775
-
1776
-
1777
-
1778
-    /**
1779
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1780
-     *
1781
-     * @param string $model_classname
1782
-     * @param null   $timezone
1783
-     * @return EEM_Base
1784
-     */
1785
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1786
-    {
1787
-        $model_classname = str_replace('EEM_', '', $model_classname);
1788
-        $model = EE_Registry::instance()->load_model($model_classname);
1789
-        $model->set_timezone($timezone);
1790
-        return $model;
1791
-    }
1792
-
1793
-
1794
-
1795
-    /**
1796
-     * If a model name is provided (eg Registration), gets the model classname for that model.
1797
-     * Also works if a model class's classname is provided (eg EE_Registration).
1798
-     *
1799
-     * @param null $model_name
1800
-     * @return string like EEM_Attendee
1801
-     */
1802
-    private static function _get_model_classname($model_name = null)
1803
-    {
1804
-        if (strpos($model_name, "EE_") === 0) {
1805
-            $model_classname = str_replace("EE_", "EEM_", $model_name);
1806
-        } else {
1807
-            $model_classname = "EEM_" . $model_name;
1808
-        }
1809
-        return $model_classname;
1810
-    }
1811
-
1812
-
1813
-
1814
-    /**
1815
-     * returns the name of the primary key attribute
1816
-     *
1817
-     * @param null $classname
1818
-     * @throws EE_Error
1819
-     * @return string
1820
-     */
1821
-    protected static function _get_primary_key_name($classname = null)
1822
-    {
1823
-        if ( ! $classname) {
1824
-            throw new EE_Error(
1825
-                sprintf(
1826
-                    __("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
1827
-                    $classname
1828
-                )
1829
-            );
1830
-        }
1831
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
1832
-    }
1833
-
1834
-
1835
-
1836
-    /**
1837
-     * Gets the value of the primary key.
1838
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
1839
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value is.
1840
-     * Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
1841
-     *
1842
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
1843
-     * @throws \EE_Error
1844
-     */
1845
-    public function ID()
1846
-    {
1847
-        //now that we know the name of the variable, use a variable variable to get its value and return its
1848
-        if ($this->get_model()->has_primary_key_field()) {
1849
-            return $this->_fields[self::_get_primary_key_name(get_class($this))];
1850
-        } else {
1851
-            return $this->get_model()->get_index_primary_key_string($this->_fields);
1852
-        }
1853
-    }
1854
-
1855
-
1856
-
1857
-    /**
1858
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current model is related
1859
-     * to a group of events, the $relationName should be 'Event', and should be a key in the EE Model's $_model_relations array.
1860
-     * If this model object doesn't exist in the DB, just caches the related thing
1861
-     *
1862
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
1863
-     * @param string $relationName                     eg 'Events','Question',etc.
1864
-     *                                                 an attendee to a group, you also want to specify which role they will have in that group. So you would use this parameter to specify array('role-column-name'=>'role-id')
1865
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that allow you to further constrict the relation to being added.  However, keep in mind that the columns (keys) given must match
1866
-     *                                                 a column on the JOIN table and currently only the HABTM models accept these additional conditions.  Also remember that if an exact match isn't found for these extra cols/val pairs,
1867
-     *                                                 then a NEW row is created in the join table.
1868
-     * @param null   $cache_id
1869
-     * @throws EE_Error
1870
-     * @return EE_Base_Class the object the relation was added to
1871
-     */
1872
-    public function _add_relation_to($otherObjectModelObjectOrID, $relationName, $extra_join_model_fields_n_values = array(), $cache_id = null)
1873
-    {
1874
-        //if this thing exists in the DB, save the relation to the DB
1875
-        if ($this->ID()) {
1876
-            $otherObject = $this->get_model()->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName, $extra_join_model_fields_n_values);
1877
-            //clear cache so future get_many_related and get_first_related() return new results.
1878
-            $this->clear_cache($relationName, $otherObject, true);
1879
-            if ($otherObject instanceof EE_Base_Class) {
1880
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
1881
-            }
1882
-        } else {
1883
-            //this thing doesn't exist in the DB,  so just cache it
1884
-            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
1885
-                throw new EE_Error(sprintf(
1886
-                    __('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s', 'event_espresso'),
1887
-                    $otherObjectModelObjectOrID,
1888
-                    get_class($this)
1889
-                ));
1890
-            } else {
1891
-                $otherObject = $otherObjectModelObjectOrID;
1892
-            }
1893
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
1894
-        }
1895
-        if ($otherObject instanceof EE_Base_Class) {
1896
-            //fix the reciprocal relation too
1897
-            if ($otherObject->ID()) {
1898
-                //its saved so assumed relations exist in the DB, so we can just
1899
-                //clear the cache so future queries use the updated info in the DB
1900
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), null, true);
1901
-            } else {
1902
-                //it's not saved, so it caches relations like this
1903
-                $otherObject->cache($this->get_model()->get_this_model_name(), $this);
1904
-            }
1905
-        }
1906
-        return $otherObject;
1907
-    }
1908
-
1909
-
1910
-
1911
-    /**
1912
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current model is related
1913
-     * to a group of events, the $relationName should be 'Events', and should be a key in the EE Model's $_model_relations array.
1914
-     * If this model object doesn't exist in the DB, just removes the related thing from the cache
1915
-     *
1916
-     * @param mixed  $otherObjectModelObjectOrID
1917
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved to the DB yet
1918
-     * @param string $relationName
1919
-     * @param array  $where_query
1920
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the relation to being added.
1921
-     *                However, keep in mind that the columns (keys) given must match a column on the JOIN table
1922
-     *                and currently only the HABTM models accept these additional conditions.
1923
-     *                Also remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is created in the join table.
1924
-     * @return EE_Base_Class the relation was removed from
1925
-     * @throws \EE_Error
1926
-     */
1927
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
1928
-    {
1929
-        if ($this->ID()) {
1930
-            //if this exists in the DB, save the relation change to the DB too
1931
-            $otherObject = $this->get_model()->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName, $where_query);
1932
-            $this->clear_cache($relationName, $otherObject);
1933
-        } else {
1934
-            //this doesn't exist in the DB, just remove it from the cache
1935
-            $otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
1936
-        }
1937
-        if ($otherObject instanceof EE_Base_Class) {
1938
-            $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
1939
-        }
1940
-        return $otherObject;
1941
-    }
1942
-
1943
-
1944
-
1945
-    /**
1946
-     * Removes ALL the related things for the $relationName.
1947
-     *
1948
-     * @param string $relationName
1949
-     * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
1950
-     * @return EE_Base_Class
1951
-     * @throws \EE_Error
1952
-     */
1953
-    public function _remove_relations($relationName, $where_query_params = array())
1954
-    {
1955
-        if ($this->ID()) {
1956
-            //if this exists in the DB, save the relation change to the DB too
1957
-            $otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
1958
-            $this->clear_cache($relationName, null, true);
1959
-        } else {
1960
-            //this doesn't exist in the DB, just remove it from the cache
1961
-            $otherObjects = $this->clear_cache($relationName, null, true);
1962
-        }
1963
-        if (is_array($otherObjects)) {
1964
-            foreach ($otherObjects as $otherObject) {
1965
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
1966
-            }
1967
-        }
1968
-        return $otherObjects;
1969
-    }
1970
-
1971
-
1972
-
1973
-    /**
1974
-     * Gets all the related model objects of the specified type. Eg, if the current class if
1975
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
1976
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
1977
-     * because we want to get even deleted items etc.
1978
-     *
1979
-     * @param string $relationName key in the model's _model_relations array
1980
-     * @param array  $query_params like EEM_Base::get_all
1981
-     * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
1982
-     * @throws \EE_Error
1983
-     *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if you want IDs
1984
-     */
1985
-    public function get_many_related($relationName, $query_params = array())
1986
-    {
1987
-        if ($this->ID()) {
1988
-            //this exists in the DB, so get the related things from either the cache or the DB
1989
-            //if there are query parameters, forget about caching the related model objects.
1990
-            if ($query_params) {
1991
-                $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
1992
-            } else {
1993
-                //did we already cache the result of this query?
1994
-                $cached_results = $this->get_all_from_cache($relationName);
1995
-                if ( ! $cached_results) {
1996
-                    $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
1997
-                    //if no query parameters were passed, then we got all the related model objects
1998
-                    //for that relation. We can cache them then.
1999
-                    foreach ($related_model_objects as $related_model_object) {
2000
-                        $this->cache($relationName, $related_model_object);
2001
-                    }
2002
-                } else {
2003
-                    $related_model_objects = $cached_results;
2004
-                }
2005
-            }
2006
-        } else {
2007
-            //this doesn't exist in the DB, so just get the related things from the cache
2008
-            $related_model_objects = $this->get_all_from_cache($relationName);
2009
-        }
2010
-        return $related_model_objects;
2011
-    }
2012
-
2013
-
2014
-
2015
-    /**
2016
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2017
-     * unless otherwise specified in the $query_params
2018
-     *
2019
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2020
-     * @param array  $query_params   like EEM_Base::get_all's
2021
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2022
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger that by the setting $distinct to TRUE;
2023
-     * @return int
2024
-     */
2025
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2026
-    {
2027
-        return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2028
-    }
2029
-
2030
-
2031
-
2032
-    /**
2033
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2034
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2035
-     *
2036
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2037
-     * @param array  $query_params  like EEM_Base::get_all's
2038
-     * @param string $field_to_sum  name of field to count by.
2039
-     *                              By default, uses primary key (which doesn't make much sense, so you should probably change it)
2040
-     * @return int
2041
-     */
2042
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2043
-    {
2044
-        return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2045
-    }
2046
-
2047
-
2048
-
2049
-    /**
2050
-     * Gets the first (ie, one) related model object of the specified type.
2051
-     *
2052
-     * @param string $relationName key in the model's _model_relations array
2053
-     * @param array  $query_params like EEM_Base::get_all
2054
-     * @return EE_Base_Class (not an array, a single object)
2055
-     * @throws \EE_Error
2056
-     */
2057
-    public function get_first_related($relationName, $query_params = array())
2058
-    {
2059
-        if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2060
-            //if they've provided some query parameters, don't bother trying to cache the result
2061
-            //also make sure we're not caching the result of get_first_related
2062
-            //on a relation which should have an array of objects (because the cache might have an array of objects)
2063
-            if ($query_params || ! $this->get_model()->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2064
-                $related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2065
-            } else {
2066
-                //first, check if we've already cached the result of this query
2067
-                $cached_result = $this->get_one_from_cache($relationName);
2068
-                if ( ! $cached_result) {
2069
-                    $related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2070
-                    $this->cache($relationName, $related_model_object);
2071
-                } else {
2072
-                    $related_model_object = $cached_result;
2073
-                }
2074
-            }
2075
-        } else {
2076
-            $related_model_object = null;
2077
-            //this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2078
-            if ($this->get_model()->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2079
-                $related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2080
-            }
2081
-            //this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2082
-            if ( ! $related_model_object) {
2083
-                $related_model_object = $this->get_one_from_cache($relationName);
2084
-            }
2085
-        }
2086
-        return $related_model_object;
2087
-    }
2088
-
2089
-
2090
-
2091
-    /**
2092
-     * Does a delete on all related objects of type $relationName and removes
2093
-     * the current model object's relation to them. If they can't be deleted (because
2094
-     * of blocking related model objects) does nothing. If the related model objects are
2095
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2096
-     * If this model object doesn't exist yet in the DB, just removes its related things
2097
-     *
2098
-     * @param string $relationName
2099
-     * @param array  $query_params like EEM_Base::get_all's
2100
-     * @return int how many deleted
2101
-     * @throws \EE_Error
2102
-     */
2103
-    public function delete_related($relationName, $query_params = array())
2104
-    {
2105
-        if ($this->ID()) {
2106
-            $count = $this->get_model()->delete_related($this, $relationName, $query_params);
2107
-        } else {
2108
-            $count = count($this->get_all_from_cache($relationName));
2109
-            $this->clear_cache($relationName, null, true);
2110
-        }
2111
-        return $count;
2112
-    }
2113
-
2114
-
2115
-
2116
-    /**
2117
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2118
-     * the current model object's relation to them. If they can't be deleted (because
2119
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2120
-     * If the related thing isn't a soft-deletable model object, this function is identical
2121
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2122
-     *
2123
-     * @param string $relationName
2124
-     * @param array  $query_params like EEM_Base::get_all's
2125
-     * @return int how many deleted (including those soft deleted)
2126
-     * @throws \EE_Error
2127
-     */
2128
-    public function delete_related_permanently($relationName, $query_params = array())
2129
-    {
2130
-        if ($this->ID()) {
2131
-            $count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2132
-        } else {
2133
-            $count = count($this->get_all_from_cache($relationName));
2134
-        }
2135
-        $this->clear_cache($relationName, null, true);
2136
-        return $count;
2137
-    }
2138
-
2139
-
2140
-
2141
-    /**
2142
-     * is_set
2143
-     * Just a simple utility function children can use for checking if property exists
2144
-     *
2145
-     * @access  public
2146
-     * @param  string $field_name property to check
2147
-     * @return bool                              TRUE if existing,FALSE if not.
2148
-     */
2149
-    public function is_set($field_name)
2150
-    {
2151
-        return isset($this->_fields[$field_name]);
2152
-    }
2153
-
2154
-
2155
-
2156
-    /**
2157
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an EE_Error exception if they don't
2158
-     *
2159
-     * @param  mixed (string|array) $properties properties to check
2160
-     * @throws EE_Error
2161
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2162
-     */
2163
-    protected function _property_exists($properties)
2164
-    {
2165
-        foreach ((array)$properties as $property_name) {
2166
-            //first make sure this property exists
2167
-            if ( ! $this->_fields[$property_name]) {
2168
-                throw new EE_Error(
2169
-                    sprintf(
2170
-                        __(
2171
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2172
-                            'event_espresso'
2173
-                        ),
2174
-                        $property_name
2175
-                    )
2176
-                );
2177
-            }
2178
-        }
2179
-        return true;
2180
-    }
2181
-
2182
-
2183
-
2184
-    /**
2185
-     * This simply returns an array of model fields for this object
2186
-     *
2187
-     * @return array
2188
-     * @throws \EE_Error
2189
-     */
2190
-    public function model_field_array()
2191
-    {
2192
-        $fields = $this->get_model()->field_settings(false);
2193
-        $properties = array();
2194
-        //remove prepended underscore
2195
-        foreach ($fields as $field_name => $settings) {
2196
-            $properties[$field_name] = $this->get($field_name);
2197
-        }
2198
-        return $properties;
2199
-    }
2200
-
2201
-
2202
-
2203
-    /**
2204
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2205
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called (http://www.garfieldtech.com/blog/php-magic-call)
2206
-     * and passed the method's name and arguments.
2207
-     * Instead of requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that happen?)
2208
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg, filters_hook_espresso__EE_Answer__my_great_function)
2209
-     * and accepts 2 arguments: the object on which the function was called, and an array of the original arguments passed to the function. Whatever their callback function returns will be returned by this function.
2210
-     * Example: in functions.php (or in a plugin):
2211
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2212
-     * function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2213
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2214
-     *        return $previousReturnValue.$returnString;
2215
-     * }
2216
-     * require('EE_Answer.class.php');
2217
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2218
-     * echo $answer->my_callback('monkeys',100);
2219
-     * //will output "you called my_callback! and passed args:monkeys,100"
2220
-     *
2221
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2222
-     * @param array  $args       array of original arguments passed to the function
2223
-     * @throws EE_Error
2224
-     * @return mixed whatever the plugin which calls add_filter decides
2225
-     */
2226
-    public function __call($methodName, $args)
2227
-    {
2228
-        $className = get_class($this);
2229
-        $tagName = "FHEE__{$className}__{$methodName}";
2230
-        if ( ! has_filter($tagName)) {
2231
-            throw new EE_Error(
2232
-                sprintf(
2233
-                    __(
2234
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2235
-                        "event_espresso"
2236
-                    ),
2237
-                    $methodName,
2238
-                    $className,
2239
-                    $tagName
2240
-                )
2241
-            );
2242
-        }
2243
-        return apply_filters($tagName, null, $this, $args);
2244
-    }
2245
-
2246
-
2247
-
2248
-    /**
2249
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2250
-     * A $previous_value can be specified in case there are many meta rows with the same key
2251
-     *
2252
-     * @param string $meta_key
2253
-     * @param string $meta_value
2254
-     * @param string $previous_value
2255
-     * @return int records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2256
-     * @throws \EE_Error
2257
-     * NOTE: if the values haven't changed, returns 0
2258
-     */
2259
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2260
-    {
2261
-        $query_params = array(
2262
-            array(
2263
-                'EXM_key'  => $meta_key,
2264
-                'OBJ_ID'   => $this->ID(),
2265
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2266
-            ),
2267
-        );
2268
-        if ($previous_value !== null) {
2269
-            $query_params[0]['EXM_value'] = $meta_value;
2270
-        }
2271
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2272
-        if ( ! $existing_rows_like_that) {
2273
-            return $this->add_extra_meta($meta_key, $meta_value);
2274
-        } else {
2275
-            foreach ($existing_rows_like_that as $existing_row) {
2276
-                $existing_row->save(array('EXM_value' => $meta_value));
2277
-            }
2278
-            return count($existing_rows_like_that);
2279
-        }
2280
-    }
2281
-
2282
-
2283
-
2284
-    /**
2285
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2286
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2287
-     * extra meta row was entered, false if not
2288
-     *
2289
-     * @param string  $meta_key
2290
-     * @param string  $meta_value
2291
-     * @param boolean $unique
2292
-     * @return boolean
2293
-     * @throws \EE_Error
2294
-     */
2295
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2296
-    {
2297
-        if ($unique) {
2298
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2299
-                array(
2300
-                    array(
2301
-                        'EXM_key'  => $meta_key,
2302
-                        'OBJ_ID'   => $this->ID(),
2303
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2304
-                    ),
2305
-                )
2306
-            );
2307
-            if ($existing_extra_meta) {
2308
-                return false;
2309
-            }
2310
-        }
2311
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2312
-            array(
2313
-                'EXM_key'   => $meta_key,
2314
-                'EXM_value' => $meta_value,
2315
-                'OBJ_ID'    => $this->ID(),
2316
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2317
-            )
2318
-        );
2319
-        $new_extra_meta->save();
2320
-        return true;
2321
-    }
2322
-
2323
-
2324
-
2325
-    /**
2326
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2327
-     * is specified, only deletes extra meta records with that value.
2328
-     *
2329
-     * @param string $meta_key
2330
-     * @param string $meta_value
2331
-     * @return int number of extra meta rows deleted
2332
-     * @throws \EE_Error
2333
-     */
2334
-    public function delete_extra_meta($meta_key, $meta_value = null)
2335
-    {
2336
-        $query_params = array(
2337
-            array(
2338
-                'EXM_key'  => $meta_key,
2339
-                'OBJ_ID'   => $this->ID(),
2340
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2341
-            ),
2342
-        );
2343
-        if ($meta_value !== null) {
2344
-            $query_params[0]['EXM_value'] = $meta_value;
2345
-        }
2346
-        return EEM_Extra_Meta::instance()->delete($query_params);
2347
-    }
2348
-
2349
-
2350
-
2351
-    /**
2352
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2353
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2354
-     * You can specify $default is case you haven't found the extra meta
2355
-     *
2356
-     * @param string  $meta_key
2357
-     * @param boolean $single
2358
-     * @param mixed   $default if we don't find anything, what should we return?
2359
-     * @return mixed single value if $single; array if ! $single
2360
-     * @throws \EE_Error
2361
-     */
2362
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2363
-    {
2364
-        if ($single) {
2365
-            $result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2366
-            if ($result instanceof EE_Extra_Meta) {
2367
-                return $result->value();
2368
-            } else {
2369
-                return $default;
2370
-            }
2371
-        } else {
2372
-            $results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2373
-            if ($results) {
2374
-                $values = array();
2375
-                foreach ($results as $result) {
2376
-                    if ($result instanceof EE_Extra_Meta) {
2377
-                        $values[$result->ID()] = $result->value();
2378
-                    }
2379
-                }
2380
-                return $values;
2381
-            } else {
2382
-                return $default;
2383
-            }
2384
-        }
2385
-    }
2386
-
2387
-
2388
-
2389
-    /**
2390
-     * Returns a simple array of all the extra meta associated with this model object.
2391
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2392
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2393
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2394
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2395
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2396
-     * finally the extra meta's value as each sub-value. (eg array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2397
-     *
2398
-     * @param boolean $one_of_each_key
2399
-     * @return array
2400
-     * @throws \EE_Error
2401
-     */
2402
-    public function all_extra_meta_array($one_of_each_key = true)
2403
-    {
2404
-        $return_array = array();
2405
-        if ($one_of_each_key) {
2406
-            $extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2407
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2408
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2409
-                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2410
-                }
2411
-            }
2412
-        } else {
2413
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2414
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2415
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2416
-                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2417
-                        $return_array[$extra_meta_obj->key()] = array();
2418
-                    }
2419
-                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2420
-                }
2421
-            }
2422
-        }
2423
-        return $return_array;
2424
-    }
2425
-
2426
-
2427
-
2428
-    /**
2429
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2430
-     *
2431
-     * @return string
2432
-     * @throws \EE_Error
2433
-     */
2434
-    public function name()
2435
-    {
2436
-        //find a field that's not a text field
2437
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2438
-        if ($field_we_can_use) {
2439
-            return $this->get($field_we_can_use->get_name());
2440
-        } else {
2441
-            $first_few_properties = $this->model_field_array();
2442
-            $first_few_properties = array_slice($first_few_properties, 0, 3);
2443
-            $name_parts = array();
2444
-            foreach ($first_few_properties as $name => $value) {
2445
-                $name_parts[] = "$name:$value";
2446
-            }
2447
-            return implode(",", $name_parts);
2448
-        }
2449
-    }
2450
-
2451
-
2452
-
2453
-    /**
2454
-     * in_entity_map
2455
-     * Checks if this model object has been proven to already be in the entity map
2456
-     *
2457
-     * @return boolean
2458
-     * @throws \EE_Error
2459
-     */
2460
-    public function in_entity_map()
2461
-    {
2462
-        if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2463
-            //well, if we looked, did we find it in the entity map?
2464
-            return true;
2465
-        } else {
2466
-            return false;
2467
-        }
2468
-    }
2469
-
2470
-
2471
-
2472
-    /**
2473
-     * refresh_from_db
2474
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
2475
-     *
2476
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2477
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2478
-     */
2479
-    public function refresh_from_db()
2480
-    {
2481
-        if ($this->ID() && $this->in_entity_map()) {
2482
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
2483
-        } else {
2484
-            //if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2485
-            //if it has an ID but it's not in the map, and you're asking me to refresh it
2486
-            //that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2487
-            //absolutely nothing in it for this ID
2488
-            if (WP_DEBUG) {
2489
-                throw new EE_Error(
2490
-                    sprintf(
2491
-                        __('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2492
-                            'event_espresso'),
2493
-                        $this->ID(),
2494
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2495
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2496
-                    )
2497
-                );
2498
-            }
2499
-        }
2500
-    }
2501
-
2502
-
2503
-
2504
-    /**
2505
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2506
-     * (probably a bad assumption they have made, oh well)
2507
-     *
2508
-     * @return string
2509
-     */
2510
-    public function __toString()
2511
-    {
2512
-        try {
2513
-            return sprintf('%s (%s)', $this->name(), $this->ID());
2514
-        } catch (Exception $e) {
2515
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2516
-            return '';
2517
-        }
2518
-    }
2519
-
2520
-
2521
-
2522
-    /**
2523
-     * Clear related model objects if they're already in the DB, because otherwise when we
2524
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
2525
-     * This means if we have made changes to those related model objects, and want to unserialize
2526
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
2527
-     * Instead, those related model objects should be directly serialized and stored.
2528
-     * Eg, the following won't work:
2529
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2530
-     * $att = $reg->attendee();
2531
-     * $att->set( 'ATT_fname', 'Dirk' );
2532
-     * update_option( 'my_option', serialize( $reg ) );
2533
-     * //END REQUEST
2534
-     * //START NEXT REQUEST
2535
-     * $reg = get_option( 'my_option' );
2536
-     * $reg->attendee()->save();
2537
-     * And would need to be replace with:
2538
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2539
-     * $att = $reg->attendee();
2540
-     * $att->set( 'ATT_fname', 'Dirk' );
2541
-     * update_option( 'my_option', serialize( $reg ) );
2542
-     * //END REQUEST
2543
-     * //START NEXT REQUEST
2544
-     * $att = get_option( 'my_option' );
2545
-     * $att->save();
2546
-     *
2547
-     * @return array
2548
-     * @throws \EE_Error
2549
-     */
2550
-    public function __sleep()
2551
-    {
2552
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
2553
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
2554
-                $classname = 'EE_' . $this->get_model()->get_this_model_name();
2555
-                if (
2556
-                    $this->get_one_from_cache($relation_name) instanceof $classname
2557
-                    && $this->get_one_from_cache($relation_name)->ID()
2558
-                ) {
2559
-                    $this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2560
-                }
2561
-            }
2562
-        }
2563
-        $this->_props_n_values_provided_in_constructor = array();
2564
-        return array_keys(get_object_vars($this));
2565
-    }
2566
-
2567
-
2568
-
2569
-    /**
2570
-     * restore _props_n_values_provided_in_constructor
2571
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2572
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
2573
-     * At best, you would only be able to detect if state change has occurred during THIS request.
2574
-     */
2575
-    public function __wakeup()
2576
-    {
2577
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
2578
-    }
28
+	/**
29
+	 * This is an array of the original properties and values provided during construction
30
+	 * of this model object. (keys are model field names, values are their values).
31
+	 * This list is important to remember so that when we are merging data from the db, we know
32
+	 * which values to override and which to not override.
33
+	 *
34
+	 * @var array
35
+	 */
36
+	protected $_props_n_values_provided_in_constructor;
37
+
38
+	/**
39
+	 * Timezone
40
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.  This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT all
41
+	 * EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have access to it.
42
+	 *
43
+	 * @var string
44
+	 */
45
+	protected $_timezone;
46
+
47
+
48
+
49
+	/**
50
+	 * date format
51
+	 * pattern or format for displaying dates
52
+	 *
53
+	 * @var string $_dt_frmt
54
+	 */
55
+	protected $_dt_frmt;
56
+
57
+
58
+
59
+	/**
60
+	 * time format
61
+	 * pattern or format for displaying time
62
+	 *
63
+	 * @var string $_tm_frmt
64
+	 */
65
+	protected $_tm_frmt;
66
+
67
+
68
+
69
+	/**
70
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
71
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having to recalculate.
72
+	 * Used by _set_cached_property() and _get_cached_property() methods.
73
+	 *
74
+	 * @var array
75
+	 */
76
+	protected $_cached_properties = array();
77
+
78
+	/**
79
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a single
80
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the relation
81
+	 * is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object, all others have an array)
82
+	 *
83
+	 * @var array
84
+	 */
85
+	protected $_model_relations = array();
86
+
87
+	/**
88
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
89
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
90
+	 *
91
+	 * @var array
92
+	 */
93
+	protected $_fields = array();
94
+
95
+	/**
96
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
97
+	 * For example, we might create model objects intended to only be used for the duration
98
+	 * of this request and to be thrown away, and if they were accidentally saved
99
+	 * it would be a bug.
100
+	 */
101
+	protected $_allow_persist = true;
102
+
103
+
104
+
105
+	/**
106
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children play nice
107
+	 *
108
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd layer of the model's _fields array, (eg, EVT_ID, TXN_amount, QST_name, etc) and values are their values
109
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the corresponding db model or not.
110
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to be in when instantiating a EE_Base_Class object.
111
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
112
+	 *                                                         value is the date_format and second value is the time
113
+	 *                                                         format.
114
+	 * @throws EE_Error
115
+	 */
116
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
117
+	{
118
+		$className = get_class($this);
119
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
120
+		$model = $this->get_model();
121
+		$model_fields = $model->field_settings(false);
122
+		// ensure $fieldValues is an array
123
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
124
+		// EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
125
+		// verify client code has not passed any invalid field names
126
+		foreach ($fieldValues as $field_name => $field_value) {
127
+			if ( ! isset($model_fields[$field_name])) {
128
+				throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s", "event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
129
+			}
130
+		}
131
+		// EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
132
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
133
+		if ( ! empty($date_formats) && is_array($date_formats)) {
134
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
135
+		} else {
136
+			//set default formats for date and time
137
+			$this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
138
+			$this->_tm_frmt = (string)get_option('time_format', 'g:i a');
139
+		}
140
+		//if db model is instantiating
141
+		if ($bydb) {
142
+			//client code has indicated these field values are from the database
143
+			foreach ($model_fields as $fieldName => $field) {
144
+				$this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
145
+			}
146
+		} else {
147
+			//we're constructing a brand
148
+			//new instance of the model object. Generally, this means we'll need to do more field validation
149
+			foreach ($model_fields as $fieldName => $field) {
150
+				$this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
151
+			}
152
+		}
153
+		//remember what values were passed to this constructor
154
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
155
+		//remember in entity mapper
156
+		if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
157
+			$model->add_to_entity_map($this);
158
+		}
159
+		//setup all the relations
160
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
161
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
162
+				$this->_model_relations[$relation_name] = null;
163
+			} else {
164
+				$this->_model_relations[$relation_name] = array();
165
+			}
166
+		}
167
+		/**
168
+		 * Action done at the end of each model object construction
169
+		 *
170
+		 * @param EE_Base_Class $this the model object just created
171
+		 */
172
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
173
+	}
174
+
175
+
176
+
177
+	/**
178
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
179
+	 *
180
+	 * @return boolean
181
+	 */
182
+	public function allow_persist()
183
+	{
184
+		return $this->_allow_persist;
185
+	}
186
+
187
+
188
+
189
+	/**
190
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
191
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
192
+	 * you got new information that somehow made you change your mind.
193
+	 *
194
+	 * @param boolean $allow_persist
195
+	 * @return boolean
196
+	 */
197
+	public function set_allow_persist($allow_persist)
198
+	{
199
+		return $this->_allow_persist = $allow_persist;
200
+	}
201
+
202
+
203
+
204
+	/**
205
+	 * Gets the field's original value when this object was constructed during this request.
206
+	 * This can be helpful when determining if a model object has changed or not
207
+	 *
208
+	 * @param string $field_name
209
+	 * @return mixed|null
210
+	 * @throws \EE_Error
211
+	 */
212
+	public function get_original($field_name)
213
+	{
214
+		if (isset($this->_props_n_values_provided_in_constructor[$field_name])
215
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
216
+		) {
217
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
218
+		} else {
219
+			return null;
220
+		}
221
+	}
222
+
223
+
224
+
225
+	/**
226
+	 * @param EE_Base_Class $obj
227
+	 * @return string
228
+	 */
229
+	public function get_class($obj)
230
+	{
231
+		return get_class($obj);
232
+	}
233
+
234
+
235
+
236
+	/**
237
+	 * Overrides parent because parent expects old models.
238
+	 * This also doesn't do any validation, and won't work for serialized arrays
239
+	 *
240
+	 * @param    string $field_name
241
+	 * @param    mixed  $field_value
242
+	 * @param bool      $use_default
243
+	 * @throws \EE_Error
244
+	 */
245
+	public function set($field_name, $field_value, $use_default = false)
246
+	{
247
+		$field_obj = $this->get_model()->field_settings_for($field_name);
248
+		if ($field_obj instanceof EE_Model_Field_Base) {
249
+			//			if ( method_exists( $field_obj, 'set_timezone' )) {
250
+			if ($field_obj instanceof EE_Datetime_Field) {
251
+				$field_obj->set_timezone($this->_timezone);
252
+				$field_obj->set_date_format($this->_dt_frmt);
253
+				$field_obj->set_time_format($this->_tm_frmt);
254
+			}
255
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
256
+			//should the value be null?
257
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
258
+				$this->_fields[$field_name] = $field_obj->get_default_value();
259
+				/**
260
+				 * To save having to refactor all the models, if a default value is used for a
261
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
262
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
263
+				 * object.
264
+				 *
265
+				 * @since 4.6.10+
266
+				 */
267
+				if (
268
+					$field_obj instanceof EE_Datetime_Field
269
+					&& $this->_fields[$field_name] !== null
270
+					&& ! $this->_fields[$field_name] instanceof DateTime
271
+				) {
272
+					empty($this->_fields[$field_name])
273
+						? $this->set($field_name, time())
274
+						: $this->set($field_name, $this->_fields[$field_name]);
275
+				}
276
+			} else {
277
+				$this->_fields[$field_name] = $holder_of_value;
278
+			}
279
+			//if we're not in the constructor...
280
+			//now check if what we set was a primary key
281
+			if (
282
+				//note: props_n_values_provided_in_constructor is only set at the END of the constructor
283
+				$this->_props_n_values_provided_in_constructor
284
+				&& $field_value
285
+				&& $field_name === self::_get_primary_key_name(get_class($this))
286
+			) {
287
+				//if so, we want all this object's fields to be filled either with
288
+				//what we've explicitly set on this model
289
+				//or what we have in the db
290
+				// echo "setting primary key!";
291
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
292
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
293
+				foreach ($fields_on_model as $field_obj) {
294
+					if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
295
+						 && $field_obj->get_name() !== $field_name
296
+					) {
297
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
298
+					}
299
+				}
300
+				//oh this model object has an ID? well make sure its in the entity mapper
301
+				$this->get_model()->add_to_entity_map($this);
302
+			}
303
+			//let's unset any cache for this field_name from the $_cached_properties property.
304
+			$this->_clear_cached_property($field_name);
305
+		} else {
306
+			throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s", "event_espresso"), $field_name));
307
+		}
308
+	}
309
+
310
+
311
+
312
+	/**
313
+	 * This sets the field value on the db column if it exists for the given $column_name or
314
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
315
+	 *
316
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
317
+	 * @param string $field_name  Must be the exact column name.
318
+	 * @param mixed  $field_value The value to set.
319
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
320
+	 * @throws \EE_Error
321
+	 */
322
+	public function set_field_or_extra_meta($field_name, $field_value)
323
+	{
324
+		if ($this->get_model()->has_field($field_name)) {
325
+			$this->set($field_name, $field_value);
326
+			return true;
327
+		} else {
328
+			//ensure this object is saved first so that extra meta can be properly related.
329
+			$this->save();
330
+			return $this->update_extra_meta($field_name, $field_value);
331
+		}
332
+	}
333
+
334
+
335
+
336
+	/**
337
+	 * This retrieves the value of the db column set on this class or if that's not present
338
+	 * it will attempt to retrieve from extra_meta if found.
339
+	 * Example Usage:
340
+	 * Via EE_Message child class:
341
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
342
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
343
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
344
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
345
+	 * value for those extra fields dynamically via the EE_message object.
346
+	 *
347
+	 * @param  string $field_name expecting the fully qualified field name.
348
+	 * @return mixed|null  value for the field if found.  null if not found.
349
+	 * @throws \EE_Error
350
+	 */
351
+	public function get_field_or_extra_meta($field_name)
352
+	{
353
+		if ($this->get_model()->has_field($field_name)) {
354
+			$column_value = $this->get($field_name);
355
+		} else {
356
+			//This isn't a column in the main table, let's see if it is in the extra meta.
357
+			$column_value = $this->get_extra_meta($field_name, true, null);
358
+		}
359
+		return $column_value;
360
+	}
361
+
362
+
363
+
364
+	/**
365
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally for being able to reference what timezone we are running conversions on when converting TO the internal timezone (UTC
366
+	 * Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is available to all child classes that may be using the EE_Datetime_Field for a field data type.
367
+	 *
368
+	 * @access public
369
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
370
+	 * @return void
371
+	 * @throws \EE_Error
372
+	 */
373
+	public function set_timezone($timezone = '')
374
+	{
375
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
376
+		//make sure we clear all cached properties because they won't be relevant now
377
+		$this->_clear_cached_properties();
378
+		//make sure we update field settings and the date for all EE_Datetime_Fields
379
+		$model_fields = $this->get_model()->field_settings(false);
380
+		foreach ($model_fields as $field_name => $field_obj) {
381
+			if ($field_obj instanceof EE_Datetime_Field) {
382
+				$field_obj->set_timezone($this->_timezone);
383
+				if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
384
+					$this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
385
+				}
386
+			}
387
+		}
388
+	}
389
+
390
+
391
+
392
+	/**
393
+	 * This just returns whatever is set for the current timezone.
394
+	 *
395
+	 * @access public
396
+	 * @return string timezone string
397
+	 */
398
+	public function get_timezone()
399
+	{
400
+		return $this->_timezone;
401
+	}
402
+
403
+
404
+
405
+	/**
406
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
407
+	 * internally instead of wp set date format options
408
+	 *
409
+	 * @since 4.6
410
+	 * @param string $format should be a format recognizable by PHP date() functions.
411
+	 */
412
+	public function set_date_format($format)
413
+	{
414
+		$this->_dt_frmt = $format;
415
+		//clear cached_properties because they won't be relevant now.
416
+		$this->_clear_cached_properties();
417
+	}
418
+
419
+
420
+
421
+	/**
422
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
423
+	 * class internally instead of wp set time format options.
424
+	 *
425
+	 * @since 4.6
426
+	 * @param string $format should be a format recognizable by PHP date() functions.
427
+	 */
428
+	public function set_time_format($format)
429
+	{
430
+		$this->_tm_frmt = $format;
431
+		//clear cached_properties because they won't be relevant now.
432
+		$this->_clear_cached_properties();
433
+	}
434
+
435
+
436
+
437
+	/**
438
+	 * This returns the current internal set format for the date and time formats.
439
+	 *
440
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array where the
441
+	 *                             first value is the date format and the second value is the time format.
442
+	 * @return mixed string|array
443
+	 */
444
+	public function get_format($full = true)
445
+	{
446
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
447
+	}
448
+
449
+
450
+
451
+	/**
452
+	 * cache
453
+	 * stores the passed model object on the current model object.
454
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
455
+	 *
456
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg 'Registration' associated with this model object
457
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction, that could be a payment or a registration)
458
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many items which will be stored in an array on this object
459
+	 * @throws EE_Error
460
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one related thing, no array)
461
+	 */
462
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
463
+	{
464
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
465
+		if ( ! $object_to_cache instanceof EE_Base_Class) {
466
+			return false;
467
+		}
468
+		// also get "how" the object is related, or throw an error
469
+		if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
470
+			throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'), $relationName, get_class($this)));
471
+		}
472
+		// how many things are related ?
473
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
474
+			// if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
475
+			// so for these model objects just set it to be cached
476
+			$this->_model_relations[$relationName] = $object_to_cache;
477
+			$return = true;
478
+		} else {
479
+			// otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
480
+			// eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
481
+			if ( ! is_array($this->_model_relations[$relationName])) {
482
+				// if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
483
+				$this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class ? array($this->_model_relations[$relationName]) : array();
484
+			}
485
+			// first check for a cache_id which is normally empty
486
+			if ( ! empty($cache_id)) {
487
+				// if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
488
+				$this->_model_relations[$relationName][$cache_id] = $object_to_cache;
489
+				$return = $cache_id;
490
+			} elseif ($object_to_cache->ID()) {
491
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
492
+				$this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
493
+				$return = $object_to_cache->ID();
494
+			} else {
495
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
496
+				$this->_model_relations[$relationName][] = $object_to_cache;
497
+				// move the internal pointer to the end of the array
498
+				end($this->_model_relations[$relationName]);
499
+				// and grab the key so that we can return it
500
+				$return = key($this->_model_relations[$relationName]);
501
+			}
502
+		}
503
+		return $return;
504
+	}
505
+
506
+
507
+
508
+	/**
509
+	 * For adding an item to the cached_properties property.
510
+	 *
511
+	 * @access protected
512
+	 * @param string      $fieldname the property item the corresponding value is for.
513
+	 * @param mixed       $value     The value we are caching.
514
+	 * @param string|null $cache_type
515
+	 * @return void
516
+	 * @throws \EE_Error
517
+	 */
518
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
519
+	{
520
+		//first make sure this property exists
521
+		$this->get_model()->field_settings_for($fieldname);
522
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
523
+		$this->_cached_properties[$fieldname][$cache_type] = $value;
524
+	}
525
+
526
+
527
+
528
+	/**
529
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
530
+	 * This also SETS the cache if we return the actual property!
531
+	 *
532
+	 * @param string $fieldname        the name of the property we're trying to retrieve
533
+	 * @param bool   $pretty
534
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
535
+	 *                                 (in cases where the same property may be used for different outputs
536
+	 *                                 - i.e. datetime, money etc.)
537
+	 *                                 It can also accept certain pre-defined "schema" strings
538
+	 *                                 to define how to output the property.
539
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
540
+	 * @return mixed                   whatever the value for the property is we're retrieving
541
+	 * @throws \EE_Error
542
+	 */
543
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
544
+	{
545
+		//verify the field exists
546
+		$this->get_model()->field_settings_for($fieldname);
547
+		$cache_type = $pretty ? 'pretty' : 'standard';
548
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
549
+		if (isset($this->_cached_properties[$fieldname][$cache_type])) {
550
+			return $this->_cached_properties[$fieldname][$cache_type];
551
+		}
552
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
553
+		if ($field_obj instanceof EE_Model_Field_Base) {
554
+			/**
555
+			 * maybe this is EE_Datetime_Field.  If so we need to make sure timezone and
556
+			 * formats are correct.
557
+			 */
558
+			if ($field_obj instanceof EE_Datetime_Field) {
559
+				$field_obj->set_timezone($this->_timezone);
560
+				$field_obj->set_date_format($this->_dt_frmt, $pretty);
561
+				$field_obj->set_time_format($this->_tm_frmt, $pretty);
562
+			}
563
+			if ( ! isset($this->_fields[$fieldname])) {
564
+				$this->_fields[$fieldname] = null;
565
+			}
566
+			$value = $pretty
567
+				? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
568
+				: $field_obj->prepare_for_get($this->_fields[$fieldname]);
569
+			$this->_set_cached_property($fieldname, $value, $cache_type);
570
+			return $value;
571
+		}
572
+		return null;
573
+	}
574
+
575
+
576
+
577
+	/**
578
+	 * This just takes care of clearing out the cached_properties
579
+	 *
580
+	 * @return void
581
+	 */
582
+	protected function _clear_cached_properties()
583
+	{
584
+		$this->_cached_properties = array();
585
+	}
586
+
587
+
588
+
589
+	/**
590
+	 * This just clears out ONE property if it exists in the cache
591
+	 *
592
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
593
+	 * @return void
594
+	 */
595
+	protected function _clear_cached_property($property_name)
596
+	{
597
+		if (isset($this->_cached_properties[$property_name])) {
598
+			unset($this->_cached_properties[$property_name]);
599
+		}
600
+	}
601
+
602
+
603
+
604
+	/**
605
+	 * Ensures that this related thing is a model object.
606
+	 *
607
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
608
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
609
+	 * @return EE_Base_Class
610
+	 * @throws \EE_Error
611
+	 */
612
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
613
+	{
614
+		$other_model_instance = self::_get_model_instance_with_name(
615
+			self::_get_model_classname($model_name),
616
+			$this->_timezone
617
+		);
618
+		return $other_model_instance->ensure_is_obj($object_or_id);
619
+	}
620
+
621
+
622
+
623
+	/**
624
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
625
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
626
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
627
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
628
+	 *
629
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model. Eg 'Registration'
630
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
631
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only has 1 object anyways (ie, it's a BelongsToRelation)
632
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if this is HasMany or HABTM.
633
+	 * @throws EE_Error
634
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a relation from all
635
+	 */
636
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
637
+	{
638
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
639
+		$index_in_cache = '';
640
+		if ( ! $relationship_to_model) {
641
+			throw new EE_Error(
642
+				sprintf(
643
+					__("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
644
+					$relationName,
645
+					get_class($this)
646
+				)
647
+			);
648
+		}
649
+		if ($clear_all) {
650
+			$obj_removed = true;
651
+			$this->_model_relations[$relationName] = null;
652
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
653
+			$obj_removed = $this->_model_relations[$relationName];
654
+			$this->_model_relations[$relationName] = null;
655
+		} else {
656
+			if ($object_to_remove_or_index_into_array instanceof EE_Base_Class && $object_to_remove_or_index_into_array->ID()) {
657
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
658
+				if (is_array($this->_model_relations[$relationName]) && ! isset($this->_model_relations[$relationName][$index_in_cache])) {
659
+					$index_found_at = null;
660
+					//find this object in the array even though it has a different key
661
+					foreach ($this->_model_relations[$relationName] as $index => $obj) {
662
+						if (
663
+							$obj instanceof EE_Base_Class
664
+							&& (
665
+								$obj == $object_to_remove_or_index_into_array
666
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
667
+							)
668
+						) {
669
+							$index_found_at = $index;
670
+							break;
671
+						}
672
+					}
673
+					if ($index_found_at) {
674
+						$index_in_cache = $index_found_at;
675
+					} else {
676
+						//it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
677
+						//if it wasn't in it to begin with. So we're done
678
+						return $object_to_remove_or_index_into_array;
679
+					}
680
+				}
681
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
682
+				//so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
683
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
684
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
685
+						$index_in_cache = $index;
686
+					}
687
+				}
688
+			} else {
689
+				$index_in_cache = $object_to_remove_or_index_into_array;
690
+			}
691
+			//supposedly we've found it. But it could just be that the client code
692
+			//provided a bad index/object
693
+			if (
694
+			isset(
695
+				$this->_model_relations[$relationName],
696
+				$this->_model_relations[$relationName][$index_in_cache]
697
+			)
698
+			) {
699
+				$obj_removed = $this->_model_relations[$relationName][$index_in_cache];
700
+				unset($this->_model_relations[$relationName][$index_in_cache]);
701
+			} else {
702
+				//that thing was never cached anyways.
703
+				$obj_removed = null;
704
+			}
705
+		}
706
+		return $obj_removed;
707
+	}
708
+
709
+
710
+
711
+	/**
712
+	 * update_cache_after_object_save
713
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has obtained after being saved to the db
714
+	 *
715
+	 * @param string         $relationName       - the type of object that is cached
716
+	 * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
717
+	 * @param string         $current_cache_id   - the ID that was used when originally caching the object
718
+	 * @return boolean TRUE on success, FALSE on fail
719
+	 * @throws \EE_Error
720
+	 */
721
+	public function update_cache_after_object_save($relationName, EE_Base_Class $newly_saved_object, $current_cache_id = '')
722
+	{
723
+		// verify that incoming object is of the correct type
724
+		$obj_class = 'EE_' . $relationName;
725
+		if ($newly_saved_object instanceof $obj_class) {
726
+			/* @type EE_Base_Class $newly_saved_object */
727
+			// now get the type of relation
728
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
729
+			// if this is a 1:1 relationship
730
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
731
+				// then just replace the cached object with the newly saved object
732
+				$this->_model_relations[$relationName] = $newly_saved_object;
733
+				return true;
734
+				// or if it's some kind of sordid feral polyamorous relationship...
735
+			} elseif (is_array($this->_model_relations[$relationName]) && isset($this->_model_relations[$relationName][$current_cache_id])) {
736
+				// then remove the current cached item
737
+				unset($this->_model_relations[$relationName][$current_cache_id]);
738
+				// and cache the newly saved object using it's new ID
739
+				$this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
740
+				return true;
741
+			}
742
+		}
743
+		return false;
744
+	}
745
+
746
+
747
+
748
+	/**
749
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
750
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
751
+	 *
752
+	 * @param string $relationName
753
+	 * @return EE_Base_Class
754
+	 */
755
+	public function get_one_from_cache($relationName)
756
+	{
757
+		$cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : null;
758
+		if (is_array($cached_array_or_object)) {
759
+			return array_shift($cached_array_or_object);
760
+		} else {
761
+			return $cached_array_or_object;
762
+		}
763
+	}
764
+
765
+
766
+
767
+	/**
768
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
769
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
770
+	 *
771
+	 * @param string $relationName
772
+	 * @throws \EE_Error
773
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
774
+	 */
775
+	public function get_all_from_cache($relationName)
776
+	{
777
+		$objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
778
+		// if the result is not an array, but exists, make it an array
779
+		$objects = is_array($objects) ? $objects : array($objects);
780
+		//bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
781
+		//basically, if this model object was stored in the session, and these cached model objects
782
+		//already have IDs, let's make sure they're in their model's entity mapper
783
+		//otherwise we will have duplicates next time we call
784
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
785
+		$model = EE_Registry::instance()->load_model($relationName);
786
+		foreach ($objects as $model_object) {
787
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
788
+				//ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
789
+				if ($model_object->ID()) {
790
+					$model->add_to_entity_map($model_object);
791
+				}
792
+			} else {
793
+				throw new EE_Error(
794
+					sprintf(
795
+						__(
796
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
797
+							'event_espresso'
798
+						),
799
+						$relationName,
800
+						gettype($model_object)
801
+					)
802
+				);
803
+			}
804
+		}
805
+		return $objects;
806
+	}
807
+
808
+
809
+
810
+	/**
811
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
812
+	 * matching the given query conditions.
813
+	 *
814
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
815
+	 * @param int   $limit              How many objects to return.
816
+	 * @param array $query_params       Any additional conditions on the query.
817
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
818
+	 *                                  you can indicate just the columns you want returned
819
+	 * @return array|EE_Base_Class[]
820
+	 * @throws \EE_Error
821
+	 */
822
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
823
+	{
824
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
825
+			? $this->get_model()->get_primary_key_field()->get_name()
826
+			: $field_to_order_by;
827
+		$current_value = ! empty($field) ? $this->get($field) : null;
828
+		if (empty($field) || empty($current_value)) {
829
+			return array();
830
+		}
831
+		return $this->get_model()->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
832
+	}
833
+
834
+
835
+
836
+	/**
837
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
838
+	 * matching the given query conditions.
839
+	 *
840
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
841
+	 * @param int   $limit              How many objects to return.
842
+	 * @param array $query_params       Any additional conditions on the query.
843
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
844
+	 *                                  you can indicate just the columns you want returned
845
+	 * @return array|EE_Base_Class[]
846
+	 * @throws \EE_Error
847
+	 */
848
+	public function previous_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
849
+	{
850
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
851
+			? $this->get_model()->get_primary_key_field()->get_name()
852
+			: $field_to_order_by;
853
+		$current_value = ! empty($field) ? $this->get($field) : null;
854
+		if (empty($field) || empty($current_value)) {
855
+			return array();
856
+		}
857
+		return $this->get_model()->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
858
+	}
859
+
860
+
861
+
862
+	/**
863
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
864
+	 * matching the given query conditions.
865
+	 *
866
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
867
+	 * @param array $query_params       Any additional conditions on the query.
868
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
869
+	 *                                  you can indicate just the columns you want returned
870
+	 * @return array|EE_Base_Class
871
+	 * @throws \EE_Error
872
+	 */
873
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
874
+	{
875
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
876
+			? $this->get_model()->get_primary_key_field()->get_name()
877
+			: $field_to_order_by;
878
+		$current_value = ! empty($field) ? $this->get($field) : null;
879
+		if (empty($field) || empty($current_value)) {
880
+			return array();
881
+		}
882
+		return $this->get_model()->next($current_value, $field, $query_params, $columns_to_select);
883
+	}
884
+
885
+
886
+
887
+	/**
888
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
889
+	 * matching the given query conditions.
890
+	 *
891
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
892
+	 * @param array $query_params       Any additional conditions on the query.
893
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
894
+	 *                                  you can indicate just the column you want returned
895
+	 * @return array|EE_Base_Class
896
+	 * @throws \EE_Error
897
+	 */
898
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
899
+	{
900
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
901
+			? $this->get_model()->get_primary_key_field()->get_name()
902
+			: $field_to_order_by;
903
+		$current_value = ! empty($field) ? $this->get($field) : null;
904
+		if (empty($field) || empty($current_value)) {
905
+			return array();
906
+		}
907
+		return $this->get_model()->previous($current_value, $field, $query_params, $columns_to_select);
908
+	}
909
+
910
+
911
+
912
+	/**
913
+	 * Overrides parent because parent expects old models.
914
+	 * This also doesn't do any validation, and won't work for serialized arrays
915
+	 *
916
+	 * @param string $field_name
917
+	 * @param mixed  $field_value_from_db
918
+	 * @throws \EE_Error
919
+	 */
920
+	public function set_from_db($field_name, $field_value_from_db)
921
+	{
922
+		$field_obj = $this->get_model()->field_settings_for($field_name);
923
+		if ($field_obj instanceof EE_Model_Field_Base) {
924
+			//you would think the DB has no NULLs for non-null label fields right? wrong!
925
+			//eg, a CPT model object could have an entry in the posts table, but no
926
+			//entry in the meta table. Meaning that all its columns in the meta table
927
+			//are null! yikes! so when we find one like that, use defaults for its meta columns
928
+			if ($field_value_from_db === null) {
929
+				if ($field_obj->is_nullable()) {
930
+					//if the field allows nulls, then let it be null
931
+					$field_value = null;
932
+				} else {
933
+					$field_value = $field_obj->get_default_value();
934
+				}
935
+			} else {
936
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
937
+			}
938
+			$this->_fields[$field_name] = $field_value;
939
+			$this->_clear_cached_property($field_name);
940
+		}
941
+	}
942
+
943
+
944
+
945
+	/**
946
+	 * verifies that the specified field is of the correct type
947
+	 *
948
+	 * @param string $field_name
949
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
950
+	 *                                (in cases where the same property may be used for different outputs
951
+	 *                                - i.e. datetime, money etc.)
952
+	 * @return mixed
953
+	 * @throws \EE_Error
954
+	 */
955
+	public function get($field_name, $extra_cache_ref = null)
956
+	{
957
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
958
+	}
959
+
960
+
961
+
962
+	/**
963
+	 * This method simply returns the RAW unprocessed value for the given property in this class
964
+	 *
965
+	 * @param  string $field_name A valid fieldname
966
+	 * @return mixed              Whatever the raw value stored on the property is.
967
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
968
+	 */
969
+	public function get_raw($field_name)
970
+	{
971
+		$field_settings = $this->get_model()->field_settings_for($field_name);
972
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
973
+			? $this->_fields[$field_name]->format('U')
974
+			: $this->_fields[$field_name];
975
+	}
976
+
977
+
978
+
979
+	/**
980
+	 * This is used to return the internal DateTime object used for a field that is a
981
+	 * EE_Datetime_Field.
982
+	 *
983
+	 * @param string $field_name               The field name retrieving the DateTime object.
984
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
985
+	 * @throws \EE_Error
986
+	 *                                         an error is set and false returned.  If the field IS an
987
+	 *                                         EE_Datetime_Field and but the field value is null, then
988
+	 *                                         just null is returned (because that indicates that likely
989
+	 *                                         this field is nullable).
990
+	 */
991
+	public function get_DateTime_object($field_name)
992
+	{
993
+		$field_settings = $this->get_model()->field_settings_for($field_name);
994
+		if ( ! $field_settings instanceof EE_Datetime_Field) {
995
+			EE_Error::add_error(
996
+				sprintf(
997
+					__(
998
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
999
+						'event_espresso'
1000
+					),
1001
+					$field_name
1002
+				),
1003
+				__FILE__,
1004
+				__FUNCTION__,
1005
+				__LINE__
1006
+			);
1007
+			return false;
1008
+		}
1009
+		return $this->_fields[$field_name];
1010
+	}
1011
+
1012
+
1013
+
1014
+	/**
1015
+	 * To be used in template to immediately echo out the value, and format it for output.
1016
+	 * Eg, should call stripslashes and whatnot before echoing
1017
+	 *
1018
+	 * @param string $field_name      the name of the field as it appears in the DB
1019
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1020
+	 *                                (in cases where the same property may be used for different outputs
1021
+	 *                                - i.e. datetime, money etc.)
1022
+	 * @return void
1023
+	 * @throws \EE_Error
1024
+	 */
1025
+	public function e($field_name, $extra_cache_ref = null)
1026
+	{
1027
+		echo $this->get_pretty($field_name, $extra_cache_ref);
1028
+	}
1029
+
1030
+
1031
+
1032
+	/**
1033
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1034
+	 * can be easily used as the value of form input.
1035
+	 *
1036
+	 * @param string $field_name
1037
+	 * @return void
1038
+	 * @throws \EE_Error
1039
+	 */
1040
+	public function f($field_name)
1041
+	{
1042
+		$this->e($field_name, 'form_input');
1043
+	}
1044
+
1045
+
1046
+
1047
+	/**
1048
+	 * @param string $field_name
1049
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1050
+	 *                                (in cases where the same property may be used for different outputs
1051
+	 *                                - i.e. datetime, money etc.)
1052
+	 * @return mixed
1053
+	 * @throws \EE_Error
1054
+	 */
1055
+	public function get_pretty($field_name, $extra_cache_ref = null)
1056
+	{
1057
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1058
+	}
1059
+
1060
+
1061
+
1062
+	/**
1063
+	 * This simply returns the datetime for the given field name
1064
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1065
+	 * (and the equivalent e_date, e_time, e_datetime).
1066
+	 *
1067
+	 * @access   protected
1068
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1069
+	 * @param string   $dt_frmt      valid datetime format used for date
1070
+	 *                               (if '' then we just use the default on the field,
1071
+	 *                               if NULL we use the last-used format)
1072
+	 * @param string   $tm_frmt      Same as above except this is for time format
1073
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1074
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1075
+	 * @return void|string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1076
+	 *                               if field is not a valid dtt field, or void if echoing
1077
+	 * @throws \EE_Error
1078
+	 */
1079
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1080
+	{
1081
+		$in_dt_frmt = empty($dt_frmt) ? $this->_dt_frmt : $dt_frmt;
1082
+		$in_tm_frmt = empty($tm_frmt) ? $this->_tm_frmt : $tm_frmt;
1083
+		//validate field for datetime and returns field settings if valid.
1084
+		$field = $this->_get_dtt_field_settings($field_name);
1085
+		//clear cached property if either formats are not null.
1086
+		if ($dt_frmt !== null || $tm_frmt !== null) {
1087
+			$this->_clear_cached_property($field_name);
1088
+			//reset format properties because they are used in get()
1089
+			$this->_dt_frmt = $in_dt_frmt;
1090
+			$this->_tm_frmt = $in_tm_frmt;
1091
+		}
1092
+		if ($echo) {
1093
+			$field->set_pretty_date_format($in_dt_frmt);
1094
+		} else {
1095
+			$field->set_date_format($in_dt_frmt);
1096
+		}
1097
+		if ($echo) {
1098
+			$field->set_pretty_time_format($in_tm_frmt);
1099
+		} else {
1100
+			$field->set_time_format($in_tm_frmt);
1101
+		}
1102
+		//set timezone in field object
1103
+		$field->set_timezone($this->_timezone);
1104
+		//set the output returned
1105
+		switch ($date_or_time) {
1106
+			case 'D' :
1107
+				$field->set_date_time_output('date');
1108
+				break;
1109
+			case 'T' :
1110
+				$field->set_date_time_output('time');
1111
+				break;
1112
+			default :
1113
+				$field->set_date_time_output();
1114
+		}
1115
+		if ($echo) {
1116
+			$this->e($field_name, $date_or_time);
1117
+			return '';
1118
+		}
1119
+		return $this->get($field_name, $date_or_time);
1120
+	}
1121
+
1122
+
1123
+
1124
+	/**
1125
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the other echoes
1126
+	 * the pretty value for dtt)
1127
+	 *
1128
+	 * @param  string $field_name name of model object datetime field holding the value
1129
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1130
+	 * @return string            datetime value formatted
1131
+	 * @throws \EE_Error
1132
+	 */
1133
+	public function get_date($field_name, $format = null)
1134
+	{
1135
+		return $this->_get_datetime($field_name, $format, null, 'D');
1136
+	}
1137
+
1138
+
1139
+
1140
+	/**
1141
+	 * @param      $field_name
1142
+	 * @param null $format
1143
+	 * @throws \EE_Error
1144
+	 */
1145
+	public function e_date($field_name, $format = null)
1146
+	{
1147
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1148
+	}
1149
+
1150
+
1151
+
1152
+	/**
1153
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the other echoes
1154
+	 * the pretty value for dtt)
1155
+	 *
1156
+	 * @param  string $field_name name of model object datetime field holding the value
1157
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1158
+	 * @return string             datetime value formatted
1159
+	 * @throws \EE_Error
1160
+	 */
1161
+	public function get_time($field_name, $format = null)
1162
+	{
1163
+		return $this->_get_datetime($field_name, null, $format, 'T');
1164
+	}
1165
+
1166
+
1167
+
1168
+	/**
1169
+	 * @param      $field_name
1170
+	 * @param null $format
1171
+	 * @throws \EE_Error
1172
+	 */
1173
+	public function e_time($field_name, $format = null)
1174
+	{
1175
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1176
+	}
1177
+
1178
+
1179
+
1180
+	/**
1181
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the other
1182
+	 * echoes the pretty value for dtt)
1183
+	 *
1184
+	 * @param  string $field_name name of model object datetime field holding the value
1185
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1186
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1187
+	 * @return string             datetime value formatted
1188
+	 * @throws \EE_Error
1189
+	 */
1190
+	public function get_datetime($field_name, $dt_frmt = null, $tm_frmt = null)
1191
+	{
1192
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1193
+	}
1194
+
1195
+
1196
+
1197
+	/**
1198
+	 * @param      $field_name
1199
+	 * @param null $dt_frmt
1200
+	 * @param null $tm_frmt
1201
+	 * @throws \EE_Error
1202
+	 */
1203
+	public function e_datetime($field_name, $dt_frmt = null, $tm_frmt = null)
1204
+	{
1205
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1206
+	}
1207
+
1208
+
1209
+
1210
+	/**
1211
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1212
+	 *
1213
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1214
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format on the object will be used.
1215
+	 * @return string Date and time string in set locale or false if no field exists for the given
1216
+	 * @throws \EE_Error
1217
+	 *                           field name.
1218
+	 */
1219
+	public function get_i18n_datetime($field_name, $format = null)
1220
+	{
1221
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1222
+		return date_i18n(
1223
+			$format,
1224
+			EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1225
+		);
1226
+	}
1227
+
1228
+
1229
+
1230
+	/**
1231
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is thrown.
1232
+	 *
1233
+	 * @param  string $field_name The field name being checked
1234
+	 * @throws EE_Error
1235
+	 * @return EE_Datetime_Field
1236
+	 */
1237
+	protected function _get_dtt_field_settings($field_name)
1238
+	{
1239
+		$field = $this->get_model()->field_settings_for($field_name);
1240
+		//check if field is dtt
1241
+		if ($field instanceof EE_Datetime_Field) {
1242
+			return $field;
1243
+		} else {
1244
+			throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1245
+				'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1246
+		}
1247
+	}
1248
+
1249
+
1250
+
1251
+
1252
+	/**
1253
+	 * NOTE ABOUT BELOW:
1254
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might want to change the time on a datetime_field but leave the date the same (or vice versa).
1255
+	 * IF on the other hand you want to set both date and time at the same time, you can just use the models default set($fieldname,$value) method and make sure you send the entire datetime value for setting.
1256
+	 */
1257
+	/**
1258
+	 * sets the time on a datetime property
1259
+	 *
1260
+	 * @access protected
1261
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1262
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1263
+	 * @throws \EE_Error
1264
+	 */
1265
+	protected function _set_time_for($time, $fieldname)
1266
+	{
1267
+		$this->_set_date_time('T', $time, $fieldname);
1268
+	}
1269
+
1270
+
1271
+
1272
+	/**
1273
+	 * sets the date on a datetime property
1274
+	 *
1275
+	 * @access protected
1276
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1277
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1278
+	 * @throws \EE_Error
1279
+	 */
1280
+	protected function _set_date_for($date, $fieldname)
1281
+	{
1282
+		$this->_set_date_time('D', $date, $fieldname);
1283
+	}
1284
+
1285
+
1286
+
1287
+	/**
1288
+	 * This takes care of setting a date or time independently on a given model object property. This method also verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1289
+	 *
1290
+	 * @access protected
1291
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1292
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1293
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a EE_Datetime_Field property)
1294
+	 * @throws \EE_Error
1295
+	 */
1296
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1297
+	{
1298
+		$field = $this->_get_dtt_field_settings($fieldname);
1299
+		$field->set_timezone($this->_timezone);
1300
+		$field->set_date_format($this->_dt_frmt);
1301
+		$field->set_time_format($this->_tm_frmt);
1302
+		switch ($what) {
1303
+			case 'T' :
1304
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1305
+					$datetime_value,
1306
+					$this->_fields[$fieldname]
1307
+				);
1308
+				break;
1309
+			case 'D' :
1310
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1311
+					$datetime_value,
1312
+					$this->_fields[$fieldname]
1313
+				);
1314
+				break;
1315
+			case 'B' :
1316
+				$this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1317
+				break;
1318
+		}
1319
+		$this->_clear_cached_property($fieldname);
1320
+	}
1321
+
1322
+
1323
+
1324
+	/**
1325
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different than the timezone set for the website.
1326
+	 * NOTE, this currently only works well with methods that return values.  If you use it with methods that echo values the $_timestamp property may not get reset to its original value and that could lead to some unexpected results!
1327
+	 *
1328
+	 * @access public
1329
+	 * @param string               $field_name This is the name of the field on the object that contains the date/time value being returned.
1330
+	 * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1331
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1332
+	 * @param string               $prepend    You can include something to prepend on the timestamp
1333
+	 * @param string               $append     You can include something to append on the timestamp
1334
+	 * @throws EE_Error
1335
+	 * @return string timestamp
1336
+	 */
1337
+	public function display_in_my_timezone($field_name, $callback = 'get_datetime', $args = null, $prepend = '', $append = '')
1338
+	{
1339
+		$timezone = EEH_DTT_Helper::get_timezone();
1340
+		if ($timezone === $this->_timezone) {
1341
+			return '';
1342
+		}
1343
+		$original_timezone = $this->_timezone;
1344
+		$this->set_timezone($timezone);
1345
+		$fn = (array)$field_name;
1346
+		$args = array_merge($fn, (array)$args);
1347
+		if ( ! method_exists($this, $callback)) {
1348
+			throw new EE_Error(
1349
+				sprintf(
1350
+					__(
1351
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1352
+						'event_espresso'
1353
+					),
1354
+					$callback
1355
+				)
1356
+			);
1357
+		}
1358
+		$args = (array)$args;
1359
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1360
+		$this->set_timezone($original_timezone);
1361
+		return $return;
1362
+	}
1363
+
1364
+
1365
+
1366
+	/**
1367
+	 * Deletes this model object.
1368
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should override
1369
+	 * `EE_Base_Class::_delete` NOT this class.
1370
+	 *
1371
+	 * @return boolean | int
1372
+	 * @throws \EE_Error
1373
+	 */
1374
+	public function delete()
1375
+	{
1376
+		/**
1377
+		 * Called just before the `EE_Base_Class::_delete` method call.
1378
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1379
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1380
+		 * soft deletes (trash) the object and does not permanently delete it.
1381
+		 *
1382
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1383
+		 */
1384
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1385
+		$result = $this->_delete();
1386
+		/**
1387
+		 * Called just after the `EE_Base_Class::_delete` method call.
1388
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1389
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1390
+		 * soft deletes (trash) the object and does not permanently delete it.
1391
+		 *
1392
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1393
+		 * @param boolean       $result
1394
+		 */
1395
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1396
+		return $result;
1397
+	}
1398
+
1399
+
1400
+
1401
+	/**
1402
+	 * Calls the specific delete method for the instantiated class.
1403
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override default
1404
+	 * functionality for "delete" (which is to call `permanently_delete`) should override this method NOT `EE_Base_Class::delete`
1405
+	 *
1406
+	 * @return bool|int
1407
+	 * @throws \EE_Error
1408
+	 */
1409
+	protected function _delete()
1410
+	{
1411
+		return $this->delete_permanently();
1412
+	}
1413
+
1414
+
1415
+
1416
+	/**
1417
+	 * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an error)
1418
+	 *
1419
+	 * @return bool | int
1420
+	 * @throws \EE_Error
1421
+	 */
1422
+	public function delete_permanently()
1423
+	{
1424
+		/**
1425
+		 * Called just before HARD deleting a model object
1426
+		 *
1427
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1428
+		 */
1429
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1430
+		$model = $this->get_model();
1431
+		$result = $model->delete_permanently_by_ID($this->ID());
1432
+		$this->refresh_cache_of_related_objects();
1433
+		/**
1434
+		 * Called just after HARD deleting a model object
1435
+		 *
1436
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1437
+		 * @param boolean       $result
1438
+		 */
1439
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1440
+		return $result;
1441
+	}
1442
+
1443
+
1444
+
1445
+	/**
1446
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1447
+	 * related model objects
1448
+	 *
1449
+	 * @throws \EE_Error
1450
+	 */
1451
+	public function refresh_cache_of_related_objects()
1452
+	{
1453
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1454
+			if ( ! empty($this->_model_relations[$relation_name])) {
1455
+				$related_objects = $this->_model_relations[$relation_name];
1456
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1457
+					//this relation only stores a single model object, not an array
1458
+					//but let's make it consistent
1459
+					$related_objects = array($related_objects);
1460
+				}
1461
+				foreach ($related_objects as $related_object) {
1462
+					//only refresh their cache if they're in memory
1463
+					if ($related_object instanceof EE_Base_Class) {
1464
+						$related_object->clear_cache($this->get_model()->get_this_model_name(), $this);
1465
+					}
1466
+				}
1467
+			}
1468
+		}
1469
+	}
1470
+
1471
+
1472
+
1473
+	/**
1474
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1475
+	 * object just before saving.
1476
+	 *
1477
+	 * @access public
1478
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1479
+	 *                                 if provided during the save() method (often client code will change the fields' values before calling save)
1480
+	 * @throws \EE_Error
1481
+	 * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1482
+	 *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1483
+	 */
1484
+	public function save($set_cols_n_values = array())
1485
+	{
1486
+		/**
1487
+		 * Filters the fields we're about to save on the model object
1488
+		 *
1489
+		 * @param array         $set_cols_n_values
1490
+		 * @param EE_Base_Class $model_object
1491
+		 */
1492
+		$set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values, $this);
1493
+		//set attributes as provided in $set_cols_n_values
1494
+		foreach ($set_cols_n_values as $column => $value) {
1495
+			$this->set($column, $value);
1496
+		}
1497
+		/**
1498
+		 * Saving a model object.
1499
+		 * Before we perform a save, this action is fired.
1500
+		 *
1501
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1502
+		 */
1503
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1504
+		if ( ! $this->allow_persist()) {
1505
+			return 0;
1506
+		}
1507
+		//now get current attribute values
1508
+		$save_cols_n_values = $this->_fields;
1509
+		//if the object already has an ID, update it. Otherwise, insert it
1510
+		//also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1511
+		$old_assumption_concerning_value_preparation = $this->get_model()->get_assumption_concerning_values_already_prepared_by_model_object();
1512
+		$this->get_model()->assume_values_already_prepared_by_model_object(true);
1513
+		//does this model have an autoincrement PK?
1514
+		if ($this->get_model()->has_primary_key_field()) {
1515
+			if ($this->get_model()->get_primary_key_field()->is_auto_increment()) {
1516
+				//ok check if it's set, if so: update; if not, insert
1517
+				if ( ! empty($save_cols_n_values[self::_get_primary_key_name(get_class($this))])) {
1518
+					$results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1519
+				} else {
1520
+					unset($save_cols_n_values[self::_get_primary_key_name(get_class($this))]);
1521
+					$results = $this->get_model()->insert($save_cols_n_values);
1522
+					if ($results) {
1523
+						//if successful, set the primary key
1524
+						//but don't use the normal SET method, because it will check if
1525
+						//an item with the same ID exists in the mapper & db, then
1526
+						//will find it in the db (because we just added it) and THAT object
1527
+						//will get added to the mapper before we can add this one!
1528
+						//but if we just avoid using the SET method, all that headache can be avoided
1529
+						$pk_field_name = self::_get_primary_key_name(get_class($this));
1530
+						$this->_fields[$pk_field_name] = $results;
1531
+						$this->_clear_cached_property($pk_field_name);
1532
+						$this->get_model()->add_to_entity_map($this);
1533
+						$this->_update_cached_related_model_objs_fks();
1534
+					}
1535
+				}
1536
+			} else {//PK is NOT auto-increment
1537
+				//so check if one like it already exists in the db
1538
+				if ($this->get_model()->exists_by_ID($this->ID())) {
1539
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1540
+						throw new EE_Error(
1541
+							sprintf(
1542
+								__('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1543
+									'event_espresso'),
1544
+								get_class($this),
1545
+								get_class($this->get_model()) . '::instance()->add_to_entity_map()',
1546
+								get_class($this->get_model()) . '::instance()->get_one_by_ID()',
1547
+								'<br />'
1548
+							)
1549
+						);
1550
+					}
1551
+					$results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1552
+				} else {
1553
+					$results = $this->get_model()->insert($save_cols_n_values);
1554
+					$this->_update_cached_related_model_objs_fks();
1555
+				}
1556
+			}
1557
+		} else {//there is NO primary key
1558
+			$already_in_db = false;
1559
+			foreach ($this->get_model()->unique_indexes() as $index) {
1560
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1561
+				if ($this->get_model()->exists(array($uniqueness_where_params))) {
1562
+					$already_in_db = true;
1563
+				}
1564
+			}
1565
+			if ($already_in_db) {
1566
+				$combined_pk_fields_n_values = array_intersect_key($save_cols_n_values, $this->get_model()->get_combined_primary_key_fields());
1567
+				$results = $this->get_model()->update($save_cols_n_values, $combined_pk_fields_n_values);
1568
+			} else {
1569
+				$results = $this->get_model()->insert($save_cols_n_values);
1570
+			}
1571
+		}
1572
+		//restore the old assumption about values being prepared by the model object
1573
+		$this->get_model()->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1574
+		/**
1575
+		 * After saving the model object this action is called
1576
+		 *
1577
+		 * @param EE_Base_Class $model_object which was just saved
1578
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1579
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1580
+		 */
1581
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1582
+		return $results;
1583
+	}
1584
+
1585
+
1586
+
1587
+	/**
1588
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1589
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB is consistent)
1590
+	 * Especially useful in case we JUST added this model object ot the database
1591
+	 * and we want to let its cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on
1592
+	 * the transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether or not they exist in the DB (if they do, their DB records will be automatically updated)
1593
+	 *
1594
+	 * @return void
1595
+	 * @throws \EE_Error
1596
+	 */
1597
+	protected function _update_cached_related_model_objs_fks()
1598
+	{
1599
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1600
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1601
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1602
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1603
+						$this->get_model()->get_this_model_name()
1604
+					);
1605
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1606
+					if ($related_model_obj_in_cache->ID()) {
1607
+						$related_model_obj_in_cache->save();
1608
+					}
1609
+				}
1610
+			}
1611
+		}
1612
+	}
1613
+
1614
+
1615
+
1616
+	/**
1617
+	 * Saves this model object and its NEW cached relations to the database.
1618
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1619
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1620
+	 * because otherwise, there's a potential for infinite looping of saving
1621
+	 * Saves the cached related model objects, and ensures the relation between them
1622
+	 * and this object and properly setup
1623
+	 *
1624
+	 * @return int ID of new model object on save; 0 on failure+
1625
+	 * @throws \EE_Error
1626
+	 */
1627
+	public function save_new_cached_related_model_objs()
1628
+	{
1629
+		//make sure this has been saved
1630
+		if ( ! $this->ID()) {
1631
+			$id = $this->save();
1632
+		} else {
1633
+			$id = $this->ID();
1634
+		}
1635
+		//now save all the NEW cached model objects  (ie they don't exist in the DB)
1636
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1637
+			if ($this->_model_relations[$relationName]) {
1638
+				//is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1639
+				//or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1640
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1641
+					//add a relation to that relation type (which saves the appropriate thing in the process)
1642
+					//but ONLY if it DOES NOT exist in the DB
1643
+					/* @var $related_model_obj EE_Base_Class */
1644
+					$related_model_obj = $this->_model_relations[$relationName];
1645
+					//					if( ! $related_model_obj->ID()){
1646
+					$this->_add_relation_to($related_model_obj, $relationName);
1647
+					$related_model_obj->save_new_cached_related_model_objs();
1648
+					//					}
1649
+				} else {
1650
+					foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1651
+						//add a relation to that relation type (which saves the appropriate thing in the process)
1652
+						//but ONLY if it DOES NOT exist in the DB
1653
+						//						if( ! $related_model_obj->ID()){
1654
+						$this->_add_relation_to($related_model_obj, $relationName);
1655
+						$related_model_obj->save_new_cached_related_model_objs();
1656
+						//						}
1657
+					}
1658
+				}
1659
+			}
1660
+		}
1661
+		return $id;
1662
+	}
1663
+
1664
+
1665
+
1666
+	/**
1667
+	 * for getting a model while instantiated.
1668
+	 *
1669
+	 * @return \EEM_Base | \EEM_CPT_Base
1670
+	 */
1671
+	public function get_model()
1672
+	{
1673
+		$modelName = self::_get_model_classname(get_class($this));
1674
+		return self::_get_model_instance_with_name($modelName, $this->_timezone);
1675
+	}
1676
+
1677
+
1678
+
1679
+	/**
1680
+	 * @param $props_n_values
1681
+	 * @param $classname
1682
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1683
+	 * @throws \EE_Error
1684
+	 */
1685
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1686
+	{
1687
+		//TODO: will not work for Term_Relationships because they have no PK!
1688
+		$primary_id_ref = self::_get_primary_key_name($classname);
1689
+		if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1690
+			$id = $props_n_values[$primary_id_ref];
1691
+			return self::_get_model($classname)->get_from_entity_map($id);
1692
+		}
1693
+		return false;
1694
+	}
1695
+
1696
+
1697
+
1698
+	/**
1699
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for the primary key (if present in incoming values).
1700
+	 * If there is a key in the incoming array that matches the primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not we return false.
1701
+	 *
1702
+	 * @param  array  $props_n_values   incoming array of properties and their values
1703
+	 * @param  string $classname        the classname of the child class
1704
+	 * @param null    $timezone
1705
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
1706
+	 *                                  date_format and the second value is the time format
1707
+	 * @return mixed (EE_Base_Class|bool)
1708
+	 * @throws \EE_Error
1709
+	 */
1710
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1711
+	{
1712
+		$existing = null;
1713
+		if (self::_get_model($classname)->has_primary_key_field()) {
1714
+			$primary_id_ref = self::_get_primary_key_name($classname);
1715
+			if (array_key_exists($primary_id_ref, $props_n_values)
1716
+				&& ! empty($props_n_values[$primary_id_ref])
1717
+			) {
1718
+				$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1719
+					$props_n_values[$primary_id_ref]
1720
+				);
1721
+			}
1722
+		} elseif (self::_get_model($classname, $timezone)->has_all_combined_primary_key_fields($props_n_values)) {
1723
+			//no primary key on this model, but there's still a matching item in the DB
1724
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1725
+				self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1726
+			);
1727
+		}
1728
+		if ($existing) {
1729
+			//set date formats if present before setting values
1730
+			if ( ! empty($date_formats) && is_array($date_formats)) {
1731
+				$existing->set_date_format($date_formats[0]);
1732
+				$existing->set_time_format($date_formats[1]);
1733
+			} else {
1734
+				//set default formats for date and time
1735
+				$existing->set_date_format(get_option('date_format'));
1736
+				$existing->set_time_format(get_option('time_format'));
1737
+			}
1738
+			foreach ($props_n_values as $property => $field_value) {
1739
+				$existing->set($property, $field_value);
1740
+			}
1741
+			return $existing;
1742
+		} else {
1743
+			return false;
1744
+		}
1745
+	}
1746
+
1747
+
1748
+
1749
+	/**
1750
+	 * Gets the EEM_*_Model for this class
1751
+	 *
1752
+	 * @access public now, as this is more convenient
1753
+	 * @param      $classname
1754
+	 * @param null $timezone
1755
+	 * @throws EE_Error
1756
+	 * @return EEM_Base
1757
+	 */
1758
+	protected static function _get_model($classname, $timezone = null)
1759
+	{
1760
+		//find model for this class
1761
+		if ( ! $classname) {
1762
+			throw new EE_Error(
1763
+				sprintf(
1764
+					__(
1765
+						"What were you thinking calling _get_model(%s)?? You need to specify the class name",
1766
+						"event_espresso"
1767
+					),
1768
+					$classname
1769
+				)
1770
+			);
1771
+		}
1772
+		$modelName = self::_get_model_classname($classname);
1773
+		return self::_get_model_instance_with_name($modelName, $timezone);
1774
+	}
1775
+
1776
+
1777
+
1778
+	/**
1779
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1780
+	 *
1781
+	 * @param string $model_classname
1782
+	 * @param null   $timezone
1783
+	 * @return EEM_Base
1784
+	 */
1785
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1786
+	{
1787
+		$model_classname = str_replace('EEM_', '', $model_classname);
1788
+		$model = EE_Registry::instance()->load_model($model_classname);
1789
+		$model->set_timezone($timezone);
1790
+		return $model;
1791
+	}
1792
+
1793
+
1794
+
1795
+	/**
1796
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
1797
+	 * Also works if a model class's classname is provided (eg EE_Registration).
1798
+	 *
1799
+	 * @param null $model_name
1800
+	 * @return string like EEM_Attendee
1801
+	 */
1802
+	private static function _get_model_classname($model_name = null)
1803
+	{
1804
+		if (strpos($model_name, "EE_") === 0) {
1805
+			$model_classname = str_replace("EE_", "EEM_", $model_name);
1806
+		} else {
1807
+			$model_classname = "EEM_" . $model_name;
1808
+		}
1809
+		return $model_classname;
1810
+	}
1811
+
1812
+
1813
+
1814
+	/**
1815
+	 * returns the name of the primary key attribute
1816
+	 *
1817
+	 * @param null $classname
1818
+	 * @throws EE_Error
1819
+	 * @return string
1820
+	 */
1821
+	protected static function _get_primary_key_name($classname = null)
1822
+	{
1823
+		if ( ! $classname) {
1824
+			throw new EE_Error(
1825
+				sprintf(
1826
+					__("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
1827
+					$classname
1828
+				)
1829
+			);
1830
+		}
1831
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
1832
+	}
1833
+
1834
+
1835
+
1836
+	/**
1837
+	 * Gets the value of the primary key.
1838
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
1839
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value is.
1840
+	 * Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
1841
+	 *
1842
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
1843
+	 * @throws \EE_Error
1844
+	 */
1845
+	public function ID()
1846
+	{
1847
+		//now that we know the name of the variable, use a variable variable to get its value and return its
1848
+		if ($this->get_model()->has_primary_key_field()) {
1849
+			return $this->_fields[self::_get_primary_key_name(get_class($this))];
1850
+		} else {
1851
+			return $this->get_model()->get_index_primary_key_string($this->_fields);
1852
+		}
1853
+	}
1854
+
1855
+
1856
+
1857
+	/**
1858
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current model is related
1859
+	 * to a group of events, the $relationName should be 'Event', and should be a key in the EE Model's $_model_relations array.
1860
+	 * If this model object doesn't exist in the DB, just caches the related thing
1861
+	 *
1862
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
1863
+	 * @param string $relationName                     eg 'Events','Question',etc.
1864
+	 *                                                 an attendee to a group, you also want to specify which role they will have in that group. So you would use this parameter to specify array('role-column-name'=>'role-id')
1865
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that allow you to further constrict the relation to being added.  However, keep in mind that the columns (keys) given must match
1866
+	 *                                                 a column on the JOIN table and currently only the HABTM models accept these additional conditions.  Also remember that if an exact match isn't found for these extra cols/val pairs,
1867
+	 *                                                 then a NEW row is created in the join table.
1868
+	 * @param null   $cache_id
1869
+	 * @throws EE_Error
1870
+	 * @return EE_Base_Class the object the relation was added to
1871
+	 */
1872
+	public function _add_relation_to($otherObjectModelObjectOrID, $relationName, $extra_join_model_fields_n_values = array(), $cache_id = null)
1873
+	{
1874
+		//if this thing exists in the DB, save the relation to the DB
1875
+		if ($this->ID()) {
1876
+			$otherObject = $this->get_model()->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName, $extra_join_model_fields_n_values);
1877
+			//clear cache so future get_many_related and get_first_related() return new results.
1878
+			$this->clear_cache($relationName, $otherObject, true);
1879
+			if ($otherObject instanceof EE_Base_Class) {
1880
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
1881
+			}
1882
+		} else {
1883
+			//this thing doesn't exist in the DB,  so just cache it
1884
+			if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
1885
+				throw new EE_Error(sprintf(
1886
+					__('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s', 'event_espresso'),
1887
+					$otherObjectModelObjectOrID,
1888
+					get_class($this)
1889
+				));
1890
+			} else {
1891
+				$otherObject = $otherObjectModelObjectOrID;
1892
+			}
1893
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
1894
+		}
1895
+		if ($otherObject instanceof EE_Base_Class) {
1896
+			//fix the reciprocal relation too
1897
+			if ($otherObject->ID()) {
1898
+				//its saved so assumed relations exist in the DB, so we can just
1899
+				//clear the cache so future queries use the updated info in the DB
1900
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), null, true);
1901
+			} else {
1902
+				//it's not saved, so it caches relations like this
1903
+				$otherObject->cache($this->get_model()->get_this_model_name(), $this);
1904
+			}
1905
+		}
1906
+		return $otherObject;
1907
+	}
1908
+
1909
+
1910
+
1911
+	/**
1912
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current model is related
1913
+	 * to a group of events, the $relationName should be 'Events', and should be a key in the EE Model's $_model_relations array.
1914
+	 * If this model object doesn't exist in the DB, just removes the related thing from the cache
1915
+	 *
1916
+	 * @param mixed  $otherObjectModelObjectOrID
1917
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved to the DB yet
1918
+	 * @param string $relationName
1919
+	 * @param array  $where_query
1920
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the relation to being added.
1921
+	 *                However, keep in mind that the columns (keys) given must match a column on the JOIN table
1922
+	 *                and currently only the HABTM models accept these additional conditions.
1923
+	 *                Also remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is created in the join table.
1924
+	 * @return EE_Base_Class the relation was removed from
1925
+	 * @throws \EE_Error
1926
+	 */
1927
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
1928
+	{
1929
+		if ($this->ID()) {
1930
+			//if this exists in the DB, save the relation change to the DB too
1931
+			$otherObject = $this->get_model()->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName, $where_query);
1932
+			$this->clear_cache($relationName, $otherObject);
1933
+		} else {
1934
+			//this doesn't exist in the DB, just remove it from the cache
1935
+			$otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
1936
+		}
1937
+		if ($otherObject instanceof EE_Base_Class) {
1938
+			$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
1939
+		}
1940
+		return $otherObject;
1941
+	}
1942
+
1943
+
1944
+
1945
+	/**
1946
+	 * Removes ALL the related things for the $relationName.
1947
+	 *
1948
+	 * @param string $relationName
1949
+	 * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
1950
+	 * @return EE_Base_Class
1951
+	 * @throws \EE_Error
1952
+	 */
1953
+	public function _remove_relations($relationName, $where_query_params = array())
1954
+	{
1955
+		if ($this->ID()) {
1956
+			//if this exists in the DB, save the relation change to the DB too
1957
+			$otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
1958
+			$this->clear_cache($relationName, null, true);
1959
+		} else {
1960
+			//this doesn't exist in the DB, just remove it from the cache
1961
+			$otherObjects = $this->clear_cache($relationName, null, true);
1962
+		}
1963
+		if (is_array($otherObjects)) {
1964
+			foreach ($otherObjects as $otherObject) {
1965
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
1966
+			}
1967
+		}
1968
+		return $otherObjects;
1969
+	}
1970
+
1971
+
1972
+
1973
+	/**
1974
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
1975
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
1976
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
1977
+	 * because we want to get even deleted items etc.
1978
+	 *
1979
+	 * @param string $relationName key in the model's _model_relations array
1980
+	 * @param array  $query_params like EEM_Base::get_all
1981
+	 * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
1982
+	 * @throws \EE_Error
1983
+	 *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if you want IDs
1984
+	 */
1985
+	public function get_many_related($relationName, $query_params = array())
1986
+	{
1987
+		if ($this->ID()) {
1988
+			//this exists in the DB, so get the related things from either the cache or the DB
1989
+			//if there are query parameters, forget about caching the related model objects.
1990
+			if ($query_params) {
1991
+				$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
1992
+			} else {
1993
+				//did we already cache the result of this query?
1994
+				$cached_results = $this->get_all_from_cache($relationName);
1995
+				if ( ! $cached_results) {
1996
+					$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
1997
+					//if no query parameters were passed, then we got all the related model objects
1998
+					//for that relation. We can cache them then.
1999
+					foreach ($related_model_objects as $related_model_object) {
2000
+						$this->cache($relationName, $related_model_object);
2001
+					}
2002
+				} else {
2003
+					$related_model_objects = $cached_results;
2004
+				}
2005
+			}
2006
+		} else {
2007
+			//this doesn't exist in the DB, so just get the related things from the cache
2008
+			$related_model_objects = $this->get_all_from_cache($relationName);
2009
+		}
2010
+		return $related_model_objects;
2011
+	}
2012
+
2013
+
2014
+
2015
+	/**
2016
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2017
+	 * unless otherwise specified in the $query_params
2018
+	 *
2019
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2020
+	 * @param array  $query_params   like EEM_Base::get_all's
2021
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2022
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger that by the setting $distinct to TRUE;
2023
+	 * @return int
2024
+	 */
2025
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2026
+	{
2027
+		return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2028
+	}
2029
+
2030
+
2031
+
2032
+	/**
2033
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2034
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2035
+	 *
2036
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2037
+	 * @param array  $query_params  like EEM_Base::get_all's
2038
+	 * @param string $field_to_sum  name of field to count by.
2039
+	 *                              By default, uses primary key (which doesn't make much sense, so you should probably change it)
2040
+	 * @return int
2041
+	 */
2042
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2043
+	{
2044
+		return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2045
+	}
2046
+
2047
+
2048
+
2049
+	/**
2050
+	 * Gets the first (ie, one) related model object of the specified type.
2051
+	 *
2052
+	 * @param string $relationName key in the model's _model_relations array
2053
+	 * @param array  $query_params like EEM_Base::get_all
2054
+	 * @return EE_Base_Class (not an array, a single object)
2055
+	 * @throws \EE_Error
2056
+	 */
2057
+	public function get_first_related($relationName, $query_params = array())
2058
+	{
2059
+		if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2060
+			//if they've provided some query parameters, don't bother trying to cache the result
2061
+			//also make sure we're not caching the result of get_first_related
2062
+			//on a relation which should have an array of objects (because the cache might have an array of objects)
2063
+			if ($query_params || ! $this->get_model()->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2064
+				$related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2065
+			} else {
2066
+				//first, check if we've already cached the result of this query
2067
+				$cached_result = $this->get_one_from_cache($relationName);
2068
+				if ( ! $cached_result) {
2069
+					$related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2070
+					$this->cache($relationName, $related_model_object);
2071
+				} else {
2072
+					$related_model_object = $cached_result;
2073
+				}
2074
+			}
2075
+		} else {
2076
+			$related_model_object = null;
2077
+			//this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2078
+			if ($this->get_model()->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2079
+				$related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2080
+			}
2081
+			//this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2082
+			if ( ! $related_model_object) {
2083
+				$related_model_object = $this->get_one_from_cache($relationName);
2084
+			}
2085
+		}
2086
+		return $related_model_object;
2087
+	}
2088
+
2089
+
2090
+
2091
+	/**
2092
+	 * Does a delete on all related objects of type $relationName and removes
2093
+	 * the current model object's relation to them. If they can't be deleted (because
2094
+	 * of blocking related model objects) does nothing. If the related model objects are
2095
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2096
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2097
+	 *
2098
+	 * @param string $relationName
2099
+	 * @param array  $query_params like EEM_Base::get_all's
2100
+	 * @return int how many deleted
2101
+	 * @throws \EE_Error
2102
+	 */
2103
+	public function delete_related($relationName, $query_params = array())
2104
+	{
2105
+		if ($this->ID()) {
2106
+			$count = $this->get_model()->delete_related($this, $relationName, $query_params);
2107
+		} else {
2108
+			$count = count($this->get_all_from_cache($relationName));
2109
+			$this->clear_cache($relationName, null, true);
2110
+		}
2111
+		return $count;
2112
+	}
2113
+
2114
+
2115
+
2116
+	/**
2117
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2118
+	 * the current model object's relation to them. If they can't be deleted (because
2119
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2120
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2121
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2122
+	 *
2123
+	 * @param string $relationName
2124
+	 * @param array  $query_params like EEM_Base::get_all's
2125
+	 * @return int how many deleted (including those soft deleted)
2126
+	 * @throws \EE_Error
2127
+	 */
2128
+	public function delete_related_permanently($relationName, $query_params = array())
2129
+	{
2130
+		if ($this->ID()) {
2131
+			$count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2132
+		} else {
2133
+			$count = count($this->get_all_from_cache($relationName));
2134
+		}
2135
+		$this->clear_cache($relationName, null, true);
2136
+		return $count;
2137
+	}
2138
+
2139
+
2140
+
2141
+	/**
2142
+	 * is_set
2143
+	 * Just a simple utility function children can use for checking if property exists
2144
+	 *
2145
+	 * @access  public
2146
+	 * @param  string $field_name property to check
2147
+	 * @return bool                              TRUE if existing,FALSE if not.
2148
+	 */
2149
+	public function is_set($field_name)
2150
+	{
2151
+		return isset($this->_fields[$field_name]);
2152
+	}
2153
+
2154
+
2155
+
2156
+	/**
2157
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an EE_Error exception if they don't
2158
+	 *
2159
+	 * @param  mixed (string|array) $properties properties to check
2160
+	 * @throws EE_Error
2161
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2162
+	 */
2163
+	protected function _property_exists($properties)
2164
+	{
2165
+		foreach ((array)$properties as $property_name) {
2166
+			//first make sure this property exists
2167
+			if ( ! $this->_fields[$property_name]) {
2168
+				throw new EE_Error(
2169
+					sprintf(
2170
+						__(
2171
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2172
+							'event_espresso'
2173
+						),
2174
+						$property_name
2175
+					)
2176
+				);
2177
+			}
2178
+		}
2179
+		return true;
2180
+	}
2181
+
2182
+
2183
+
2184
+	/**
2185
+	 * This simply returns an array of model fields for this object
2186
+	 *
2187
+	 * @return array
2188
+	 * @throws \EE_Error
2189
+	 */
2190
+	public function model_field_array()
2191
+	{
2192
+		$fields = $this->get_model()->field_settings(false);
2193
+		$properties = array();
2194
+		//remove prepended underscore
2195
+		foreach ($fields as $field_name => $settings) {
2196
+			$properties[$field_name] = $this->get($field_name);
2197
+		}
2198
+		return $properties;
2199
+	}
2200
+
2201
+
2202
+
2203
+	/**
2204
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2205
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called (http://www.garfieldtech.com/blog/php-magic-call)
2206
+	 * and passed the method's name and arguments.
2207
+	 * Instead of requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that happen?)
2208
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg, filters_hook_espresso__EE_Answer__my_great_function)
2209
+	 * and accepts 2 arguments: the object on which the function was called, and an array of the original arguments passed to the function. Whatever their callback function returns will be returned by this function.
2210
+	 * Example: in functions.php (or in a plugin):
2211
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2212
+	 * function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2213
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2214
+	 *        return $previousReturnValue.$returnString;
2215
+	 * }
2216
+	 * require('EE_Answer.class.php');
2217
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2218
+	 * echo $answer->my_callback('monkeys',100);
2219
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2220
+	 *
2221
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2222
+	 * @param array  $args       array of original arguments passed to the function
2223
+	 * @throws EE_Error
2224
+	 * @return mixed whatever the plugin which calls add_filter decides
2225
+	 */
2226
+	public function __call($methodName, $args)
2227
+	{
2228
+		$className = get_class($this);
2229
+		$tagName = "FHEE__{$className}__{$methodName}";
2230
+		if ( ! has_filter($tagName)) {
2231
+			throw new EE_Error(
2232
+				sprintf(
2233
+					__(
2234
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2235
+						"event_espresso"
2236
+					),
2237
+					$methodName,
2238
+					$className,
2239
+					$tagName
2240
+				)
2241
+			);
2242
+		}
2243
+		return apply_filters($tagName, null, $this, $args);
2244
+	}
2245
+
2246
+
2247
+
2248
+	/**
2249
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2250
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2251
+	 *
2252
+	 * @param string $meta_key
2253
+	 * @param string $meta_value
2254
+	 * @param string $previous_value
2255
+	 * @return int records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2256
+	 * @throws \EE_Error
2257
+	 * NOTE: if the values haven't changed, returns 0
2258
+	 */
2259
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2260
+	{
2261
+		$query_params = array(
2262
+			array(
2263
+				'EXM_key'  => $meta_key,
2264
+				'OBJ_ID'   => $this->ID(),
2265
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2266
+			),
2267
+		);
2268
+		if ($previous_value !== null) {
2269
+			$query_params[0]['EXM_value'] = $meta_value;
2270
+		}
2271
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2272
+		if ( ! $existing_rows_like_that) {
2273
+			return $this->add_extra_meta($meta_key, $meta_value);
2274
+		} else {
2275
+			foreach ($existing_rows_like_that as $existing_row) {
2276
+				$existing_row->save(array('EXM_value' => $meta_value));
2277
+			}
2278
+			return count($existing_rows_like_that);
2279
+		}
2280
+	}
2281
+
2282
+
2283
+
2284
+	/**
2285
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2286
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2287
+	 * extra meta row was entered, false if not
2288
+	 *
2289
+	 * @param string  $meta_key
2290
+	 * @param string  $meta_value
2291
+	 * @param boolean $unique
2292
+	 * @return boolean
2293
+	 * @throws \EE_Error
2294
+	 */
2295
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2296
+	{
2297
+		if ($unique) {
2298
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2299
+				array(
2300
+					array(
2301
+						'EXM_key'  => $meta_key,
2302
+						'OBJ_ID'   => $this->ID(),
2303
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2304
+					),
2305
+				)
2306
+			);
2307
+			if ($existing_extra_meta) {
2308
+				return false;
2309
+			}
2310
+		}
2311
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2312
+			array(
2313
+				'EXM_key'   => $meta_key,
2314
+				'EXM_value' => $meta_value,
2315
+				'OBJ_ID'    => $this->ID(),
2316
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2317
+			)
2318
+		);
2319
+		$new_extra_meta->save();
2320
+		return true;
2321
+	}
2322
+
2323
+
2324
+
2325
+	/**
2326
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2327
+	 * is specified, only deletes extra meta records with that value.
2328
+	 *
2329
+	 * @param string $meta_key
2330
+	 * @param string $meta_value
2331
+	 * @return int number of extra meta rows deleted
2332
+	 * @throws \EE_Error
2333
+	 */
2334
+	public function delete_extra_meta($meta_key, $meta_value = null)
2335
+	{
2336
+		$query_params = array(
2337
+			array(
2338
+				'EXM_key'  => $meta_key,
2339
+				'OBJ_ID'   => $this->ID(),
2340
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2341
+			),
2342
+		);
2343
+		if ($meta_value !== null) {
2344
+			$query_params[0]['EXM_value'] = $meta_value;
2345
+		}
2346
+		return EEM_Extra_Meta::instance()->delete($query_params);
2347
+	}
2348
+
2349
+
2350
+
2351
+	/**
2352
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2353
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2354
+	 * You can specify $default is case you haven't found the extra meta
2355
+	 *
2356
+	 * @param string  $meta_key
2357
+	 * @param boolean $single
2358
+	 * @param mixed   $default if we don't find anything, what should we return?
2359
+	 * @return mixed single value if $single; array if ! $single
2360
+	 * @throws \EE_Error
2361
+	 */
2362
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2363
+	{
2364
+		if ($single) {
2365
+			$result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2366
+			if ($result instanceof EE_Extra_Meta) {
2367
+				return $result->value();
2368
+			} else {
2369
+				return $default;
2370
+			}
2371
+		} else {
2372
+			$results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2373
+			if ($results) {
2374
+				$values = array();
2375
+				foreach ($results as $result) {
2376
+					if ($result instanceof EE_Extra_Meta) {
2377
+						$values[$result->ID()] = $result->value();
2378
+					}
2379
+				}
2380
+				return $values;
2381
+			} else {
2382
+				return $default;
2383
+			}
2384
+		}
2385
+	}
2386
+
2387
+
2388
+
2389
+	/**
2390
+	 * Returns a simple array of all the extra meta associated with this model object.
2391
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2392
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2393
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2394
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2395
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2396
+	 * finally the extra meta's value as each sub-value. (eg array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2397
+	 *
2398
+	 * @param boolean $one_of_each_key
2399
+	 * @return array
2400
+	 * @throws \EE_Error
2401
+	 */
2402
+	public function all_extra_meta_array($one_of_each_key = true)
2403
+	{
2404
+		$return_array = array();
2405
+		if ($one_of_each_key) {
2406
+			$extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2407
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2408
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2409
+					$return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2410
+				}
2411
+			}
2412
+		} else {
2413
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2414
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2415
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2416
+					if ( ! isset($return_array[$extra_meta_obj->key()])) {
2417
+						$return_array[$extra_meta_obj->key()] = array();
2418
+					}
2419
+					$return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2420
+				}
2421
+			}
2422
+		}
2423
+		return $return_array;
2424
+	}
2425
+
2426
+
2427
+
2428
+	/**
2429
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2430
+	 *
2431
+	 * @return string
2432
+	 * @throws \EE_Error
2433
+	 */
2434
+	public function name()
2435
+	{
2436
+		//find a field that's not a text field
2437
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2438
+		if ($field_we_can_use) {
2439
+			return $this->get($field_we_can_use->get_name());
2440
+		} else {
2441
+			$first_few_properties = $this->model_field_array();
2442
+			$first_few_properties = array_slice($first_few_properties, 0, 3);
2443
+			$name_parts = array();
2444
+			foreach ($first_few_properties as $name => $value) {
2445
+				$name_parts[] = "$name:$value";
2446
+			}
2447
+			return implode(",", $name_parts);
2448
+		}
2449
+	}
2450
+
2451
+
2452
+
2453
+	/**
2454
+	 * in_entity_map
2455
+	 * Checks if this model object has been proven to already be in the entity map
2456
+	 *
2457
+	 * @return boolean
2458
+	 * @throws \EE_Error
2459
+	 */
2460
+	public function in_entity_map()
2461
+	{
2462
+		if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2463
+			//well, if we looked, did we find it in the entity map?
2464
+			return true;
2465
+		} else {
2466
+			return false;
2467
+		}
2468
+	}
2469
+
2470
+
2471
+
2472
+	/**
2473
+	 * refresh_from_db
2474
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
2475
+	 *
2476
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2477
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2478
+	 */
2479
+	public function refresh_from_db()
2480
+	{
2481
+		if ($this->ID() && $this->in_entity_map()) {
2482
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
2483
+		} else {
2484
+			//if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2485
+			//if it has an ID but it's not in the map, and you're asking me to refresh it
2486
+			//that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2487
+			//absolutely nothing in it for this ID
2488
+			if (WP_DEBUG) {
2489
+				throw new EE_Error(
2490
+					sprintf(
2491
+						__('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2492
+							'event_espresso'),
2493
+						$this->ID(),
2494
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2495
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2496
+					)
2497
+				);
2498
+			}
2499
+		}
2500
+	}
2501
+
2502
+
2503
+
2504
+	/**
2505
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2506
+	 * (probably a bad assumption they have made, oh well)
2507
+	 *
2508
+	 * @return string
2509
+	 */
2510
+	public function __toString()
2511
+	{
2512
+		try {
2513
+			return sprintf('%s (%s)', $this->name(), $this->ID());
2514
+		} catch (Exception $e) {
2515
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2516
+			return '';
2517
+		}
2518
+	}
2519
+
2520
+
2521
+
2522
+	/**
2523
+	 * Clear related model objects if they're already in the DB, because otherwise when we
2524
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
2525
+	 * This means if we have made changes to those related model objects, and want to unserialize
2526
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
2527
+	 * Instead, those related model objects should be directly serialized and stored.
2528
+	 * Eg, the following won't work:
2529
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2530
+	 * $att = $reg->attendee();
2531
+	 * $att->set( 'ATT_fname', 'Dirk' );
2532
+	 * update_option( 'my_option', serialize( $reg ) );
2533
+	 * //END REQUEST
2534
+	 * //START NEXT REQUEST
2535
+	 * $reg = get_option( 'my_option' );
2536
+	 * $reg->attendee()->save();
2537
+	 * And would need to be replace with:
2538
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2539
+	 * $att = $reg->attendee();
2540
+	 * $att->set( 'ATT_fname', 'Dirk' );
2541
+	 * update_option( 'my_option', serialize( $reg ) );
2542
+	 * //END REQUEST
2543
+	 * //START NEXT REQUEST
2544
+	 * $att = get_option( 'my_option' );
2545
+	 * $att->save();
2546
+	 *
2547
+	 * @return array
2548
+	 * @throws \EE_Error
2549
+	 */
2550
+	public function __sleep()
2551
+	{
2552
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
2553
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
2554
+				$classname = 'EE_' . $this->get_model()->get_this_model_name();
2555
+				if (
2556
+					$this->get_one_from_cache($relation_name) instanceof $classname
2557
+					&& $this->get_one_from_cache($relation_name)->ID()
2558
+				) {
2559
+					$this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2560
+				}
2561
+			}
2562
+		}
2563
+		$this->_props_n_values_provided_in_constructor = array();
2564
+		return array_keys(get_object_vars($this));
2565
+	}
2566
+
2567
+
2568
+
2569
+	/**
2570
+	 * restore _props_n_values_provided_in_constructor
2571
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2572
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
2573
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
2574
+	 */
2575
+	public function __wakeup()
2576
+	{
2577
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
2578
+	}
2579 2579
 
2580 2580
 
2581 2581
 
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -134,8 +134,8 @@  discard block
 block discarded – undo
134 134
             list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
135 135
         } else {
136 136
             //set default formats for date and time
137
-            $this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
138
-            $this->_tm_frmt = (string)get_option('time_format', 'g:i a');
137
+            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
138
+            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
139 139
         }
140 140
         //if db model is instantiating
141 141
         if ($bydb) {
@@ -443,7 +443,7 @@  discard block
 block discarded – undo
443 443
      */
444 444
     public function get_format($full = true)
445 445
     {
446
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
446
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
447 447
     }
448 448
 
449 449
 
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
         //verify the field exists
546 546
         $this->get_model()->field_settings_for($fieldname);
547 547
         $cache_type = $pretty ? 'pretty' : 'standard';
548
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
548
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
549 549
         if (isset($this->_cached_properties[$fieldname][$cache_type])) {
550 550
             return $this->_cached_properties[$fieldname][$cache_type];
551 551
         }
@@ -721,7 +721,7 @@  discard block
 block discarded – undo
721 721
     public function update_cache_after_object_save($relationName, EE_Base_Class $newly_saved_object, $current_cache_id = '')
722 722
     {
723 723
         // verify that incoming object is of the correct type
724
-        $obj_class = 'EE_' . $relationName;
724
+        $obj_class = 'EE_'.$relationName;
725 725
         if ($newly_saved_object instanceof $obj_class) {
726 726
             /* @type EE_Base_Class $newly_saved_object */
727 727
             // now get the type of relation
@@ -1218,7 +1218,7 @@  discard block
 block discarded – undo
1218 1218
      */
1219 1219
     public function get_i18n_datetime($field_name, $format = null)
1220 1220
     {
1221
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1221
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1222 1222
         return date_i18n(
1223 1223
             $format,
1224 1224
             EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
@@ -1342,8 +1342,8 @@  discard block
 block discarded – undo
1342 1342
         }
1343 1343
         $original_timezone = $this->_timezone;
1344 1344
         $this->set_timezone($timezone);
1345
-        $fn = (array)$field_name;
1346
-        $args = array_merge($fn, (array)$args);
1345
+        $fn = (array) $field_name;
1346
+        $args = array_merge($fn, (array) $args);
1347 1347
         if ( ! method_exists($this, $callback)) {
1348 1348
             throw new EE_Error(
1349 1349
                 sprintf(
@@ -1355,8 +1355,8 @@  discard block
 block discarded – undo
1355 1355
                 )
1356 1356
             );
1357 1357
         }
1358
-        $args = (array)$args;
1359
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1358
+        $args = (array) $args;
1359
+        $return = $prepend.call_user_func_array(array($this, $callback), $args).$append;
1360 1360
         $this->set_timezone($original_timezone);
1361 1361
         return $return;
1362 1362
     }
@@ -1489,7 +1489,7 @@  discard block
 block discarded – undo
1489 1489
          * @param array         $set_cols_n_values
1490 1490
          * @param EE_Base_Class $model_object
1491 1491
          */
1492
-        $set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values, $this);
1492
+        $set_cols_n_values = (array) apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values, $this);
1493 1493
         //set attributes as provided in $set_cols_n_values
1494 1494
         foreach ($set_cols_n_values as $column => $value) {
1495 1495
             $this->set($column, $value);
@@ -1542,8 +1542,8 @@  discard block
 block discarded – undo
1542 1542
                                 __('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1543 1543
                                     'event_espresso'),
1544 1544
                                 get_class($this),
1545
-                                get_class($this->get_model()) . '::instance()->add_to_entity_map()',
1546
-                                get_class($this->get_model()) . '::instance()->get_one_by_ID()',
1545
+                                get_class($this->get_model()).'::instance()->add_to_entity_map()',
1546
+                                get_class($this->get_model()).'::instance()->get_one_by_ID()',
1547 1547
                                 '<br />'
1548 1548
                             )
1549 1549
                         );
@@ -1804,7 +1804,7 @@  discard block
 block discarded – undo
1804 1804
         if (strpos($model_name, "EE_") === 0) {
1805 1805
             $model_classname = str_replace("EE_", "EEM_", $model_name);
1806 1806
         } else {
1807
-            $model_classname = "EEM_" . $model_name;
1807
+            $model_classname = "EEM_".$model_name;
1808 1808
         }
1809 1809
         return $model_classname;
1810 1810
     }
@@ -2162,7 +2162,7 @@  discard block
 block discarded – undo
2162 2162
      */
2163 2163
     protected function _property_exists($properties)
2164 2164
     {
2165
-        foreach ((array)$properties as $property_name) {
2165
+        foreach ((array) $properties as $property_name) {
2166 2166
             //first make sure this property exists
2167 2167
             if ( ! $this->_fields[$property_name]) {
2168 2168
                 throw new EE_Error(
@@ -2491,8 +2491,8 @@  discard block
 block discarded – undo
2491 2491
                         __('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2492 2492
                             'event_espresso'),
2493 2493
                         $this->ID(),
2494
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2495
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2494
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
2495
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
2496 2496
                     )
2497 2497
                 );
2498 2498
             }
@@ -2551,7 +2551,7 @@  discard block
 block discarded – undo
2551 2551
     {
2552 2552
         foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
2553 2553
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
2554
-                $classname = 'EE_' . $this->get_model()->get_this_model_name();
2554
+                $classname = 'EE_'.$this->get_model()->get_this_model_name();
2555 2555
                 if (
2556 2556
                     $this->get_one_from_cache($relation_name) instanceof $classname
2557 2557
                     && $this->get_one_from_cache($relation_name)->ID()
Please login to merge, or discard this patch.
core/middleware/EE_Recommended_Versions.core.php 1 patch
Indentation   +130 added lines, -130 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
 
@@ -18,141 +18,141 @@  discard block
 block discarded – undo
18 18
 {
19 19
 
20 20
 
21
-    /**
22
-     * converts a Request to a Response
23
-     *
24
-     * @param    EE_Request  $request
25
-     * @param    EE_Response $response
26
-     * @return    EE_Response
27
-     */
28
-    public function handle_request(EE_Request $request, EE_Response $response)
29
-    {
30
-        $this->_request = $request;
31
-        $this->_response = $response;
32
-        //$this->_response->add_output( "\n\t IN >>  " . __CLASS__ );
33
-        //$this->_response->set_notice( 1, 'hey look at this' );
34
-        // check required WP version
35
-        if ( ! $this->_minimum_wp_version_required()) {
36
-            $this->_request->un_set('activate', true);
37
-            add_action('admin_notices', array($this, 'minimum_wp_version_error'), 1);
38
-            //$this->_response->add_output( "\n<br />" . 'minimum_wp_version_error' );
39
-            $this->_response->terminate_request();
40
-            $this->_response->deactivate_plugin();
41
-        }
42
-        // check recommended PHP version
43
-        if ( ! $this->_minimum_php_version_recommended()) {
44
-            $this->_display_minimum_recommended_php_version_notice();
45
-        }
46
-        $this->_response = $this->process_request_stack($this->_request, $this->_response);
47
-        //$this->_response->add_output( "\n\t OUT << " . __CLASS__ );
48
-        return $this->_response;
49
-    }
50
-
51
-
52
-
53
-    /**
54
-     *    _check_wp_version
55
-     *
56
-     * @access private
57
-     * @param string $min_version
58
-     * @return boolean
59
-     */
60
-    private function _check_wp_version($min_version = EE_MIN_WP_VER_REQUIRED)
61
-    {
62
-        global $wp_version;
63
-        return version_compare($wp_version, $min_version, '>=') ? true : false;
64
-    }
65
-
66
-
67
-
68
-    /**
69
-     *    _minimum_wp_version_required
70
-     *
71
-     * @access private
72
-     * @return boolean
73
-     */
74
-    private function _minimum_wp_version_required()
75
-    {
76
-        return $this->_check_wp_version(EE_MIN_WP_VER_REQUIRED);
77
-    }
78
-
79
-
80
-
81
-    /**
82
-     *    _check_php_version
83
-     *
84
-     * @access private
85
-     * @param string $min_version
86
-     * @return boolean
87
-     */
88
-    private function _check_php_version($min_version = EE_MIN_PHP_VER_RECOMMENDED)
89
-    {
90
-        return version_compare(PHP_VERSION, $min_version, '>=') ? true : false;
91
-    }
92
-
93
-
94
-
95
-    /**
96
-     *    _minimum_php_version_recommended
97
-     *
98
-     * @access private
99
-     * @return boolean
100
-     */
101
-    private function _minimum_php_version_recommended()
102
-    {
103
-        return $this->_check_php_version(EE_MIN_PHP_VER_RECOMMENDED);
104
-    }
105
-
106
-
107
-
108
-    /**
109
-     *    minimum_wp_version_error
110
-     *
111
-     * @return void
112
-     */
113
-    public function minimum_wp_version_error()
114
-    {
115
-        global $wp_version;
116
-        ?>
21
+	/**
22
+	 * converts a Request to a Response
23
+	 *
24
+	 * @param    EE_Request  $request
25
+	 * @param    EE_Response $response
26
+	 * @return    EE_Response
27
+	 */
28
+	public function handle_request(EE_Request $request, EE_Response $response)
29
+	{
30
+		$this->_request = $request;
31
+		$this->_response = $response;
32
+		//$this->_response->add_output( "\n\t IN >>  " . __CLASS__ );
33
+		//$this->_response->set_notice( 1, 'hey look at this' );
34
+		// check required WP version
35
+		if ( ! $this->_minimum_wp_version_required()) {
36
+			$this->_request->un_set('activate', true);
37
+			add_action('admin_notices', array($this, 'minimum_wp_version_error'), 1);
38
+			//$this->_response->add_output( "\n<br />" . 'minimum_wp_version_error' );
39
+			$this->_response->terminate_request();
40
+			$this->_response->deactivate_plugin();
41
+		}
42
+		// check recommended PHP version
43
+		if ( ! $this->_minimum_php_version_recommended()) {
44
+			$this->_display_minimum_recommended_php_version_notice();
45
+		}
46
+		$this->_response = $this->process_request_stack($this->_request, $this->_response);
47
+		//$this->_response->add_output( "\n\t OUT << " . __CLASS__ );
48
+		return $this->_response;
49
+	}
50
+
51
+
52
+
53
+	/**
54
+	 *    _check_wp_version
55
+	 *
56
+	 * @access private
57
+	 * @param string $min_version
58
+	 * @return boolean
59
+	 */
60
+	private function _check_wp_version($min_version = EE_MIN_WP_VER_REQUIRED)
61
+	{
62
+		global $wp_version;
63
+		return version_compare($wp_version, $min_version, '>=') ? true : false;
64
+	}
65
+
66
+
67
+
68
+	/**
69
+	 *    _minimum_wp_version_required
70
+	 *
71
+	 * @access private
72
+	 * @return boolean
73
+	 */
74
+	private function _minimum_wp_version_required()
75
+	{
76
+		return $this->_check_wp_version(EE_MIN_WP_VER_REQUIRED);
77
+	}
78
+
79
+
80
+
81
+	/**
82
+	 *    _check_php_version
83
+	 *
84
+	 * @access private
85
+	 * @param string $min_version
86
+	 * @return boolean
87
+	 */
88
+	private function _check_php_version($min_version = EE_MIN_PHP_VER_RECOMMENDED)
89
+	{
90
+		return version_compare(PHP_VERSION, $min_version, '>=') ? true : false;
91
+	}
92
+
93
+
94
+
95
+	/**
96
+	 *    _minimum_php_version_recommended
97
+	 *
98
+	 * @access private
99
+	 * @return boolean
100
+	 */
101
+	private function _minimum_php_version_recommended()
102
+	{
103
+		return $this->_check_php_version(EE_MIN_PHP_VER_RECOMMENDED);
104
+	}
105
+
106
+
107
+
108
+	/**
109
+	 *    minimum_wp_version_error
110
+	 *
111
+	 * @return void
112
+	 */
113
+	public function minimum_wp_version_error()
114
+	{
115
+		global $wp_version;
116
+		?>
117 117
         <div class="error">
118 118
             <p>
119 119
                 <?php
120
-                printf(
121
-                        __('We\'re sorry, but Event Espresso requires WordPress version %1$s or greater in order to operate. You are currently running version %2$s.%3$sFor information on how to update your version of WordPress, please go to %4$s.',
122
-                                'event_espresso'),
123
-                        EE_MIN_WP_VER_REQUIRED,
124
-                        $wp_version,
125
-                        '<br/>',
126
-                        '<a href="http://codex.wordpress.org/Updating_WordPress">http://codex.wordpress.org/Updating_WordPress</a>'
127
-                );
128
-                ?>
120
+				printf(
121
+						__('We\'re sorry, but Event Espresso requires WordPress version %1$s or greater in order to operate. You are currently running version %2$s.%3$sFor information on how to update your version of WordPress, please go to %4$s.',
122
+								'event_espresso'),
123
+						EE_MIN_WP_VER_REQUIRED,
124
+						$wp_version,
125
+						'<br/>',
126
+						'<a href="http://codex.wordpress.org/Updating_WordPress">http://codex.wordpress.org/Updating_WordPress</a>'
127
+				);
128
+				?>
129 129
             </p>
130 130
         </div>
131 131
         <?php
132
-    }
133
-
134
-
135
-
136
-    /**
137
-     *    _display_minimum_recommended_php_version_notice
138
-     *
139
-     * @access private
140
-     * @return void
141
-     */
142
-    private function _display_minimum_recommended_php_version_notice()
143
-    {
144
-        EE_Error::add_persistent_admin_notice(
145
-                'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
146
-                sprintf(
147
-                        __('Event Espresso recommends PHP version %1$s or greater for optimal performance. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
148
-                                'event_espresso'),
149
-                        EE_MIN_PHP_VER_RECOMMENDED,
150
-                        PHP_VERSION,
151
-                        '<br/>',
152
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
153
-                )
154
-        );
155
-    }
132
+	}
133
+
134
+
135
+
136
+	/**
137
+	 *    _display_minimum_recommended_php_version_notice
138
+	 *
139
+	 * @access private
140
+	 * @return void
141
+	 */
142
+	private function _display_minimum_recommended_php_version_notice()
143
+	{
144
+		EE_Error::add_persistent_admin_notice(
145
+				'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
146
+				sprintf(
147
+						__('Event Espresso recommends PHP version %1$s or greater for optimal performance. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
148
+								'event_espresso'),
149
+						EE_MIN_PHP_VER_RECOMMENDED,
150
+						PHP_VERSION,
151
+						'<br/>',
152
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
153
+				)
154
+		);
155
+	}
156 156
 
157 157
 
158 158
 }
Please login to merge, or discard this patch.
core/EE_Encryption.core.php 2 patches
Indentation   +350 added lines, -351 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\interfaces\InterminableInterface;
2 2
 
3 3
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
4
-    exit('No direct script access allowed');
4
+	exit('No direct script access allowed');
5 5
 }
6 6
 
7 7
 
@@ -19,356 +19,355 @@  discard block
 block discarded – undo
19 19
 class EE_Encryption
20 20
 {
21 21
 
22
-    // instance of the EE_Encryption object
23
-    protected static $_instance;
24
-
25
-    protected        $_encryption_key;
26
-
27
-    protected        $_use_mcrypt = true;
28
-
29
-
30
-
31
-    /**
32
-     *    private constructor to prevent direct creation
33
-
34
-     */
35
-    private function __construct()
36
-    {
37
-        define('ESPRESSO_ENCRYPT', true);
38
-        if ( ! function_exists('mcrypt_encrypt')) {
39
-            $this->_use_mcrypt = false;
40
-        }
41
-    }
42
-
43
-
44
-
45
-    /**
46
-     *    singleton method used to instantiate class object
47
-     *
48
-     * @access public
49
-     * @return \EE_Encryption
50
-     */
51
-    public static function instance()
52
-    {
53
-        // check if class object is instantiated
54
-        if ( ! self::$_instance instanceof EE_Encryption) {
55
-            self::$_instance = new self();
56
-        }
57
-        return self::$_instance;
58
-    }
59
-
60
-
61
-
62
-    /**
63
-     *        get encryption key
64
-     *
65
-     * @access public
66
-     * @return string
67
-     */
68
-    public function get_encryption_key()
69
-    {
70
-        // if encryption key has not been set
71
-        if (empty($this->_encryption_key)) {
72
-            // retrieve encryption_key from db
73
-            $this->_encryption_key = get_option('ee_encryption_key', '');
74
-            // WHAT?? No encryption_key in the db ??
75
-            if ($this->_encryption_key === '') {
76
-                // let's make one. And md5 it to make it just the right size for a key
77
-                $new_key = md5($this->generate_random_string());
78
-                // now save it to the db for later
79
-                add_option('ee_encryption_key', $new_key);
80
-                // here's the key - FINALLY !
81
-                $this->_encryption_key = $new_key;
82
-            }
83
-        }
84
-        return $this->_encryption_key;
85
-    }
86
-
87
-
88
-
89
-    /**
90
-     * encrypts data
91
-     *
92
-     * @access   public
93
-     * @param string $text_string - the text to be encrypted
94
-     * @return string
95
-     */
96
-    public function encrypt($text_string = '')
97
-    {
98
-        // you give me nothing??? GET OUT !
99
-        if (empty($text_string)) {
100
-            return $text_string;
101
-        }
102
-        if ($this->_use_mcrypt) {
103
-            $encrypted_text = $this->m_encrypt($text_string);
104
-        } else {
105
-            $encrypted_text = $this->acme_encrypt($text_string);
106
-        }
107
-        return $encrypted_text;
108
-    }
109
-
110
-
111
-
112
-    /**
113
-     * decrypts data
114
-     *
115
-     * @access   public
116
-     * @param string $encrypted_text - the text to be decrypted
117
-     * @return string
118
-     */
119
-    public function decrypt($encrypted_text = '')
120
-    {
121
-        // you give me nothing??? GET OUT !
122
-        if (empty($encrypted_text)) {
123
-            return $encrypted_text;
124
-        }
125
-        // if PHP's mcrypt functions are installed then we'll use them
126
-        if ($this->_use_mcrypt) {
127
-            $decrypted_text = $this->m_decrypt($encrypted_text);
128
-        } else {
129
-            $decrypted_text = $this->acme_decrypt($encrypted_text);
130
-        }
131
-        return $decrypted_text;
132
-    }
133
-
134
-
135
-
136
-    /**
137
-     * encodes string with PHP's base64 encoding
138
-     * @source  http://php.net/manual/en/function.base64-encode.php
139
-     *
140
-     * @param string $text_string
141
-     * @internal param $string - the text to be encoded
142
-     * @return string
143
-     */
144
-    public function base64_string_encode($text_string = '')
145
-    {
146
-        // you give me nothing??? GET OUT !
147
-        if (empty($text_string) || ! function_exists('base64_encode')) {
148
-            return $text_string;
149
-        }
150
-        // encode
151
-        return base64_encode($text_string);
152
-    }
153
-
154
-
155
-
156
-    /**
157
-     * decodes string that has been encoded with PHP's base64 encoding
158
-     * @source  http://php.net/manual/en/function.base64-encode.php
159
-     *
160
-     * @param string $encoded_string
161
-     * @internal param $string - the text to be decoded
162
-     * @return string
163
-     */
164
-    public function base64_string_decode($encoded_string = '')
165
-    {
166
-        // you give me nothing??? GET OUT !
167
-        if (empty($encoded_string) || ! $this->valid_base_64($encoded_string)) {
168
-            return $encoded_string;
169
-        }
170
-        // decode
171
-        return base64_decode($encoded_string);
172
-    }
173
-
174
-
175
-
176
-    /**
177
-     * encodes  url string with PHP's base64 encoding
178
-     * @source  http://php.net/manual/en/function.base64-encode.php
179
-     *
180
-     * @access   public
181
-     * @param string $text_string
182
-     * @internal param $string - the text to be encoded
183
-     * @return string
184
-     */
185
-    public function base64_url_encode($text_string = '')
186
-    {
187
-        // you give me nothing??? GET OUT !
188
-        if (empty($text_string) || ! function_exists('base64_encode')) {
189
-            return $text_string;
190
-        }
191
-        // encode
192
-        $encoded_string = base64_encode($text_string);
193
-        // remove chars to make encoding more URL friendly
194
-        return strtr($encoded_string, '+/=', '-_,');
195
-    }
196
-
197
-
198
-
199
-    /**
200
-     * decodes  url string that has been encoded with PHP's base64 encoding
201
-     * @source  http://php.net/manual/en/function.base64-encode.php
202
-     *
203
-     * @access   public
204
-     * @param string $encoded_string
205
-     * @internal param $string - the text to be decoded
206
-     * @return string
207
-     */
208
-    public function base64_url_decode($encoded_string = '')
209
-    {
210
-        // you give me nothing??? GET OUT !
211
-        if (empty($encoded_string) || ! $this->valid_base_64($encoded_string)) {
212
-            return $encoded_string;
213
-        }
214
-        // replace previously removed characters
215
-        $encoded_string = strtr($encoded_string, '-_,', '+/=');
216
-        // decode
217
-        return base64_decode($encoded_string);
218
-    }
219
-
220
-
221
-
222
-    /**
223
-     * encrypts data using PHP's mcrypt functions
224
-     *
225
-     * @access   private
226
-     * @param string $text_string
227
-     * @internal param $string - the text to be encrypted
228
-     * @return string
229
-     */
230
-    private function m_encrypt($text_string = '')
231
-    {
232
-        // you give me nothing??? GET OUT !
233
-        if (empty($text_string)) {
234
-            return $text_string;
235
-        }
236
-        // get the initialization vector size
237
-        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
238
-        // initialization vector
239
-        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
240
-        // encrypt it
241
-        $encrypted_text = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->get_encryption_key(), $text_string, MCRYPT_MODE_ECB, $iv);
242
-        // trim and maybe encode
243
-        return function_exists('base64_encode') ? trim(base64_encode($encrypted_text)) : trim($encrypted_text);
244
-    }
245
-
246
-
247
-
248
-    /**
249
-     * decrypts data that has been encrypted with PHP's mcrypt functions
250
-     *
251
-     * @access   private
252
-     * @param string $encrypted_text
253
-     * @internal param $string - the text to be decrypted
254
-     * @return string
255
-     */
256
-    private function m_decrypt($encrypted_text = '')
257
-    {
258
-        // you give me nothing??? GET OUT !
259
-        if (empty($encrypted_text)) {
260
-            return $encrypted_text;
261
-        }
262
-        // decode
263
-        $encrypted_text = $this->valid_base_64($encrypted_text) ? base64_decode($encrypted_text) : $encrypted_text;
264
-        // get the initialization vector size
265
-        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
266
-        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
267
-        // decrypt it
268
-        $decrypted_text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->get_encryption_key(), $encrypted_text, MCRYPT_MODE_ECB, $iv);
269
-        $decrypted_text = trim($decrypted_text);
270
-        return $decrypted_text;
271
-    }
272
-
273
-
274
-
275
-    /**
276
-     * encrypts data for acme servers that didn't bother to install PHP mcrypt
277
-     *
278
-     * @source   : http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php
279
-     * @access   private
280
-     * @param string $text_string
281
-     * @internal param $string - the text to be decrypted
282
-     * @return string
283
-     */
284
-    private function acme_encrypt($text_string = '')
285
-    {
286
-        // you give me nothing??? GET OUT !
287
-        if (empty($text_string)) {
288
-            return $text_string;
289
-        }
290
-        $key_bits = str_split(str_pad('', strlen($text_string), $this->get_encryption_key(), STR_PAD_RIGHT));
291
-        $string_bits = str_split($text_string);
292
-        foreach ($string_bits as $k => $v) {
293
-            $temp = ord($v) + ord($key_bits[$k]);
294
-            $string_bits[$k] = chr($temp > 255 ? ($temp - 256) : $temp);
295
-        }
296
-        return function_exists('base64_encode') ? base64_encode(implode('', $string_bits)) : implode('', $string_bits);
297
-    }
298
-
299
-
300
-
301
-    /**
302
-     * decrypts data for acme servers that didn't bother to install PHP mcrypt
303
-     *
304
-     * @source   : http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php
305
-     * @param string $encrypted_text the text to be decrypted
306
-     * @return string
307
-     */
308
-    private function acme_decrypt($encrypted_text = '')
309
-    {
310
-        // you give me nothing??? GET OUT !
311
-        if (empty($encrypted_text)) {
312
-            return $encrypted_text;
313
-        }
314
-        // decode the data ?
315
-        $encrypted_text = $this->valid_base_64($encrypted_text) ? base64_decode($encrypted_text) : $encrypted_text;
316
-        $key_bits = str_split(str_pad('', strlen($encrypted_text), $this->get_encryption_key(), STR_PAD_RIGHT));
317
-        $string_bits = str_split($encrypted_text);
318
-        foreach ($string_bits as $k => $v) {
319
-            $temp = ord($v) - ord($key_bits[$k]);
320
-            $string_bits[$k] = chr($temp < 0 ? ($temp + 256) : $temp);
321
-        }
322
-        return implode('', $string_bits);
323
-    }
324
-
325
-
326
-
327
-    /**
328
-     * @see http://stackoverflow.com/questions/2556345/detect-base64-encoding-in-php#30231906
329
-     * @param $string
330
-     * @return bool
331
-     */
332
-    private function valid_base_64($string)
333
-    {
334
-        // ensure data is a string
335
-        if ( ! is_string($string) || ! function_exists('base64_decode')) {
336
-            return false;
337
-        }
338
-        $decoded = base64_decode($string, true);
339
-        // Check if there is no invalid character in string
340
-        if ( ! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
341
-            return false;
342
-        }
343
-        // Decode the string in strict mode and send the response
344
-        if ( ! base64_decode($string, true)) {
345
-            return false;
346
-        }
347
-        // Encode and compare it to original one
348
-        return base64_encode($decoded) === $string;
349
-    }
350
-
351
-
352
-
353
-    /**
354
-     * generate random string
355
-     *
356
-     * @source   : http://stackoverflow.com/questions/637278/what-is-the-best-way-to-generate-a-random-key-within-php
357
-     * @access   public
358
-     * @param int $length
359
-     * @internal param $string - number of characters for random string
360
-     * @return string
361
-     */
362
-    public function generate_random_string($length = 40)
363
-    {
364
-        $iterations = ceil($length / 40);
365
-        $random_string = '';
366
-        for ($i = 0; $i < $iterations; $i++) {
367
-            $random_string .= sha1(microtime(true) . mt_rand(10000, 90000));
368
-        }
369
-        $random_string = substr($random_string, 0, $length);
370
-        return $random_string;
371
-    }
22
+	// instance of the EE_Encryption object
23
+	protected static $_instance;
24
+
25
+	protected        $_encryption_key;
26
+
27
+	protected        $_use_mcrypt = true;
28
+
29
+
30
+
31
+	/**
32
+	 *    private constructor to prevent direct creation
33
+	 */
34
+	private function __construct()
35
+	{
36
+		define('ESPRESSO_ENCRYPT', true);
37
+		if ( ! function_exists('mcrypt_encrypt')) {
38
+			$this->_use_mcrypt = false;
39
+		}
40
+	}
41
+
42
+
43
+
44
+	/**
45
+	 *    singleton method used to instantiate class object
46
+	 *
47
+	 * @access public
48
+	 * @return \EE_Encryption
49
+	 */
50
+	public static function instance()
51
+	{
52
+		// check if class object is instantiated
53
+		if ( ! self::$_instance instanceof EE_Encryption) {
54
+			self::$_instance = new self();
55
+		}
56
+		return self::$_instance;
57
+	}
58
+
59
+
60
+
61
+	/**
62
+	 *        get encryption key
63
+	 *
64
+	 * @access public
65
+	 * @return string
66
+	 */
67
+	public function get_encryption_key()
68
+	{
69
+		// if encryption key has not been set
70
+		if (empty($this->_encryption_key)) {
71
+			// retrieve encryption_key from db
72
+			$this->_encryption_key = get_option('ee_encryption_key', '');
73
+			// WHAT?? No encryption_key in the db ??
74
+			if ($this->_encryption_key === '') {
75
+				// let's make one. And md5 it to make it just the right size for a key
76
+				$new_key = md5($this->generate_random_string());
77
+				// now save it to the db for later
78
+				add_option('ee_encryption_key', $new_key);
79
+				// here's the key - FINALLY !
80
+				$this->_encryption_key = $new_key;
81
+			}
82
+		}
83
+		return $this->_encryption_key;
84
+	}
85
+
86
+
87
+
88
+	/**
89
+	 * encrypts data
90
+	 *
91
+	 * @access   public
92
+	 * @param string $text_string - the text to be encrypted
93
+	 * @return string
94
+	 */
95
+	public function encrypt($text_string = '')
96
+	{
97
+		// you give me nothing??? GET OUT !
98
+		if (empty($text_string)) {
99
+			return $text_string;
100
+		}
101
+		if ($this->_use_mcrypt) {
102
+			$encrypted_text = $this->m_encrypt($text_string);
103
+		} else {
104
+			$encrypted_text = $this->acme_encrypt($text_string);
105
+		}
106
+		return $encrypted_text;
107
+	}
108
+
109
+
110
+
111
+	/**
112
+	 * decrypts data
113
+	 *
114
+	 * @access   public
115
+	 * @param string $encrypted_text - the text to be decrypted
116
+	 * @return string
117
+	 */
118
+	public function decrypt($encrypted_text = '')
119
+	{
120
+		// you give me nothing??? GET OUT !
121
+		if (empty($encrypted_text)) {
122
+			return $encrypted_text;
123
+		}
124
+		// if PHP's mcrypt functions are installed then we'll use them
125
+		if ($this->_use_mcrypt) {
126
+			$decrypted_text = $this->m_decrypt($encrypted_text);
127
+		} else {
128
+			$decrypted_text = $this->acme_decrypt($encrypted_text);
129
+		}
130
+		return $decrypted_text;
131
+	}
132
+
133
+
134
+
135
+	/**
136
+	 * encodes string with PHP's base64 encoding
137
+	 * @source  http://php.net/manual/en/function.base64-encode.php
138
+	 *
139
+	 * @param string $text_string
140
+	 * @internal param $string - the text to be encoded
141
+	 * @return string
142
+	 */
143
+	public function base64_string_encode($text_string = '')
144
+	{
145
+		// you give me nothing??? GET OUT !
146
+		if (empty($text_string) || ! function_exists('base64_encode')) {
147
+			return $text_string;
148
+		}
149
+		// encode
150
+		return base64_encode($text_string);
151
+	}
152
+
153
+
154
+
155
+	/**
156
+	 * decodes string that has been encoded with PHP's base64 encoding
157
+	 * @source  http://php.net/manual/en/function.base64-encode.php
158
+	 *
159
+	 * @param string $encoded_string
160
+	 * @internal param $string - the text to be decoded
161
+	 * @return string
162
+	 */
163
+	public function base64_string_decode($encoded_string = '')
164
+	{
165
+		// you give me nothing??? GET OUT !
166
+		if (empty($encoded_string) || ! $this->valid_base_64($encoded_string)) {
167
+			return $encoded_string;
168
+		}
169
+		// decode
170
+		return base64_decode($encoded_string);
171
+	}
172
+
173
+
174
+
175
+	/**
176
+	 * encodes  url string with PHP's base64 encoding
177
+	 * @source  http://php.net/manual/en/function.base64-encode.php
178
+	 *
179
+	 * @access   public
180
+	 * @param string $text_string
181
+	 * @internal param $string - the text to be encoded
182
+	 * @return string
183
+	 */
184
+	public function base64_url_encode($text_string = '')
185
+	{
186
+		// you give me nothing??? GET OUT !
187
+		if (empty($text_string) || ! function_exists('base64_encode')) {
188
+			return $text_string;
189
+		}
190
+		// encode
191
+		$encoded_string = base64_encode($text_string);
192
+		// remove chars to make encoding more URL friendly
193
+		return strtr($encoded_string, '+/=', '-_,');
194
+	}
195
+
196
+
197
+
198
+	/**
199
+	 * decodes  url string that has been encoded with PHP's base64 encoding
200
+	 * @source  http://php.net/manual/en/function.base64-encode.php
201
+	 *
202
+	 * @access   public
203
+	 * @param string $encoded_string
204
+	 * @internal param $string - the text to be decoded
205
+	 * @return string
206
+	 */
207
+	public function base64_url_decode($encoded_string = '')
208
+	{
209
+		// you give me nothing??? GET OUT !
210
+		if (empty($encoded_string) || ! $this->valid_base_64($encoded_string)) {
211
+			return $encoded_string;
212
+		}
213
+		// replace previously removed characters
214
+		$encoded_string = strtr($encoded_string, '-_,', '+/=');
215
+		// decode
216
+		return base64_decode($encoded_string);
217
+	}
218
+
219
+
220
+
221
+	/**
222
+	 * encrypts data using PHP's mcrypt functions
223
+	 *
224
+	 * @access   private
225
+	 * @param string $text_string
226
+	 * @internal param $string - the text to be encrypted
227
+	 * @return string
228
+	 */
229
+	private function m_encrypt($text_string = '')
230
+	{
231
+		// you give me nothing??? GET OUT !
232
+		if (empty($text_string)) {
233
+			return $text_string;
234
+		}
235
+		// get the initialization vector size
236
+		$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
237
+		// initialization vector
238
+		$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
239
+		// encrypt it
240
+		$encrypted_text = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->get_encryption_key(), $text_string, MCRYPT_MODE_ECB, $iv);
241
+		// trim and maybe encode
242
+		return function_exists('base64_encode') ? trim(base64_encode($encrypted_text)) : trim($encrypted_text);
243
+	}
244
+
245
+
246
+
247
+	/**
248
+	 * decrypts data that has been encrypted with PHP's mcrypt functions
249
+	 *
250
+	 * @access   private
251
+	 * @param string $encrypted_text
252
+	 * @internal param $string - the text to be decrypted
253
+	 * @return string
254
+	 */
255
+	private function m_decrypt($encrypted_text = '')
256
+	{
257
+		// you give me nothing??? GET OUT !
258
+		if (empty($encrypted_text)) {
259
+			return $encrypted_text;
260
+		}
261
+		// decode
262
+		$encrypted_text = $this->valid_base_64($encrypted_text) ? base64_decode($encrypted_text) : $encrypted_text;
263
+		// get the initialization vector size
264
+		$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
265
+		$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
266
+		// decrypt it
267
+		$decrypted_text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->get_encryption_key(), $encrypted_text, MCRYPT_MODE_ECB, $iv);
268
+		$decrypted_text = trim($decrypted_text);
269
+		return $decrypted_text;
270
+	}
271
+
272
+
273
+
274
+	/**
275
+	 * encrypts data for acme servers that didn't bother to install PHP mcrypt
276
+	 *
277
+	 * @source   : http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php
278
+	 * @access   private
279
+	 * @param string $text_string
280
+	 * @internal param $string - the text to be decrypted
281
+	 * @return string
282
+	 */
283
+	private function acme_encrypt($text_string = '')
284
+	{
285
+		// you give me nothing??? GET OUT !
286
+		if (empty($text_string)) {
287
+			return $text_string;
288
+		}
289
+		$key_bits = str_split(str_pad('', strlen($text_string), $this->get_encryption_key(), STR_PAD_RIGHT));
290
+		$string_bits = str_split($text_string);
291
+		foreach ($string_bits as $k => $v) {
292
+			$temp = ord($v) + ord($key_bits[$k]);
293
+			$string_bits[$k] = chr($temp > 255 ? ($temp - 256) : $temp);
294
+		}
295
+		return function_exists('base64_encode') ? base64_encode(implode('', $string_bits)) : implode('', $string_bits);
296
+	}
297
+
298
+
299
+
300
+	/**
301
+	 * decrypts data for acme servers that didn't bother to install PHP mcrypt
302
+	 *
303
+	 * @source   : http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php
304
+	 * @param string $encrypted_text the text to be decrypted
305
+	 * @return string
306
+	 */
307
+	private function acme_decrypt($encrypted_text = '')
308
+	{
309
+		// you give me nothing??? GET OUT !
310
+		if (empty($encrypted_text)) {
311
+			return $encrypted_text;
312
+		}
313
+		// decode the data ?
314
+		$encrypted_text = $this->valid_base_64($encrypted_text) ? base64_decode($encrypted_text) : $encrypted_text;
315
+		$key_bits = str_split(str_pad('', strlen($encrypted_text), $this->get_encryption_key(), STR_PAD_RIGHT));
316
+		$string_bits = str_split($encrypted_text);
317
+		foreach ($string_bits as $k => $v) {
318
+			$temp = ord($v) - ord($key_bits[$k]);
319
+			$string_bits[$k] = chr($temp < 0 ? ($temp + 256) : $temp);
320
+		}
321
+		return implode('', $string_bits);
322
+	}
323
+
324
+
325
+
326
+	/**
327
+	 * @see http://stackoverflow.com/questions/2556345/detect-base64-encoding-in-php#30231906
328
+	 * @param $string
329
+	 * @return bool
330
+	 */
331
+	private function valid_base_64($string)
332
+	{
333
+		// ensure data is a string
334
+		if ( ! is_string($string) || ! function_exists('base64_decode')) {
335
+			return false;
336
+		}
337
+		$decoded = base64_decode($string, true);
338
+		// Check if there is no invalid character in string
339
+		if ( ! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
340
+			return false;
341
+		}
342
+		// Decode the string in strict mode and send the response
343
+		if ( ! base64_decode($string, true)) {
344
+			return false;
345
+		}
346
+		// Encode and compare it to original one
347
+		return base64_encode($decoded) === $string;
348
+	}
349
+
350
+
351
+
352
+	/**
353
+	 * generate random string
354
+	 *
355
+	 * @source   : http://stackoverflow.com/questions/637278/what-is-the-best-way-to-generate-a-random-key-within-php
356
+	 * @access   public
357
+	 * @param int $length
358
+	 * @internal param $string - number of characters for random string
359
+	 * @return string
360
+	 */
361
+	public function generate_random_string($length = 40)
362
+	{
363
+		$iterations = ceil($length / 40);
364
+		$random_string = '';
365
+		for ($i = 0; $i < $iterations; $i++) {
366
+			$random_string .= sha1(microtime(true) . mt_rand(10000, 90000));
367
+		}
368
+		$random_string = substr($random_string, 0, $length);
369
+		return $random_string;
370
+	}
372 371
 
373 372
 
374 373
 
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -364,7 +364,7 @@
 block discarded – undo
364 364
         $iterations = ceil($length / 40);
365 365
         $random_string = '';
366 366
         for ($i = 0; $i < $iterations; $i++) {
367
-            $random_string .= sha1(microtime(true) . mt_rand(10000, 90000));
367
+            $random_string .= sha1(microtime(true).mt_rand(10000, 90000));
368 368
         }
369 369
         $random_string = substr($random_string, 0, $length);
370 370
         return $random_string;
Please login to merge, or discard this patch.
core/libraries/form_sections/base/EE_Form_Section_Proper.form.php 1 patch
Indentation   +1348 added lines, -1348 removed lines patch added patch discarded remove patch
@@ -13,1354 +13,1354 @@
 block discarded – undo
13 13
 class EE_Form_Section_Proper extends EE_Form_Section_Validatable
14 14
 {
15 15
 
16
-    const SUBMITTED_FORM_DATA_SSN_KEY = 'submitted_form_data';
17
-
18
-    /**
19
-     * Subsections
20
-     *
21
-     * @var EE_Form_Section_Validatable[]
22
-     */
23
-    protected $_subsections = array();
24
-
25
-    /**
26
-     * Strategy for laying out the form
27
-     *
28
-     * @var EE_Form_Section_Layout_Base
29
-     */
30
-    protected $_layout_strategy;
31
-
32
-    /**
33
-     * Whether or not this form has received and validated a form submission yet
34
-     *
35
-     * @var boolean
36
-     */
37
-    protected $_received_submission = false;
38
-
39
-    /**
40
-     * message displayed to users upon successful form submission
41
-     *
42
-     * @var string
43
-     */
44
-    protected $_form_submission_success_message = '';
45
-
46
-    /**
47
-     * message displayed to users upon unsuccessful form submission
48
-     *
49
-     * @var string
50
-     */
51
-    protected $_form_submission_error_message = '';
52
-
53
-    /**
54
-     * Stores all the data that will localized for form validation
55
-     *
56
-     * @var array
57
-     */
58
-    static protected $_js_localization = array();
59
-
60
-    /**
61
-     * whether or not the form's localized validation JS vars have been set
62
-     *
63
-     * @type boolean
64
-     */
65
-    static protected $_scripts_localized = false;
66
-
67
-
68
-
69
-    /**
70
-     * when constructing a proper form section, calls _construct_finalize on children
71
-     * so that they know who their parent is, and what name they've been given.
72
-     *
73
-     * @param array $options_array   {
74
-     * @type        $subsections     EE_Form_Section_Validatable[] where keys are the section's name
75
-     * @type        $include         string[] numerically-indexed where values are section names to be included,
76
-     *                               and in that order. This is handy if you want
77
-     *                               the subsections to be ordered differently than the default, and if you override
78
-     *                               which fields are shown
79
-     * @type        $exclude         string[] values are subsections to be excluded. This is handy if you want
80
-     *                               to remove certain default subsections (note: if you specify BOTH 'include' AND
81
-     *                               'exclude', the inclusions will be applied first, and the exclusions will exclude
82
-     *                               items from that list of inclusions)
83
-     * @type        $layout_strategy EE_Form_Section_Layout_Base strategy for laying out the form
84
-     *                               } @see EE_Form_Section_Validatable::__construct()
85
-     * @throws \EE_Error
86
-     */
87
-    public function __construct($options_array = array())
88
-    {
89
-        $options_array = (array)apply_filters('FHEE__EE_Form_Section_Proper___construct__options_array', $options_array,
90
-            $this);
91
-        //call parent first, as it may be setting the name
92
-        parent::__construct($options_array);
93
-        //if they've included subsections in the constructor, add them now
94
-        if (isset($options_array['include'])) {
95
-            //we are going to make sure we ONLY have those subsections to include
96
-            //AND we are going to make sure they're in that specified order
97
-            $reordered_subsections = array();
98
-            foreach ($options_array['include'] as $input_name) {
99
-                if (isset($this->_subsections[$input_name])) {
100
-                    $reordered_subsections[$input_name] = $this->_subsections[$input_name];
101
-                }
102
-            }
103
-            $this->_subsections = $reordered_subsections;
104
-        }
105
-        if (isset($options_array['exclude'])) {
106
-            $exclude = $options_array['exclude'];
107
-            $this->_subsections = array_diff_key($this->_subsections, array_flip($exclude));
108
-        }
109
-        if (isset($options_array['layout_strategy'])) {
110
-            $this->_layout_strategy = $options_array['layout_strategy'];
111
-        }
112
-        if ( ! $this->_layout_strategy) {
113
-            $this->_layout_strategy = is_admin() ? new EE_Admin_Two_Column_Layout() : new EE_Two_Column_Layout();
114
-        }
115
-        $this->_layout_strategy->_construct_finalize($this);
116
-        //ok so we are definitely going to want the forms JS,
117
-        //so enqueue it or remember to enqueue it during wp_enqueue_scripts
118
-        if (did_action('wp_enqueue_scripts')
119
-            || did_action('admin_enqueue_scripts')
120
-        ) {
121
-            //ok so they've constructed this object after when they should have.
122
-            //just enqueue the generic form scripts and initialize the form immediately in the JS
123
-            \EE_Form_Section_Proper::wp_enqueue_scripts(true);
124
-        } else {
125
-            add_action('wp_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
126
-            add_action('admin_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
127
-        }
128
-        add_action('wp_footer', array($this, 'ensure_scripts_localized'), 1);
129
-        if (isset($options_array['name'])) {
130
-            $this->_construct_finalize(null, $options_array['name']);
131
-        }
132
-    }
133
-
134
-
135
-
136
-    /**
137
-     * Finishes construction given the parent form section and this form section's name
138
-     *
139
-     * @param EE_Form_Section_Proper $parent_form_section
140
-     * @param string                 $name
141
-     * @throws \EE_Error
142
-     */
143
-    public function _construct_finalize($parent_form_section, $name)
144
-    {
145
-        parent::_construct_finalize($parent_form_section, $name);
146
-        $this->_set_default_name_if_empty();
147
-        $this->_set_default_html_id_if_empty();
148
-        foreach ($this->_subsections as $subsection_name => $subsection) {
149
-            if ($subsection instanceof EE_Form_Section_Base) {
150
-                $subsection->_construct_finalize($this, $subsection_name);
151
-            } else {
152
-                throw new EE_Error(
153
-                    sprintf(
154
-                        __('Subsection "%s" is not an instanceof EE_Form_Section_Base on form "%s". It is a "%s"',
155
-                            'event_espresso'),
156
-                        $subsection_name,
157
-                        get_class($this),
158
-                        $subsection ? get_class($subsection) : __('NULL', 'event_espresso')
159
-                    )
160
-                );
161
-            }
162
-        }
163
-        do_action('AHEE__EE_Form_Section_Proper___construct_finalize__end', $this, $parent_form_section, $name);
164
-    }
165
-
166
-
167
-
168
-    /**
169
-     * Gets the layout strategy for this form section
170
-     *
171
-     * @return EE_Form_Section_Layout_Base
172
-     */
173
-    public function get_layout_strategy()
174
-    {
175
-        return $this->_layout_strategy;
176
-    }
177
-
178
-
179
-
180
-    /**
181
-     * Gets the HTML for a single input for this form section according
182
-     * to the layout strategy
183
-     *
184
-     * @param EE_Form_Input_Base $input
185
-     * @return string
186
-     */
187
-    public function get_html_for_input($input)
188
-    {
189
-        return $this->_layout_strategy->layout_input($input);
190
-    }
191
-
192
-
193
-
194
-    /**
195
-     * was_submitted - checks if form inputs are present in request data
196
-     * Basically an alias for form_data_present_in() (which is used by both
197
-     * proper form sections and form inputs)
198
-     *
199
-     * @param null $form_data
200
-     * @return boolean
201
-     */
202
-    public function was_submitted($form_data = null)
203
-    {
204
-        return $this->form_data_present_in($form_data);
205
-    }
206
-
207
-
208
-
209
-    /**
210
-     * After the form section is initially created, call this to sanitize the data in the submission
211
-     * which relates to this form section, validate it, and set it as properties on the form.
212
-     *
213
-     * @param array|null $req_data should usually be $_POST (the default).
214
-     *                             However, you CAN supply a different array.
215
-     *                             Consider using set_defaults() instead however.
216
-     *                             (If you rendered the form in the page using echo $form_x->get_html()
217
-     *                             the inputs will have the correct name in the request data for this function
218
-     *                             to find them and populate the form with them.
219
-     *                             If you have a flat form (with only input subsections),
220
-     *                             you can supply a flat array where keys
221
-     *                             are the form input names and values are their values)
222
-     * @param boolean    $validate whether or not to perform validation on this data. Default is,
223
-     *                             of course, to validate that data, and set errors on the invalid values.
224
-     *                             But if the data has already been validated
225
-     *                             (eg you validated the data then stored it in the DB)
226
-     *                             you may want to skip this step.
227
-     */
228
-    public function receive_form_submission($req_data = null, $validate = true)
229
-    {
230
-        $req_data = apply_filters('FHEE__EE_Form_Section_Proper__receive_form_submission__req_data', $req_data, $this,
231
-            $validate);
232
-        if ($req_data === null) {
233
-            $req_data = array_merge($_GET, $_POST);
234
-        }
235
-        $req_data = apply_filters('FHEE__EE_Form_Section_Proper__receive_form_submission__request_data', $req_data,
236
-            $this);
237
-        $this->_normalize($req_data);
238
-        if ($validate) {
239
-            $this->_validate();
240
-            //if it's invalid, we're going to want to re-display so remember what they submitted
241
-            if ( ! $this->is_valid()) {
242
-                $this->store_submitted_form_data_in_session();
243
-            }
244
-        }
245
-        do_action('AHEE__EE_Form_Section_Proper__receive_form_submission__end', $req_data, $this, $validate);
246
-    }
247
-
248
-
249
-
250
-    /**
251
-     * caches the originally submitted input values in the session
252
-     * so that they can be used to repopulate the form if it failed validation
253
-     *
254
-     * @return boolean whether or not the data was successfully stored in the session
255
-     */
256
-    protected function store_submitted_form_data_in_session()
257
-    {
258
-        return EE_Registry::instance()->SSN->set_session_data(
259
-            array(
260
-                \EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY => $this->submitted_values(true),
261
-            )
262
-        );
263
-    }
264
-
265
-
266
-
267
-    /**
268
-     * retrieves the originally submitted input values in the session
269
-     * so that they can be used to repopulate the form if it failed validation
270
-     *
271
-     * @return array
272
-     */
273
-    protected function get_submitted_form_data_from_session()
274
-    {
275
-        $session = EE_Registry::instance()->SSN;
276
-        if ($session instanceof EE_Session) {
277
-            return $session->get_session_data(
278
-                \EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY
279
-            );
280
-        } else {
281
-            return array();
282
-        }
283
-    }
284
-
285
-
286
-
287
-    /**
288
-     * flushed the originally submitted input values from the session
289
-     *
290
-     * @return boolean whether or not the data was successfully removed from the session
291
-     */
292
-    protected function flush_submitted_form_data_from_session()
293
-    {
294
-        return EE_Registry::instance()->SSN->reset_data(
295
-            array(\EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY)
296
-        );
297
-    }
298
-
299
-
300
-
301
-    /**
302
-     * Populates this form and its subsections with data from the session.
303
-     * (Wrapper for EE_Form_Section_Proper::receive_form_submission, so it shows
304
-     * validation errors when displaying too)
305
-     * Returns true if the form was populated from the session, false otherwise
306
-     *
307
-     * @return boolean
308
-     */
309
-    public function populate_from_session()
310
-    {
311
-        $form_data_in_session = $this->get_submitted_form_data_from_session();
312
-        if (empty($form_data_in_session)) {
313
-            return false;
314
-        }
315
-        $this->receive_form_submission($form_data_in_session);
316
-        $this->flush_submitted_form_data_from_session();
317
-        if ($this->form_data_present_in($form_data_in_session)) {
318
-            return true;
319
-        } else {
320
-            return false;
321
-        }
322
-    }
323
-
324
-
325
-
326
-    /**
327
-     * Populates the default data for the form, given an array where keys are
328
-     * the input names, and values are their values (preferably normalized to be their
329
-     * proper PHP types, not all strings... although that should be ok too).
330
-     * Proper subsections are sub-arrays, the key being the subsection's name, and
331
-     * the value being an array formatted in teh same way
332
-     *
333
-     * @param array $default_data
334
-     */
335
-    public function populate_defaults($default_data)
336
-    {
337
-        foreach ($this->subsections() as $subsection_name => $subsection) {
338
-            if (isset($default_data[$subsection_name])) {
339
-                if ($subsection instanceof EE_Form_Input_Base) {
340
-                    $subsection->set_default($default_data[$subsection_name]);
341
-                } elseif ($subsection instanceof EE_Form_Section_Proper) {
342
-                    $subsection->populate_defaults($default_data[$subsection_name]);
343
-                }
344
-            }
345
-        }
346
-    }
347
-
348
-
349
-
350
-    /**
351
-     * returns true if subsection exists
352
-     *
353
-     * @param string $name
354
-     * @return boolean
355
-     */
356
-    public function subsection_exists($name)
357
-    {
358
-        return isset($this->_subsections[$name]) ? true : false;
359
-    }
360
-
361
-
362
-
363
-    /**
364
-     * Gets the subsection specified by its name
365
-     *
366
-     * @param string  $name
367
-     * @param boolean $require_construction_to_be_finalized most client code should leave this as TRUE
368
-     *                                                      so that the inputs will be properly configured.
369
-     *                                                      However, some client code may be ok
370
-     *                                                      with construction finalize being called later
371
-     *                                                      (realizing that the subsections' html names
372
-     *                                                      might not be set yet, etc.)
373
-     * @return EE_Form_Section_Base
374
-     * @throws \EE_Error
375
-     */
376
-    public function get_subsection($name, $require_construction_to_be_finalized = true)
377
-    {
378
-        if ($require_construction_to_be_finalized) {
379
-            $this->ensure_construct_finalized_called();
380
-        }
381
-        return $this->subsection_exists($name) ? $this->_subsections[$name] : null;
382
-    }
383
-
384
-
385
-
386
-    /**
387
-     * Gets all the validatable subsections of this form section
388
-     *
389
-     * @return EE_Form_Section_Validatable[]
390
-     */
391
-    public function get_validatable_subsections()
392
-    {
393
-        $validatable_subsections = array();
394
-        foreach ($this->subsections() as $name => $obj) {
395
-            if ($obj instanceof EE_Form_Section_Validatable) {
396
-                $validatable_subsections[$name] = $obj;
397
-            }
398
-        }
399
-        return $validatable_subsections;
400
-    }
401
-
402
-
403
-
404
-    /**
405
-     * Gets an input by the given name. If not found, or if its not an EE_FOrm_Input_Base child,
406
-     * throw an EE_Error.
407
-     *
408
-     * @param string  $name
409
-     * @param boolean $require_construction_to_be_finalized most client code should
410
-     *                                                      leave this as TRUE so that the inputs will be properly
411
-     *                                                      configured. However, some client code may be ok with
412
-     *                                                      construction finalize being called later
413
-     *                                                      (realizing that the subsections' html names might not be
414
-     *                                                      set yet, etc.)
415
-     * @return EE_Form_Input_Base
416
-     * @throws EE_Error
417
-     */
418
-    public function get_input($name, $require_construction_to_be_finalized = true)
419
-    {
420
-        $subsection = $this->get_subsection($name, $require_construction_to_be_finalized);
421
-        if ( ! $subsection instanceof EE_Form_Input_Base) {
422
-            throw new EE_Error(
423
-                sprintf(
424
-                    __(
425
-                        "Subsection '%s' is not an instanceof EE_Form_Input_Base on form '%s'. It is a '%s'",
426
-                        'event_espresso'
427
-                    ),
428
-                    $name,
429
-                    get_class($this),
430
-                    $subsection ? get_class($subsection) : __("NULL", 'event_espresso')
431
-                )
432
-            );
433
-        }
434
-        return $subsection;
435
-    }
436
-
437
-
438
-
439
-    /**
440
-     * Like get_input(), gets the proper subsection of the form given the name,
441
-     * otherwise throws an EE_Error
442
-     *
443
-     * @param string  $name
444
-     * @param boolean $require_construction_to_be_finalized most client code should
445
-     *                                                      leave this as TRUE so that the inputs will be properly
446
-     *                                                      configured. However, some client code may be ok with
447
-     *                                                      construction finalize being called later
448
-     *                                                      (realizing that the subsections' html names might not be
449
-     *                                                      set yet, etc.)
450
-     * @return EE_Form_Section_Proper
451
-     * @throws EE_Error
452
-     */
453
-    public function get_proper_subsection($name, $require_construction_to_be_finalized = true)
454
-    {
455
-        $subsection = $this->get_subsection($name, $require_construction_to_be_finalized);
456
-        if ( ! $subsection instanceof EE_Form_Section_Proper) {
457
-            throw new EE_Error(
458
-                sprintf(
459
-                    __("Subsection '%'s is not an instanceof EE_Form_Section_Proper on form '%s'", 'event_espresso'),
460
-                    $name,
461
-                    get_class($this)
462
-                )
463
-            );
464
-        }
465
-        return $subsection;
466
-    }
467
-
468
-
469
-
470
-    /**
471
-     * Gets the value of the specified input. Should be called after receive_form_submission()
472
-     * or populate_defaults() on the form, where the normalized value on the input is set.
473
-     *
474
-     * @param string $name
475
-     * @return mixed depending on the input's type and its normalization strategy
476
-     * @throws \EE_Error
477
-     */
478
-    public function get_input_value($name)
479
-    {
480
-        $input = $this->get_input($name);
481
-        return $input->normalized_value();
482
-    }
483
-
484
-
485
-
486
-    /**
487
-     * Checks if this form section itself is valid, and then checks its subsections
488
-     *
489
-     * @throws EE_Error
490
-     * @return boolean
491
-     */
492
-    public function is_valid()
493
-    {
494
-        if ( ! $this->has_received_submission()) {
495
-            throw new EE_Error(
496
-                sprintf(
497
-                    __(
498
-                        "You cannot check if a form is valid before receiving the form submission using receive_form_submission",
499
-                        "event_espresso"
500
-                    )
501
-                )
502
-            );
503
-        }
504
-        if ( ! parent::is_valid()) {
505
-            return false;
506
-        }
507
-        // ok so no general errors to this entire form section.
508
-        // so let's check the subsections, but only set errors if that hasn't been done yet
509
-        $set_submission_errors = $this->submission_error_message() === '' ? true : false;
510
-        foreach ($this->get_validatable_subsections() as $subsection) {
511
-            if ( ! $subsection->is_valid() || $subsection->get_validation_error_string() !== '') {
512
-                if ($set_submission_errors) {
513
-                    $this->set_submission_error_message($subsection->get_validation_error_string());
514
-                }
515
-                return false;
516
-            }
517
-        }
518
-        return true;
519
-    }
520
-
521
-
522
-
523
-    /**
524
-     * gets teh default name of this form section if none is specified
525
-     *
526
-     * @return string
527
-     */
528
-    protected function _set_default_name_if_empty()
529
-    {
530
-        if ( ! $this->_name) {
531
-            $classname = get_class($this);
532
-            $default_name = str_replace("EE_", "", $classname);
533
-            $this->_name = $default_name;
534
-        }
535
-    }
536
-
537
-
538
-
539
-    /**
540
-     * Returns the HTML for the form, except for the form opening and closing tags
541
-     * (as the form section doesn't know where you necessarily want to send the information to),
542
-     * and except for a submit button. Enqueus JS and CSS; if called early enough we will
543
-     * try to enqueue them in the header, otherwise they'll be enqueued in the footer.
544
-     * Not doing_it_wrong because theoretically this CAN be used properly,
545
-     * provided its used during "wp_enqueue_scripts", or it doesn't need to enqueue
546
-     * any CSS.
547
-     *
548
-     * @throws \EE_Error
549
-     */
550
-    public function get_html_and_js()
551
-    {
552
-        $this->enqueue_js();
553
-        return $this->get_html();
554
-    }
555
-
556
-
557
-
558
-    /**
559
-     * returns HTML for displaying this form section. recursively calls display_section() on all subsections
560
-     *
561
-     * @param bool $display_previously_submitted_data
562
-     * @return string
563
-     */
564
-    public function get_html($display_previously_submitted_data = true)
565
-    {
566
-        $this->ensure_construct_finalized_called();
567
-        if ($display_previously_submitted_data) {
568
-            $this->populate_from_session();
569
-        }
570
-        return $this->_layout_strategy->layout_form();
571
-    }
572
-
573
-
574
-
575
-    /**
576
-     * enqueues JS and CSS for the form.
577
-     * It is preferred to call this before wp_enqueue_scripts so the
578
-     * scripts and styles can be put in the header, but if called later
579
-     * they will be put in the footer (which is OK for JS, but in HTML4 CSS should
580
-     * only be in the header; but in HTML5 its ok in the body.
581
-     * See http://stackoverflow.com/questions/4957446/load-external-css-file-in-body-tag.
582
-     * So if your form enqueues CSS, it's preferred to call this before wp_enqueue_scripts.)
583
-     *
584
-     * @return string
585
-     * @throws \EE_Error
586
-     */
587
-    public function enqueue_js()
588
-    {
589
-        $this->_enqueue_and_localize_form_js();
590
-        foreach ($this->subsections() as $subsection) {
591
-            $subsection->enqueue_js();
592
-        }
593
-    }
594
-
595
-
596
-
597
-    /**
598
-     * adds a filter so that jquery validate gets enqueued in EE_System::wp_enqueue_scripts().
599
-     * This must be done BEFORE wp_enqueue_scripts() gets called, which is on
600
-     * the wp_enqueue_scripts hook.
601
-     * However, registering the form js and localizing it can happen when we
602
-     * actually output the form (which is preferred, seeing how teh form's fields
603
-     * could change until it's actually outputted)
604
-     *
605
-     * @param boolean $init_form_validation_automatically whether or not we want the form validation
606
-     *                                                    to be triggered automatically or not
607
-     * @return void
608
-     */
609
-    public static function wp_enqueue_scripts($init_form_validation_automatically = true)
610
-    {
611
-        add_filter('FHEE_load_jquery_validate', '__return_true');
612
-        wp_register_script(
613
-            'ee_form_section_validation',
614
-            EE_GLOBAL_ASSETS_URL . 'scripts' . DS . 'form_section_validation.js',
615
-            array('jquery-validate', 'jquery-ui-datepicker', 'jquery-validate-extra-methods'),
616
-            EVENT_ESPRESSO_VERSION,
617
-            true
618
-        );
619
-        wp_localize_script(
620
-            'ee_form_section_validation',
621
-            'ee_form_section_validation_init',
622
-            array('init' => $init_form_validation_automatically ? true : false)
623
-        );
624
-    }
625
-
626
-
627
-
628
-    /**
629
-     * gets the variables used by form_section_validation.js.
630
-     * This needs to be called AFTER we've called $this->_enqueue_jquery_validate_script,
631
-     * but before the wordpress hook wp_loaded
632
-     *
633
-     * @throws \EE_Error
634
-     */
635
-    public function _enqueue_and_localize_form_js()
636
-    {
637
-        $this->ensure_construct_finalized_called();
638
-        //actually, we don't want to localize just yet. There may be other forms on the page.
639
-        //so we need to add our form section data to a static variable accessible by all form sections
640
-        //and localize it just before the footer
641
-        $this->localize_validation_rules();
642
-        add_action('wp_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'), 2);
643
-        add_action('admin_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'));
644
-    }
645
-
646
-
647
-
648
-    /**
649
-     * add our form section data to a static variable accessible by all form sections
650
-     *
651
-     * @param bool $return_for_subsection
652
-     * @return void
653
-     * @throws \EE_Error
654
-     */
655
-    public function localize_validation_rules($return_for_subsection = false)
656
-    {
657
-        // we only want to localize vars ONCE for the entire form,
658
-        // so if the form section doesn't have a parent, then it must be the top dog
659
-        if ($return_for_subsection || ! $this->parent_section()) {
660
-            EE_Form_Section_Proper::$_js_localization['form_data'][$this->html_id()] = array(
661
-                'form_section_id'  => $this->html_id(true),
662
-                'validation_rules' => $this->get_jquery_validation_rules(),
663
-                'other_data'       => $this->get_other_js_data(),
664
-                'errors'           => $this->subsection_validation_errors_by_html_name(),
665
-            );
666
-            EE_Form_Section_Proper::$_scripts_localized = true;
667
-        }
668
-    }
669
-
670
-
671
-
672
-    /**
673
-     * Gets an array of extra data that will be useful for client-side javascript.
674
-     * This is primarily data added by inputs and forms in addition to any
675
-     * scripts they might enqueue
676
-     *
677
-     * @param array $form_other_js_data
678
-     * @return array
679
-     */
680
-    public function get_other_js_data($form_other_js_data = array())
681
-    {
682
-        foreach ($this->subsections() as $subsection) {
683
-            $form_other_js_data = $subsection->get_other_js_data($form_other_js_data);
684
-        }
685
-        return $form_other_js_data;
686
-    }
687
-
688
-
689
-
690
-    /**
691
-     * Gets a flat array of inputs for this form section and its subsections.
692
-     * Keys are their form names, and values are the inputs themselves
693
-     *
694
-     * @return EE_Form_Input_Base
695
-     */
696
-    public function inputs_in_subsections()
697
-    {
698
-        $inputs = array();
699
-        foreach ($this->subsections() as $subsection) {
700
-            if ($subsection instanceof EE_Form_Input_Base) {
701
-                $inputs[$subsection->html_name()] = $subsection;
702
-            } elseif ($subsection instanceof EE_Form_Section_Proper) {
703
-                $inputs += $subsection->inputs_in_subsections();
704
-            }
705
-        }
706
-        return $inputs;
707
-    }
708
-
709
-
710
-
711
-    /**
712
-     * Gets a flat array of all the validation errors.
713
-     * Keys are html names (because those should be unique)
714
-     * and values are a string of all their validation errors
715
-     *
716
-     * @return string[]
717
-     */
718
-    public function subsection_validation_errors_by_html_name()
719
-    {
720
-        $inputs = $this->inputs();
721
-        $errors = array();
722
-        foreach ($inputs as $form_input) {
723
-            if ($form_input instanceof EE_Form_Input_Base && $form_input->get_validation_errors()) {
724
-                $errors[$form_input->html_name()] = $form_input->get_validation_error_string();
725
-            }
726
-        }
727
-        return $errors;
728
-    }
729
-
730
-
731
-
732
-    /**
733
-     * passes all the form data required by the JS to the JS, and enqueues the few required JS files.
734
-     * Should be setup by each form during the _enqueues_and_localize_form_js
735
-     */
736
-    public static function localize_script_for_all_forms()
737
-    {
738
-        //allow inputs and stuff to hook in their JS and stuff here
739
-        do_action('AHEE__EE_Form_Section_Proper__localize_script_for_all_forms__begin');
740
-        EE_Form_Section_Proper::$_js_localization['localized_error_messages'] = EE_Form_Section_Proper::_get_localized_error_messages();
741
-        $email_validation_level = isset(EE_Registry::instance()->CFG->registration->email_validation_level)
742
-            ? EE_Registry::instance()->CFG->registration->email_validation_level
743
-            : 'wp_default';
744
-        EE_Form_Section_Proper::$_js_localization['email_validation_level'] = $email_validation_level;
745
-        wp_enqueue_script('ee_form_section_validation');
746
-        wp_localize_script(
747
-            'ee_form_section_validation',
748
-            'ee_form_section_vars',
749
-            EE_Form_Section_Proper::$_js_localization
750
-        );
751
-    }
752
-
753
-
754
-
755
-    /**
756
-     * ensure_scripts_localized
757
-     */
758
-    public function ensure_scripts_localized()
759
-    {
760
-        if ( ! EE_Form_Section_Proper::$_scripts_localized) {
761
-            $this->_enqueue_and_localize_form_js();
762
-        }
763
-    }
764
-
765
-
766
-
767
-    /**
768
-     * Gets the hard-coded validation error messages to be used in the JS. The convention
769
-     * is that the key here should be the same as the custom validation rule put in the JS file
770
-     *
771
-     * @return array keys are custom validation rules, and values are internationalized strings
772
-     */
773
-    private static function _get_localized_error_messages()
774
-    {
775
-        return array(
776
-            'validUrl' => __("This is not a valid absolute URL. Eg, http://domain.com/monkey.jpg", "event_espresso"),
777
-            'regex'    => __('Please check your input', 'event_espresso'),
778
-        );
779
-    }
780
-
781
-
782
-
783
-    /**
784
-     * @return array
785
-     */
786
-    public static function js_localization()
787
-    {
788
-        return self::$_js_localization;
789
-    }
790
-
791
-
792
-
793
-    /**
794
-     * @return array
795
-     */
796
-    public static function reset_js_localization()
797
-    {
798
-        self::$_js_localization = array();
799
-    }
800
-
801
-
802
-
803
-    /**
804
-     * Gets the JS to put inside the jquery validation rules for subsection of this form section.
805
-     * See parent function for more...
806
-     *
807
-     * @return array
808
-     */
809
-    public function get_jquery_validation_rules()
810
-    {
811
-        $jquery_validation_rules = array();
812
-        foreach ($this->get_validatable_subsections() as $subsection) {
813
-            $jquery_validation_rules = array_merge(
814
-                $jquery_validation_rules,
815
-                $subsection->get_jquery_validation_rules()
816
-            );
817
-        }
818
-        return $jquery_validation_rules;
819
-    }
820
-
821
-
822
-
823
-    /**
824
-     * Sanitizes all the data and sets the sanitized value of each field
825
-     *
826
-     * @param array $req_data like $_POST
827
-     * @return void
828
-     */
829
-    protected function _normalize($req_data)
830
-    {
831
-        $this->_received_submission = true;
832
-        $this->_validation_errors = array();
833
-        foreach ($this->get_validatable_subsections() as $subsection) {
834
-            try {
835
-                $subsection->_normalize($req_data);
836
-            } catch (EE_Validation_Error $e) {
837
-                $subsection->add_validation_error($e);
838
-            }
839
-        }
840
-    }
841
-
842
-
843
-
844
-    /**
845
-     * Performs validation on this form section and its subsections.
846
-     * For each subsection,
847
-     * calls _validate_{subsection_name} on THIS form (if the function exists)
848
-     * and passes it the subsection, then calls _validate on that subsection.
849
-     * If you need to perform validation on the form as a whole (considering multiple)
850
-     * you would be best to override this _validate method,
851
-     * calling parent::_validate() first.
852
-     */
853
-    protected function _validate()
854
-    {
855
-        foreach ($this->get_validatable_subsections() as $subsection_name => $subsection) {
856
-            if (method_exists($this, '_validate_' . $subsection_name)) {
857
-                call_user_func_array(array($this, '_validate_' . $subsection_name), array($subsection));
858
-            }
859
-            $subsection->_validate();
860
-        }
861
-    }
862
-
863
-
864
-
865
-    /**
866
-     * Gets all the validated inputs for the form section
867
-     *
868
-     * @return array
869
-     */
870
-    public function valid_data()
871
-    {
872
-        $inputs = array();
873
-        foreach ($this->subsections() as $subsection_name => $subsection) {
874
-            if ($subsection instanceof EE_Form_Section_Proper) {
875
-                $inputs[$subsection_name] = $subsection->valid_data();
876
-            } else if ($subsection instanceof EE_Form_Input_Base) {
877
-                $inputs[$subsection_name] = $subsection->normalized_value();
878
-            }
879
-        }
880
-        return $inputs;
881
-    }
882
-
883
-
884
-
885
-    /**
886
-     * Gets all the inputs on this form section
887
-     *
888
-     * @return EE_Form_Input_Base[]
889
-     */
890
-    public function inputs()
891
-    {
892
-        $inputs = array();
893
-        foreach ($this->subsections() as $subsection_name => $subsection) {
894
-            if ($subsection instanceof EE_Form_Input_Base) {
895
-                $inputs[$subsection_name] = $subsection;
896
-            }
897
-        }
898
-        return $inputs;
899
-    }
900
-
901
-
902
-
903
-    /**
904
-     * Gets all the subsections which are a proper form
905
-     *
906
-     * @return EE_Form_Section_Proper[]
907
-     */
908
-    public function subforms()
909
-    {
910
-        $form_sections = array();
911
-        foreach ($this->subsections() as $name => $obj) {
912
-            if ($obj instanceof EE_Form_Section_Proper) {
913
-                $form_sections[$name] = $obj;
914
-            }
915
-        }
916
-        return $form_sections;
917
-    }
918
-
919
-
920
-
921
-    /**
922
-     * Gets all the subsections (inputs, proper subsections, or html-only sections).
923
-     * Consider using inputs() or subforms()
924
-     * if you only want form inputs or proper form sections.
925
-     *
926
-     * @return EE_Form_Section_Proper[]
927
-     */
928
-    public function subsections()
929
-    {
930
-        $this->ensure_construct_finalized_called();
931
-        return $this->_subsections;
932
-    }
933
-
934
-
935
-
936
-    /**
937
-     * Returns a simple array where keys are input names, and values are their normalized
938
-     * values. (Similar to calling get_input_value on inputs)
939
-     *
940
-     * @param boolean $include_subform_inputs Whether to include inputs from subforms,
941
-     *                                        or just this forms' direct children inputs
942
-     * @param boolean $flatten                Whether to force the results into 1-dimensional array,
943
-     *                                        or allow multidimensional array
944
-     * @return array if $flatten is TRUE it will always be a 1-dimensional array
945
-     *                                        with array keys being input names
946
-     *                                        (regardless of whether they are from a subsection or not),
947
-     *                                        and if $flatten is FALSE it can be a multidimensional array
948
-     *                                        where keys are always subsection names and values are either
949
-     *                                        the input's normalized value, or an array like the top-level array
950
-     */
951
-    public function input_values($include_subform_inputs = false, $flatten = false)
952
-    {
953
-        return $this->_input_values(false, $include_subform_inputs, $flatten);
954
-    }
955
-
956
-
957
-
958
-    /**
959
-     * Similar to EE_Form_Section_Proper::input_values(), except this returns the 'display_value'
960
-     * of each input. On some inputs (especially radio boxes or checkboxes), the value stored
961
-     * is not necessarily the value we want to display to users. This creates an array
962
-     * where keys are the input names, and values are their display values
963
-     *
964
-     * @param boolean $include_subform_inputs Whether to include inputs from subforms,
965
-     *                                        or just this forms' direct children inputs
966
-     * @param boolean $flatten                Whether to force the results into 1-dimensional array,
967
-     *                                        or allow multidimensional array
968
-     * @return array if $flatten is TRUE it will always be a 1-dimensional array
969
-     *                                        with array keys being input names
970
-     *                                        (regardless of whether they are from a subsection or not),
971
-     *                                        and if $flatten is FALSE it can be a multidimensional array
972
-     *                                        where keys are always subsection names and values are either
973
-     *                                        the input's normalized value, or an array like the top-level array
974
-     */
975
-    public function input_pretty_values($include_subform_inputs = false, $flatten = false)
976
-    {
977
-        return $this->_input_values(true, $include_subform_inputs, $flatten);
978
-    }
979
-
980
-
981
-
982
-    /**
983
-     * Gets the input values from the form
984
-     *
985
-     * @param boolean $pretty                 Whether to retrieve the pretty value,
986
-     *                                        or just the normalized value
987
-     * @param boolean $include_subform_inputs Whether to include inputs from subforms,
988
-     *                                        or just this forms' direct children inputs
989
-     * @param boolean $flatten                Whether to force the results into 1-dimensional array,
990
-     *                                        or allow multidimensional array
991
-     * @return array if $flatten is TRUE it will always be a 1-dimensional array with array keys being
992
-     *                                        input names (regardless of whether they are from a subsection or not),
993
-     *                                        and if $flatten is FALSE it can be a multidimensional array
994
-     *                                        where keys are always subsection names and values are either
995
-     *                                        the input's normalized value, or an array like the top-level array
996
-     */
997
-    public function _input_values($pretty = false, $include_subform_inputs = false, $flatten = false)
998
-    {
999
-        $input_values = array();
1000
-        foreach ($this->subsections() as $subsection_name => $subsection) {
1001
-            if ($subsection instanceof EE_Form_Input_Base) {
1002
-                $input_values[$subsection_name] = $pretty
1003
-                    ? $subsection->pretty_value()
1004
-                    : $subsection->normalized_value();
1005
-            } else if ($subsection instanceof EE_Form_Section_Proper && $include_subform_inputs) {
1006
-                $subform_input_values = $subsection->_input_values($pretty, $include_subform_inputs, $flatten);
1007
-                if ($flatten) {
1008
-                    $input_values = array_merge($input_values, $subform_input_values);
1009
-                } else {
1010
-                    $input_values[$subsection_name] = $subform_input_values;
1011
-                }
1012
-            }
1013
-        }
1014
-        return $input_values;
1015
-    }
1016
-
1017
-
1018
-
1019
-    /**
1020
-     * Gets the originally submitted input values from the form
1021
-     *
1022
-     * @param boolean $include_subforms  Whether to include inputs from subforms,
1023
-     *                                   or just this forms' direct children inputs
1024
-     * @return array                     if $flatten is TRUE it will always be a 1-dimensional array
1025
-     *                                   with array keys being input names
1026
-     *                                   (regardless of whether they are from a subsection or not),
1027
-     *                                   and if $flatten is FALSE it can be a multidimensional array
1028
-     *                                   where keys are always subsection names and values are either
1029
-     *                                   the input's normalized value, or an array like the top-level array
1030
-     */
1031
-    public function submitted_values($include_subforms = false)
1032
-    {
1033
-        $submitted_values = array();
1034
-        foreach ($this->subsections() as $subsection) {
1035
-            if ($subsection instanceof EE_Form_Input_Base) {
1036
-                // is this input part of an array of inputs?
1037
-                if (strpos($subsection->html_name(), '[') !== false) {
1038
-                    $full_input_name = \EEH_Array::convert_array_values_to_keys(
1039
-                        explode('[', str_replace(']', '', $subsection->html_name())),
1040
-                        $subsection->raw_value()
1041
-                    );
1042
-                    $submitted_values = array_replace_recursive($submitted_values, $full_input_name);
1043
-                } else {
1044
-                    $submitted_values[$subsection->html_name()] = $subsection->raw_value();
1045
-                }
1046
-            } else if ($subsection instanceof EE_Form_Section_Proper && $include_subforms) {
1047
-                $subform_input_values = $subsection->submitted_values($include_subforms);
1048
-                $submitted_values = array_replace_recursive($submitted_values, $subform_input_values);
1049
-            }
1050
-        }
1051
-        return $submitted_values;
1052
-    }
1053
-
1054
-
1055
-
1056
-    /**
1057
-     * Indicates whether or not this form has received a submission yet
1058
-     * (ie, had receive_form_submission called on it yet)
1059
-     *
1060
-     * @return boolean
1061
-     * @throws \EE_Error
1062
-     */
1063
-    public function has_received_submission()
1064
-    {
1065
-        $this->ensure_construct_finalized_called();
1066
-        return $this->_received_submission;
1067
-    }
1068
-
1069
-
1070
-
1071
-    /**
1072
-     * Equivalent to passing 'exclude' in the constructor's options array.
1073
-     * Removes the listed inputs from the form
1074
-     *
1075
-     * @param array $inputs_to_exclude values are the input names
1076
-     * @return void
1077
-     */
1078
-    public function exclude(array $inputs_to_exclude = array())
1079
-    {
1080
-        foreach ($inputs_to_exclude as $input_to_exclude_name) {
1081
-            unset($this->_subsections[$input_to_exclude_name]);
1082
-        }
1083
-    }
1084
-
1085
-
1086
-
1087
-    /**
1088
-     * @param array $inputs_to_hide
1089
-     * @throws \EE_Error
1090
-     */
1091
-    public function hide($inputs_to_hide = array())
1092
-    {
1093
-        foreach ($inputs_to_hide as $input_to_hide) {
1094
-            $input = $this->get_input($input_to_hide);
1095
-            $input->set_display_strategy(new EE_Hidden_Display_Strategy());
1096
-        }
1097
-    }
1098
-
1099
-
1100
-
1101
-    /**
1102
-     * add_subsections
1103
-     * Adds the listed subsections to the form section.
1104
-     * If $subsection_name_to_target is provided,
1105
-     * then new subsections are added before or after that subsection,
1106
-     * otherwise to the start or end of the entire subsections array.
1107
-     *
1108
-     * @param EE_Form_Section_Base[] $new_subsections           array of new form subsections
1109
-     *                                                          where keys are their names
1110
-     * @param string                 $subsection_name_to_target an existing for section that $new_subsections
1111
-     *                                                          should be added before or after
1112
-     *                                                          IF $subsection_name_to_target is null,
1113
-     *                                                          then $new_subsections will be added to
1114
-     *                                                          the beginning or end of the entire subsections array
1115
-     * @param boolean                $add_before                whether to add $new_subsections, before or after
1116
-     *                                                          $subsection_name_to_target,
1117
-     *                                                          or if $subsection_name_to_target is null,
1118
-     *                                                          before or after entire subsections array
1119
-     * @return void
1120
-     * @throws \EE_Error
1121
-     */
1122
-    public function add_subsections($new_subsections, $subsection_name_to_target = null, $add_before = true)
1123
-    {
1124
-        foreach ($new_subsections as $subsection_name => $subsection) {
1125
-            if ( ! $subsection instanceof EE_Form_Section_Base) {
1126
-                EE_Error::add_error(
1127
-                    sprintf(
1128
-                        __(
1129
-                            "Trying to add a %s as a subsection (it was named '%s') to the form section '%s'. It was removed.",
1130
-                            "event_espresso"
1131
-                        ),
1132
-                        get_class($subsection),
1133
-                        $subsection_name,
1134
-                        $this->name()
1135
-                    )
1136
-                );
1137
-                unset($new_subsections[$subsection_name]);
1138
-            }
1139
-        }
1140
-        $this->_subsections = EEH_Array::insert_into_array(
1141
-            $this->_subsections,
1142
-            $new_subsections,
1143
-            $subsection_name_to_target,
1144
-            $add_before
1145
-        );
1146
-        if ($this->_construction_finalized) {
1147
-            foreach ($this->_subsections as $name => $subsection) {
1148
-                $subsection->_construct_finalize($this, $name);
1149
-            }
1150
-        }
1151
-    }
1152
-
1153
-
1154
-
1155
-    /**
1156
-     * Just gets all validatable subsections to clean their sensitive data
1157
-     */
1158
-    public function clean_sensitive_data()
1159
-    {
1160
-        foreach ($this->get_validatable_subsections() as $subsection) {
1161
-            $subsection->clean_sensitive_data();
1162
-        }
1163
-    }
1164
-
1165
-
1166
-
1167
-    /**
1168
-     * @param string $form_submission_error_message
1169
-     */
1170
-    public function set_submission_error_message($form_submission_error_message = '')
1171
-    {
1172
-        $this->_form_submission_error_message .= ! empty($form_submission_error_message)
1173
-            ? $form_submission_error_message
1174
-            : __('Form submission failed due to errors', 'event_espresso');
1175
-    }
1176
-
1177
-
1178
-
1179
-    /**
1180
-     * @return string
1181
-     */
1182
-    public function submission_error_message()
1183
-    {
1184
-        return $this->_form_submission_error_message;
1185
-    }
1186
-
1187
-
1188
-
1189
-    /**
1190
-     * @param string $form_submission_success_message
1191
-     */
1192
-    public function set_submission_success_message($form_submission_success_message)
1193
-    {
1194
-        $this->_form_submission_success_message .= ! empty($form_submission_success_message)
1195
-            ? $form_submission_success_message
1196
-            : __('Form submitted successfully', 'event_espresso');
1197
-    }
1198
-
1199
-
1200
-
1201
-    /**
1202
-     * @return string
1203
-     */
1204
-    public function submission_success_message()
1205
-    {
1206
-        return $this->_form_submission_success_message;
1207
-    }
1208
-
1209
-
1210
-
1211
-    /**
1212
-     * Returns the prefix that should be used on child of this form section for
1213
-     * their html names. If this form section itself has a parent, prepends ITS
1214
-     * prefix onto this form section's prefix. Used primarily by
1215
-     * EE_Form_Input_Base::_set_default_html_name_if_empty
1216
-     *
1217
-     * @return string
1218
-     * @throws \EE_Error
1219
-     */
1220
-    public function html_name_prefix()
1221
-    {
1222
-        if ($this->parent_section() instanceof EE_Form_Section_Proper) {
1223
-            return $this->parent_section()->html_name_prefix() . '[' . $this->name() . ']';
1224
-        } else {
1225
-            return $this->name();
1226
-        }
1227
-    }
1228
-
1229
-
1230
-
1231
-    /**
1232
-     * Gets the name, but first checks _construct_finalize has been called. If not,
1233
-     * calls it (assumes there is no parent and that we want the name to be whatever
1234
-     * was set, which is probably nothing, or the classname)
1235
-     *
1236
-     * @return string
1237
-     * @throws \EE_Error
1238
-     */
1239
-    public function name()
1240
-    {
1241
-        $this->ensure_construct_finalized_called();
1242
-        return parent::name();
1243
-    }
1244
-
1245
-
1246
-
1247
-    /**
1248
-     * @return EE_Form_Section_Proper
1249
-     * @throws \EE_Error
1250
-     */
1251
-    public function parent_section()
1252
-    {
1253
-        $this->ensure_construct_finalized_called();
1254
-        return parent::parent_section();
1255
-    }
1256
-
1257
-
1258
-
1259
-    /**
1260
-     * make sure construction finalized was called, otherwise children might not be ready
1261
-     *
1262
-     * @return void
1263
-     * @throws \EE_Error
1264
-     */
1265
-    public function ensure_construct_finalized_called()
1266
-    {
1267
-        if ( ! $this->_construction_finalized) {
1268
-            $this->_construct_finalize($this->_parent_section, $this->_name);
1269
-        }
1270
-    }
1271
-
1272
-
1273
-
1274
-    /**
1275
-     * Checks if any of this form section's inputs, or any of its children's inputs,
1276
-     * are in teh form data. If any are found, returns true. Else false
1277
-     *
1278
-     * @param array $req_data
1279
-     * @return boolean
1280
-     */
1281
-    public function form_data_present_in($req_data = null)
1282
-    {
1283
-        if ($req_data === null) {
1284
-            $req_data = $_POST;
1285
-        }
1286
-        foreach ($this->subsections() as $subsection) {
1287
-            if ($subsection instanceof EE_Form_Input_Base) {
1288
-                if ($subsection->form_data_present_in($req_data)) {
1289
-                    return true;
1290
-                }
1291
-            } elseif ($subsection instanceof EE_Form_Section_Proper) {
1292
-                if ($subsection->form_data_present_in($req_data)) {
1293
-                    return true;
1294
-                }
1295
-            }
1296
-        }
1297
-        return false;
1298
-    }
1299
-
1300
-
1301
-
1302
-    /**
1303
-     * Gets validation errors for this form section and subsections
1304
-     * Similar to EE_Form_Section_Validatable::get_validation_errors() except this
1305
-     * gets the validation errors for ALL subsection
1306
-     *
1307
-     * @return EE_Validation_Error[]
1308
-     */
1309
-    public function get_validation_errors_accumulated()
1310
-    {
1311
-        $validation_errors = $this->get_validation_errors();
1312
-        foreach ($this->get_validatable_subsections() as $subsection) {
1313
-            if ($subsection instanceof EE_Form_Section_Proper) {
1314
-                $validation_errors_on_this_subsection = $subsection->get_validation_errors_accumulated();
1315
-            } else {
1316
-                $validation_errors_on_this_subsection = $subsection->get_validation_errors();
1317
-            }
1318
-            if ($validation_errors_on_this_subsection) {
1319
-                $validation_errors = array_merge($validation_errors, $validation_errors_on_this_subsection);
1320
-            }
1321
-        }
1322
-        return $validation_errors;
1323
-    }
1324
-
1325
-
1326
-
1327
-    /**
1328
-     * This isn't just the name of an input, it's a path pointing to an input. The
1329
-     * path is similar to a folder path: slash (/) means to descend into a subsection,
1330
-     * dot-dot-slash (../) means to ascend into the parent section.
1331
-     * After a series of slashes and dot-dot-slashes, there should be the name of an input,
1332
-     * which will be returned.
1333
-     * Eg, if you want the related input to be conditional on a sibling input name 'foobar'
1334
-     * just use 'foobar'. If you want it to be conditional on an aunt/uncle input name
1335
-     * 'baz', use '../baz'. If you want it to be conditional on a cousin input,
1336
-     * the child of 'baz_section' named 'baz_child', use '../baz_section/baz_child'.
1337
-     * Etc
1338
-     *
1339
-     * @param string|false $form_section_path we accept false also because substr( '../', '../' ) = false
1340
-     * @return EE_Form_Section_Base
1341
-     */
1342
-    public function find_section_from_path($form_section_path)
1343
-    {
1344
-        //check if we can find the input from purely going straight up the tree
1345
-        $input = parent::find_section_from_path($form_section_path);
1346
-        if ($input instanceof EE_Form_Section_Base) {
1347
-            return $input;
1348
-        }
1349
-        $next_slash_pos = strpos($form_section_path, '/');
1350
-        if ($next_slash_pos !== false) {
1351
-            $child_section_name = substr($form_section_path, 0, $next_slash_pos);
1352
-            $subpath = substr($form_section_path, $next_slash_pos + 1);
1353
-        } else {
1354
-            $child_section_name = $form_section_path;
1355
-            $subpath = '';
1356
-        }
1357
-        $child_section = $this->get_subsection($child_section_name);
1358
-        if ($child_section instanceof EE_Form_Section_Base) {
1359
-            return $child_section->find_section_from_path($subpath);
1360
-        } else {
1361
-            return null;
1362
-        }
1363
-    }
16
+	const SUBMITTED_FORM_DATA_SSN_KEY = 'submitted_form_data';
17
+
18
+	/**
19
+	 * Subsections
20
+	 *
21
+	 * @var EE_Form_Section_Validatable[]
22
+	 */
23
+	protected $_subsections = array();
24
+
25
+	/**
26
+	 * Strategy for laying out the form
27
+	 *
28
+	 * @var EE_Form_Section_Layout_Base
29
+	 */
30
+	protected $_layout_strategy;
31
+
32
+	/**
33
+	 * Whether or not this form has received and validated a form submission yet
34
+	 *
35
+	 * @var boolean
36
+	 */
37
+	protected $_received_submission = false;
38
+
39
+	/**
40
+	 * message displayed to users upon successful form submission
41
+	 *
42
+	 * @var string
43
+	 */
44
+	protected $_form_submission_success_message = '';
45
+
46
+	/**
47
+	 * message displayed to users upon unsuccessful form submission
48
+	 *
49
+	 * @var string
50
+	 */
51
+	protected $_form_submission_error_message = '';
52
+
53
+	/**
54
+	 * Stores all the data that will localized for form validation
55
+	 *
56
+	 * @var array
57
+	 */
58
+	static protected $_js_localization = array();
59
+
60
+	/**
61
+	 * whether or not the form's localized validation JS vars have been set
62
+	 *
63
+	 * @type boolean
64
+	 */
65
+	static protected $_scripts_localized = false;
66
+
67
+
68
+
69
+	/**
70
+	 * when constructing a proper form section, calls _construct_finalize on children
71
+	 * so that they know who their parent is, and what name they've been given.
72
+	 *
73
+	 * @param array $options_array   {
74
+	 * @type        $subsections     EE_Form_Section_Validatable[] where keys are the section's name
75
+	 * @type        $include         string[] numerically-indexed where values are section names to be included,
76
+	 *                               and in that order. This is handy if you want
77
+	 *                               the subsections to be ordered differently than the default, and if you override
78
+	 *                               which fields are shown
79
+	 * @type        $exclude         string[] values are subsections to be excluded. This is handy if you want
80
+	 *                               to remove certain default subsections (note: if you specify BOTH 'include' AND
81
+	 *                               'exclude', the inclusions will be applied first, and the exclusions will exclude
82
+	 *                               items from that list of inclusions)
83
+	 * @type        $layout_strategy EE_Form_Section_Layout_Base strategy for laying out the form
84
+	 *                               } @see EE_Form_Section_Validatable::__construct()
85
+	 * @throws \EE_Error
86
+	 */
87
+	public function __construct($options_array = array())
88
+	{
89
+		$options_array = (array)apply_filters('FHEE__EE_Form_Section_Proper___construct__options_array', $options_array,
90
+			$this);
91
+		//call parent first, as it may be setting the name
92
+		parent::__construct($options_array);
93
+		//if they've included subsections in the constructor, add them now
94
+		if (isset($options_array['include'])) {
95
+			//we are going to make sure we ONLY have those subsections to include
96
+			//AND we are going to make sure they're in that specified order
97
+			$reordered_subsections = array();
98
+			foreach ($options_array['include'] as $input_name) {
99
+				if (isset($this->_subsections[$input_name])) {
100
+					$reordered_subsections[$input_name] = $this->_subsections[$input_name];
101
+				}
102
+			}
103
+			$this->_subsections = $reordered_subsections;
104
+		}
105
+		if (isset($options_array['exclude'])) {
106
+			$exclude = $options_array['exclude'];
107
+			$this->_subsections = array_diff_key($this->_subsections, array_flip($exclude));
108
+		}
109
+		if (isset($options_array['layout_strategy'])) {
110
+			$this->_layout_strategy = $options_array['layout_strategy'];
111
+		}
112
+		if ( ! $this->_layout_strategy) {
113
+			$this->_layout_strategy = is_admin() ? new EE_Admin_Two_Column_Layout() : new EE_Two_Column_Layout();
114
+		}
115
+		$this->_layout_strategy->_construct_finalize($this);
116
+		//ok so we are definitely going to want the forms JS,
117
+		//so enqueue it or remember to enqueue it during wp_enqueue_scripts
118
+		if (did_action('wp_enqueue_scripts')
119
+			|| did_action('admin_enqueue_scripts')
120
+		) {
121
+			//ok so they've constructed this object after when they should have.
122
+			//just enqueue the generic form scripts and initialize the form immediately in the JS
123
+			\EE_Form_Section_Proper::wp_enqueue_scripts(true);
124
+		} else {
125
+			add_action('wp_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
126
+			add_action('admin_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
127
+		}
128
+		add_action('wp_footer', array($this, 'ensure_scripts_localized'), 1);
129
+		if (isset($options_array['name'])) {
130
+			$this->_construct_finalize(null, $options_array['name']);
131
+		}
132
+	}
133
+
134
+
135
+
136
+	/**
137
+	 * Finishes construction given the parent form section and this form section's name
138
+	 *
139
+	 * @param EE_Form_Section_Proper $parent_form_section
140
+	 * @param string                 $name
141
+	 * @throws \EE_Error
142
+	 */
143
+	public function _construct_finalize($parent_form_section, $name)
144
+	{
145
+		parent::_construct_finalize($parent_form_section, $name);
146
+		$this->_set_default_name_if_empty();
147
+		$this->_set_default_html_id_if_empty();
148
+		foreach ($this->_subsections as $subsection_name => $subsection) {
149
+			if ($subsection instanceof EE_Form_Section_Base) {
150
+				$subsection->_construct_finalize($this, $subsection_name);
151
+			} else {
152
+				throw new EE_Error(
153
+					sprintf(
154
+						__('Subsection "%s" is not an instanceof EE_Form_Section_Base on form "%s". It is a "%s"',
155
+							'event_espresso'),
156
+						$subsection_name,
157
+						get_class($this),
158
+						$subsection ? get_class($subsection) : __('NULL', 'event_espresso')
159
+					)
160
+				);
161
+			}
162
+		}
163
+		do_action('AHEE__EE_Form_Section_Proper___construct_finalize__end', $this, $parent_form_section, $name);
164
+	}
165
+
166
+
167
+
168
+	/**
169
+	 * Gets the layout strategy for this form section
170
+	 *
171
+	 * @return EE_Form_Section_Layout_Base
172
+	 */
173
+	public function get_layout_strategy()
174
+	{
175
+		return $this->_layout_strategy;
176
+	}
177
+
178
+
179
+
180
+	/**
181
+	 * Gets the HTML for a single input for this form section according
182
+	 * to the layout strategy
183
+	 *
184
+	 * @param EE_Form_Input_Base $input
185
+	 * @return string
186
+	 */
187
+	public function get_html_for_input($input)
188
+	{
189
+		return $this->_layout_strategy->layout_input($input);
190
+	}
191
+
192
+
193
+
194
+	/**
195
+	 * was_submitted - checks if form inputs are present in request data
196
+	 * Basically an alias for form_data_present_in() (which is used by both
197
+	 * proper form sections and form inputs)
198
+	 *
199
+	 * @param null $form_data
200
+	 * @return boolean
201
+	 */
202
+	public function was_submitted($form_data = null)
203
+	{
204
+		return $this->form_data_present_in($form_data);
205
+	}
206
+
207
+
208
+
209
+	/**
210
+	 * After the form section is initially created, call this to sanitize the data in the submission
211
+	 * which relates to this form section, validate it, and set it as properties on the form.
212
+	 *
213
+	 * @param array|null $req_data should usually be $_POST (the default).
214
+	 *                             However, you CAN supply a different array.
215
+	 *                             Consider using set_defaults() instead however.
216
+	 *                             (If you rendered the form in the page using echo $form_x->get_html()
217
+	 *                             the inputs will have the correct name in the request data for this function
218
+	 *                             to find them and populate the form with them.
219
+	 *                             If you have a flat form (with only input subsections),
220
+	 *                             you can supply a flat array where keys
221
+	 *                             are the form input names and values are their values)
222
+	 * @param boolean    $validate whether or not to perform validation on this data. Default is,
223
+	 *                             of course, to validate that data, and set errors on the invalid values.
224
+	 *                             But if the data has already been validated
225
+	 *                             (eg you validated the data then stored it in the DB)
226
+	 *                             you may want to skip this step.
227
+	 */
228
+	public function receive_form_submission($req_data = null, $validate = true)
229
+	{
230
+		$req_data = apply_filters('FHEE__EE_Form_Section_Proper__receive_form_submission__req_data', $req_data, $this,
231
+			$validate);
232
+		if ($req_data === null) {
233
+			$req_data = array_merge($_GET, $_POST);
234
+		}
235
+		$req_data = apply_filters('FHEE__EE_Form_Section_Proper__receive_form_submission__request_data', $req_data,
236
+			$this);
237
+		$this->_normalize($req_data);
238
+		if ($validate) {
239
+			$this->_validate();
240
+			//if it's invalid, we're going to want to re-display so remember what they submitted
241
+			if ( ! $this->is_valid()) {
242
+				$this->store_submitted_form_data_in_session();
243
+			}
244
+		}
245
+		do_action('AHEE__EE_Form_Section_Proper__receive_form_submission__end', $req_data, $this, $validate);
246
+	}
247
+
248
+
249
+
250
+	/**
251
+	 * caches the originally submitted input values in the session
252
+	 * so that they can be used to repopulate the form if it failed validation
253
+	 *
254
+	 * @return boolean whether or not the data was successfully stored in the session
255
+	 */
256
+	protected function store_submitted_form_data_in_session()
257
+	{
258
+		return EE_Registry::instance()->SSN->set_session_data(
259
+			array(
260
+				\EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY => $this->submitted_values(true),
261
+			)
262
+		);
263
+	}
264
+
265
+
266
+
267
+	/**
268
+	 * retrieves the originally submitted input values in the session
269
+	 * so that they can be used to repopulate the form if it failed validation
270
+	 *
271
+	 * @return array
272
+	 */
273
+	protected function get_submitted_form_data_from_session()
274
+	{
275
+		$session = EE_Registry::instance()->SSN;
276
+		if ($session instanceof EE_Session) {
277
+			return $session->get_session_data(
278
+				\EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY
279
+			);
280
+		} else {
281
+			return array();
282
+		}
283
+	}
284
+
285
+
286
+
287
+	/**
288
+	 * flushed the originally submitted input values from the session
289
+	 *
290
+	 * @return boolean whether or not the data was successfully removed from the session
291
+	 */
292
+	protected function flush_submitted_form_data_from_session()
293
+	{
294
+		return EE_Registry::instance()->SSN->reset_data(
295
+			array(\EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY)
296
+		);
297
+	}
298
+
299
+
300
+
301
+	/**
302
+	 * Populates this form and its subsections with data from the session.
303
+	 * (Wrapper for EE_Form_Section_Proper::receive_form_submission, so it shows
304
+	 * validation errors when displaying too)
305
+	 * Returns true if the form was populated from the session, false otherwise
306
+	 *
307
+	 * @return boolean
308
+	 */
309
+	public function populate_from_session()
310
+	{
311
+		$form_data_in_session = $this->get_submitted_form_data_from_session();
312
+		if (empty($form_data_in_session)) {
313
+			return false;
314
+		}
315
+		$this->receive_form_submission($form_data_in_session);
316
+		$this->flush_submitted_form_data_from_session();
317
+		if ($this->form_data_present_in($form_data_in_session)) {
318
+			return true;
319
+		} else {
320
+			return false;
321
+		}
322
+	}
323
+
324
+
325
+
326
+	/**
327
+	 * Populates the default data for the form, given an array where keys are
328
+	 * the input names, and values are their values (preferably normalized to be their
329
+	 * proper PHP types, not all strings... although that should be ok too).
330
+	 * Proper subsections are sub-arrays, the key being the subsection's name, and
331
+	 * the value being an array formatted in teh same way
332
+	 *
333
+	 * @param array $default_data
334
+	 */
335
+	public function populate_defaults($default_data)
336
+	{
337
+		foreach ($this->subsections() as $subsection_name => $subsection) {
338
+			if (isset($default_data[$subsection_name])) {
339
+				if ($subsection instanceof EE_Form_Input_Base) {
340
+					$subsection->set_default($default_data[$subsection_name]);
341
+				} elseif ($subsection instanceof EE_Form_Section_Proper) {
342
+					$subsection->populate_defaults($default_data[$subsection_name]);
343
+				}
344
+			}
345
+		}
346
+	}
347
+
348
+
349
+
350
+	/**
351
+	 * returns true if subsection exists
352
+	 *
353
+	 * @param string $name
354
+	 * @return boolean
355
+	 */
356
+	public function subsection_exists($name)
357
+	{
358
+		return isset($this->_subsections[$name]) ? true : false;
359
+	}
360
+
361
+
362
+
363
+	/**
364
+	 * Gets the subsection specified by its name
365
+	 *
366
+	 * @param string  $name
367
+	 * @param boolean $require_construction_to_be_finalized most client code should leave this as TRUE
368
+	 *                                                      so that the inputs will be properly configured.
369
+	 *                                                      However, some client code may be ok
370
+	 *                                                      with construction finalize being called later
371
+	 *                                                      (realizing that the subsections' html names
372
+	 *                                                      might not be set yet, etc.)
373
+	 * @return EE_Form_Section_Base
374
+	 * @throws \EE_Error
375
+	 */
376
+	public function get_subsection($name, $require_construction_to_be_finalized = true)
377
+	{
378
+		if ($require_construction_to_be_finalized) {
379
+			$this->ensure_construct_finalized_called();
380
+		}
381
+		return $this->subsection_exists($name) ? $this->_subsections[$name] : null;
382
+	}
383
+
384
+
385
+
386
+	/**
387
+	 * Gets all the validatable subsections of this form section
388
+	 *
389
+	 * @return EE_Form_Section_Validatable[]
390
+	 */
391
+	public function get_validatable_subsections()
392
+	{
393
+		$validatable_subsections = array();
394
+		foreach ($this->subsections() as $name => $obj) {
395
+			if ($obj instanceof EE_Form_Section_Validatable) {
396
+				$validatable_subsections[$name] = $obj;
397
+			}
398
+		}
399
+		return $validatable_subsections;
400
+	}
401
+
402
+
403
+
404
+	/**
405
+	 * Gets an input by the given name. If not found, or if its not an EE_FOrm_Input_Base child,
406
+	 * throw an EE_Error.
407
+	 *
408
+	 * @param string  $name
409
+	 * @param boolean $require_construction_to_be_finalized most client code should
410
+	 *                                                      leave this as TRUE so that the inputs will be properly
411
+	 *                                                      configured. However, some client code may be ok with
412
+	 *                                                      construction finalize being called later
413
+	 *                                                      (realizing that the subsections' html names might not be
414
+	 *                                                      set yet, etc.)
415
+	 * @return EE_Form_Input_Base
416
+	 * @throws EE_Error
417
+	 */
418
+	public function get_input($name, $require_construction_to_be_finalized = true)
419
+	{
420
+		$subsection = $this->get_subsection($name, $require_construction_to_be_finalized);
421
+		if ( ! $subsection instanceof EE_Form_Input_Base) {
422
+			throw new EE_Error(
423
+				sprintf(
424
+					__(
425
+						"Subsection '%s' is not an instanceof EE_Form_Input_Base on form '%s'. It is a '%s'",
426
+						'event_espresso'
427
+					),
428
+					$name,
429
+					get_class($this),
430
+					$subsection ? get_class($subsection) : __("NULL", 'event_espresso')
431
+				)
432
+			);
433
+		}
434
+		return $subsection;
435
+	}
436
+
437
+
438
+
439
+	/**
440
+	 * Like get_input(), gets the proper subsection of the form given the name,
441
+	 * otherwise throws an EE_Error
442
+	 *
443
+	 * @param string  $name
444
+	 * @param boolean $require_construction_to_be_finalized most client code should
445
+	 *                                                      leave this as TRUE so that the inputs will be properly
446
+	 *                                                      configured. However, some client code may be ok with
447
+	 *                                                      construction finalize being called later
448
+	 *                                                      (realizing that the subsections' html names might not be
449
+	 *                                                      set yet, etc.)
450
+	 * @return EE_Form_Section_Proper
451
+	 * @throws EE_Error
452
+	 */
453
+	public function get_proper_subsection($name, $require_construction_to_be_finalized = true)
454
+	{
455
+		$subsection = $this->get_subsection($name, $require_construction_to_be_finalized);
456
+		if ( ! $subsection instanceof EE_Form_Section_Proper) {
457
+			throw new EE_Error(
458
+				sprintf(
459
+					__("Subsection '%'s is not an instanceof EE_Form_Section_Proper on form '%s'", 'event_espresso'),
460
+					$name,
461
+					get_class($this)
462
+				)
463
+			);
464
+		}
465
+		return $subsection;
466
+	}
467
+
468
+
469
+
470
+	/**
471
+	 * Gets the value of the specified input. Should be called after receive_form_submission()
472
+	 * or populate_defaults() on the form, where the normalized value on the input is set.
473
+	 *
474
+	 * @param string $name
475
+	 * @return mixed depending on the input's type and its normalization strategy
476
+	 * @throws \EE_Error
477
+	 */
478
+	public function get_input_value($name)
479
+	{
480
+		$input = $this->get_input($name);
481
+		return $input->normalized_value();
482
+	}
483
+
484
+
485
+
486
+	/**
487
+	 * Checks if this form section itself is valid, and then checks its subsections
488
+	 *
489
+	 * @throws EE_Error
490
+	 * @return boolean
491
+	 */
492
+	public function is_valid()
493
+	{
494
+		if ( ! $this->has_received_submission()) {
495
+			throw new EE_Error(
496
+				sprintf(
497
+					__(
498
+						"You cannot check if a form is valid before receiving the form submission using receive_form_submission",
499
+						"event_espresso"
500
+					)
501
+				)
502
+			);
503
+		}
504
+		if ( ! parent::is_valid()) {
505
+			return false;
506
+		}
507
+		// ok so no general errors to this entire form section.
508
+		// so let's check the subsections, but only set errors if that hasn't been done yet
509
+		$set_submission_errors = $this->submission_error_message() === '' ? true : false;
510
+		foreach ($this->get_validatable_subsections() as $subsection) {
511
+			if ( ! $subsection->is_valid() || $subsection->get_validation_error_string() !== '') {
512
+				if ($set_submission_errors) {
513
+					$this->set_submission_error_message($subsection->get_validation_error_string());
514
+				}
515
+				return false;
516
+			}
517
+		}
518
+		return true;
519
+	}
520
+
521
+
522
+
523
+	/**
524
+	 * gets teh default name of this form section if none is specified
525
+	 *
526
+	 * @return string
527
+	 */
528
+	protected function _set_default_name_if_empty()
529
+	{
530
+		if ( ! $this->_name) {
531
+			$classname = get_class($this);
532
+			$default_name = str_replace("EE_", "", $classname);
533
+			$this->_name = $default_name;
534
+		}
535
+	}
536
+
537
+
538
+
539
+	/**
540
+	 * Returns the HTML for the form, except for the form opening and closing tags
541
+	 * (as the form section doesn't know where you necessarily want to send the information to),
542
+	 * and except for a submit button. Enqueus JS and CSS; if called early enough we will
543
+	 * try to enqueue them in the header, otherwise they'll be enqueued in the footer.
544
+	 * Not doing_it_wrong because theoretically this CAN be used properly,
545
+	 * provided its used during "wp_enqueue_scripts", or it doesn't need to enqueue
546
+	 * any CSS.
547
+	 *
548
+	 * @throws \EE_Error
549
+	 */
550
+	public function get_html_and_js()
551
+	{
552
+		$this->enqueue_js();
553
+		return $this->get_html();
554
+	}
555
+
556
+
557
+
558
+	/**
559
+	 * returns HTML for displaying this form section. recursively calls display_section() on all subsections
560
+	 *
561
+	 * @param bool $display_previously_submitted_data
562
+	 * @return string
563
+	 */
564
+	public function get_html($display_previously_submitted_data = true)
565
+	{
566
+		$this->ensure_construct_finalized_called();
567
+		if ($display_previously_submitted_data) {
568
+			$this->populate_from_session();
569
+		}
570
+		return $this->_layout_strategy->layout_form();
571
+	}
572
+
573
+
574
+
575
+	/**
576
+	 * enqueues JS and CSS for the form.
577
+	 * It is preferred to call this before wp_enqueue_scripts so the
578
+	 * scripts and styles can be put in the header, but if called later
579
+	 * they will be put in the footer (which is OK for JS, but in HTML4 CSS should
580
+	 * only be in the header; but in HTML5 its ok in the body.
581
+	 * See http://stackoverflow.com/questions/4957446/load-external-css-file-in-body-tag.
582
+	 * So if your form enqueues CSS, it's preferred to call this before wp_enqueue_scripts.)
583
+	 *
584
+	 * @return string
585
+	 * @throws \EE_Error
586
+	 */
587
+	public function enqueue_js()
588
+	{
589
+		$this->_enqueue_and_localize_form_js();
590
+		foreach ($this->subsections() as $subsection) {
591
+			$subsection->enqueue_js();
592
+		}
593
+	}
594
+
595
+
596
+
597
+	/**
598
+	 * adds a filter so that jquery validate gets enqueued in EE_System::wp_enqueue_scripts().
599
+	 * This must be done BEFORE wp_enqueue_scripts() gets called, which is on
600
+	 * the wp_enqueue_scripts hook.
601
+	 * However, registering the form js and localizing it can happen when we
602
+	 * actually output the form (which is preferred, seeing how teh form's fields
603
+	 * could change until it's actually outputted)
604
+	 *
605
+	 * @param boolean $init_form_validation_automatically whether or not we want the form validation
606
+	 *                                                    to be triggered automatically or not
607
+	 * @return void
608
+	 */
609
+	public static function wp_enqueue_scripts($init_form_validation_automatically = true)
610
+	{
611
+		add_filter('FHEE_load_jquery_validate', '__return_true');
612
+		wp_register_script(
613
+			'ee_form_section_validation',
614
+			EE_GLOBAL_ASSETS_URL . 'scripts' . DS . 'form_section_validation.js',
615
+			array('jquery-validate', 'jquery-ui-datepicker', 'jquery-validate-extra-methods'),
616
+			EVENT_ESPRESSO_VERSION,
617
+			true
618
+		);
619
+		wp_localize_script(
620
+			'ee_form_section_validation',
621
+			'ee_form_section_validation_init',
622
+			array('init' => $init_form_validation_automatically ? true : false)
623
+		);
624
+	}
625
+
626
+
627
+
628
+	/**
629
+	 * gets the variables used by form_section_validation.js.
630
+	 * This needs to be called AFTER we've called $this->_enqueue_jquery_validate_script,
631
+	 * but before the wordpress hook wp_loaded
632
+	 *
633
+	 * @throws \EE_Error
634
+	 */
635
+	public function _enqueue_and_localize_form_js()
636
+	{
637
+		$this->ensure_construct_finalized_called();
638
+		//actually, we don't want to localize just yet. There may be other forms on the page.
639
+		//so we need to add our form section data to a static variable accessible by all form sections
640
+		//and localize it just before the footer
641
+		$this->localize_validation_rules();
642
+		add_action('wp_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'), 2);
643
+		add_action('admin_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'));
644
+	}
645
+
646
+
647
+
648
+	/**
649
+	 * add our form section data to a static variable accessible by all form sections
650
+	 *
651
+	 * @param bool $return_for_subsection
652
+	 * @return void
653
+	 * @throws \EE_Error
654
+	 */
655
+	public function localize_validation_rules($return_for_subsection = false)
656
+	{
657
+		// we only want to localize vars ONCE for the entire form,
658
+		// so if the form section doesn't have a parent, then it must be the top dog
659
+		if ($return_for_subsection || ! $this->parent_section()) {
660
+			EE_Form_Section_Proper::$_js_localization['form_data'][$this->html_id()] = array(
661
+				'form_section_id'  => $this->html_id(true),
662
+				'validation_rules' => $this->get_jquery_validation_rules(),
663
+				'other_data'       => $this->get_other_js_data(),
664
+				'errors'           => $this->subsection_validation_errors_by_html_name(),
665
+			);
666
+			EE_Form_Section_Proper::$_scripts_localized = true;
667
+		}
668
+	}
669
+
670
+
671
+
672
+	/**
673
+	 * Gets an array of extra data that will be useful for client-side javascript.
674
+	 * This is primarily data added by inputs and forms in addition to any
675
+	 * scripts they might enqueue
676
+	 *
677
+	 * @param array $form_other_js_data
678
+	 * @return array
679
+	 */
680
+	public function get_other_js_data($form_other_js_data = array())
681
+	{
682
+		foreach ($this->subsections() as $subsection) {
683
+			$form_other_js_data = $subsection->get_other_js_data($form_other_js_data);
684
+		}
685
+		return $form_other_js_data;
686
+	}
687
+
688
+
689
+
690
+	/**
691
+	 * Gets a flat array of inputs for this form section and its subsections.
692
+	 * Keys are their form names, and values are the inputs themselves
693
+	 *
694
+	 * @return EE_Form_Input_Base
695
+	 */
696
+	public function inputs_in_subsections()
697
+	{
698
+		$inputs = array();
699
+		foreach ($this->subsections() as $subsection) {
700
+			if ($subsection instanceof EE_Form_Input_Base) {
701
+				$inputs[$subsection->html_name()] = $subsection;
702
+			} elseif ($subsection instanceof EE_Form_Section_Proper) {
703
+				$inputs += $subsection->inputs_in_subsections();
704
+			}
705
+		}
706
+		return $inputs;
707
+	}
708
+
709
+
710
+
711
+	/**
712
+	 * Gets a flat array of all the validation errors.
713
+	 * Keys are html names (because those should be unique)
714
+	 * and values are a string of all their validation errors
715
+	 *
716
+	 * @return string[]
717
+	 */
718
+	public function subsection_validation_errors_by_html_name()
719
+	{
720
+		$inputs = $this->inputs();
721
+		$errors = array();
722
+		foreach ($inputs as $form_input) {
723
+			if ($form_input instanceof EE_Form_Input_Base && $form_input->get_validation_errors()) {
724
+				$errors[$form_input->html_name()] = $form_input->get_validation_error_string();
725
+			}
726
+		}
727
+		return $errors;
728
+	}
729
+
730
+
731
+
732
+	/**
733
+	 * passes all the form data required by the JS to the JS, and enqueues the few required JS files.
734
+	 * Should be setup by each form during the _enqueues_and_localize_form_js
735
+	 */
736
+	public static function localize_script_for_all_forms()
737
+	{
738
+		//allow inputs and stuff to hook in their JS and stuff here
739
+		do_action('AHEE__EE_Form_Section_Proper__localize_script_for_all_forms__begin');
740
+		EE_Form_Section_Proper::$_js_localization['localized_error_messages'] = EE_Form_Section_Proper::_get_localized_error_messages();
741
+		$email_validation_level = isset(EE_Registry::instance()->CFG->registration->email_validation_level)
742
+			? EE_Registry::instance()->CFG->registration->email_validation_level
743
+			: 'wp_default';
744
+		EE_Form_Section_Proper::$_js_localization['email_validation_level'] = $email_validation_level;
745
+		wp_enqueue_script('ee_form_section_validation');
746
+		wp_localize_script(
747
+			'ee_form_section_validation',
748
+			'ee_form_section_vars',
749
+			EE_Form_Section_Proper::$_js_localization
750
+		);
751
+	}
752
+
753
+
754
+
755
+	/**
756
+	 * ensure_scripts_localized
757
+	 */
758
+	public function ensure_scripts_localized()
759
+	{
760
+		if ( ! EE_Form_Section_Proper::$_scripts_localized) {
761
+			$this->_enqueue_and_localize_form_js();
762
+		}
763
+	}
764
+
765
+
766
+
767
+	/**
768
+	 * Gets the hard-coded validation error messages to be used in the JS. The convention
769
+	 * is that the key here should be the same as the custom validation rule put in the JS file
770
+	 *
771
+	 * @return array keys are custom validation rules, and values are internationalized strings
772
+	 */
773
+	private static function _get_localized_error_messages()
774
+	{
775
+		return array(
776
+			'validUrl' => __("This is not a valid absolute URL. Eg, http://domain.com/monkey.jpg", "event_espresso"),
777
+			'regex'    => __('Please check your input', 'event_espresso'),
778
+		);
779
+	}
780
+
781
+
782
+
783
+	/**
784
+	 * @return array
785
+	 */
786
+	public static function js_localization()
787
+	{
788
+		return self::$_js_localization;
789
+	}
790
+
791
+
792
+
793
+	/**
794
+	 * @return array
795
+	 */
796
+	public static function reset_js_localization()
797
+	{
798
+		self::$_js_localization = array();
799
+	}
800
+
801
+
802
+
803
+	/**
804
+	 * Gets the JS to put inside the jquery validation rules for subsection of this form section.
805
+	 * See parent function for more...
806
+	 *
807
+	 * @return array
808
+	 */
809
+	public function get_jquery_validation_rules()
810
+	{
811
+		$jquery_validation_rules = array();
812
+		foreach ($this->get_validatable_subsections() as $subsection) {
813
+			$jquery_validation_rules = array_merge(
814
+				$jquery_validation_rules,
815
+				$subsection->get_jquery_validation_rules()
816
+			);
817
+		}
818
+		return $jquery_validation_rules;
819
+	}
820
+
821
+
822
+
823
+	/**
824
+	 * Sanitizes all the data and sets the sanitized value of each field
825
+	 *
826
+	 * @param array $req_data like $_POST
827
+	 * @return void
828
+	 */
829
+	protected function _normalize($req_data)
830
+	{
831
+		$this->_received_submission = true;
832
+		$this->_validation_errors = array();
833
+		foreach ($this->get_validatable_subsections() as $subsection) {
834
+			try {
835
+				$subsection->_normalize($req_data);
836
+			} catch (EE_Validation_Error $e) {
837
+				$subsection->add_validation_error($e);
838
+			}
839
+		}
840
+	}
841
+
842
+
843
+
844
+	/**
845
+	 * Performs validation on this form section and its subsections.
846
+	 * For each subsection,
847
+	 * calls _validate_{subsection_name} on THIS form (if the function exists)
848
+	 * and passes it the subsection, then calls _validate on that subsection.
849
+	 * If you need to perform validation on the form as a whole (considering multiple)
850
+	 * you would be best to override this _validate method,
851
+	 * calling parent::_validate() first.
852
+	 */
853
+	protected function _validate()
854
+	{
855
+		foreach ($this->get_validatable_subsections() as $subsection_name => $subsection) {
856
+			if (method_exists($this, '_validate_' . $subsection_name)) {
857
+				call_user_func_array(array($this, '_validate_' . $subsection_name), array($subsection));
858
+			}
859
+			$subsection->_validate();
860
+		}
861
+	}
862
+
863
+
864
+
865
+	/**
866
+	 * Gets all the validated inputs for the form section
867
+	 *
868
+	 * @return array
869
+	 */
870
+	public function valid_data()
871
+	{
872
+		$inputs = array();
873
+		foreach ($this->subsections() as $subsection_name => $subsection) {
874
+			if ($subsection instanceof EE_Form_Section_Proper) {
875
+				$inputs[$subsection_name] = $subsection->valid_data();
876
+			} else if ($subsection instanceof EE_Form_Input_Base) {
877
+				$inputs[$subsection_name] = $subsection->normalized_value();
878
+			}
879
+		}
880
+		return $inputs;
881
+	}
882
+
883
+
884
+
885
+	/**
886
+	 * Gets all the inputs on this form section
887
+	 *
888
+	 * @return EE_Form_Input_Base[]
889
+	 */
890
+	public function inputs()
891
+	{
892
+		$inputs = array();
893
+		foreach ($this->subsections() as $subsection_name => $subsection) {
894
+			if ($subsection instanceof EE_Form_Input_Base) {
895
+				$inputs[$subsection_name] = $subsection;
896
+			}
897
+		}
898
+		return $inputs;
899
+	}
900
+
901
+
902
+
903
+	/**
904
+	 * Gets all the subsections which are a proper form
905
+	 *
906
+	 * @return EE_Form_Section_Proper[]
907
+	 */
908
+	public function subforms()
909
+	{
910
+		$form_sections = array();
911
+		foreach ($this->subsections() as $name => $obj) {
912
+			if ($obj instanceof EE_Form_Section_Proper) {
913
+				$form_sections[$name] = $obj;
914
+			}
915
+		}
916
+		return $form_sections;
917
+	}
918
+
919
+
920
+
921
+	/**
922
+	 * Gets all the subsections (inputs, proper subsections, or html-only sections).
923
+	 * Consider using inputs() or subforms()
924
+	 * if you only want form inputs or proper form sections.
925
+	 *
926
+	 * @return EE_Form_Section_Proper[]
927
+	 */
928
+	public function subsections()
929
+	{
930
+		$this->ensure_construct_finalized_called();
931
+		return $this->_subsections;
932
+	}
933
+
934
+
935
+
936
+	/**
937
+	 * Returns a simple array where keys are input names, and values are their normalized
938
+	 * values. (Similar to calling get_input_value on inputs)
939
+	 *
940
+	 * @param boolean $include_subform_inputs Whether to include inputs from subforms,
941
+	 *                                        or just this forms' direct children inputs
942
+	 * @param boolean $flatten                Whether to force the results into 1-dimensional array,
943
+	 *                                        or allow multidimensional array
944
+	 * @return array if $flatten is TRUE it will always be a 1-dimensional array
945
+	 *                                        with array keys being input names
946
+	 *                                        (regardless of whether they are from a subsection or not),
947
+	 *                                        and if $flatten is FALSE it can be a multidimensional array
948
+	 *                                        where keys are always subsection names and values are either
949
+	 *                                        the input's normalized value, or an array like the top-level array
950
+	 */
951
+	public function input_values($include_subform_inputs = false, $flatten = false)
952
+	{
953
+		return $this->_input_values(false, $include_subform_inputs, $flatten);
954
+	}
955
+
956
+
957
+
958
+	/**
959
+	 * Similar to EE_Form_Section_Proper::input_values(), except this returns the 'display_value'
960
+	 * of each input. On some inputs (especially radio boxes or checkboxes), the value stored
961
+	 * is not necessarily the value we want to display to users. This creates an array
962
+	 * where keys are the input names, and values are their display values
963
+	 *
964
+	 * @param boolean $include_subform_inputs Whether to include inputs from subforms,
965
+	 *                                        or just this forms' direct children inputs
966
+	 * @param boolean $flatten                Whether to force the results into 1-dimensional array,
967
+	 *                                        or allow multidimensional array
968
+	 * @return array if $flatten is TRUE it will always be a 1-dimensional array
969
+	 *                                        with array keys being input names
970
+	 *                                        (regardless of whether they are from a subsection or not),
971
+	 *                                        and if $flatten is FALSE it can be a multidimensional array
972
+	 *                                        where keys are always subsection names and values are either
973
+	 *                                        the input's normalized value, or an array like the top-level array
974
+	 */
975
+	public function input_pretty_values($include_subform_inputs = false, $flatten = false)
976
+	{
977
+		return $this->_input_values(true, $include_subform_inputs, $flatten);
978
+	}
979
+
980
+
981
+
982
+	/**
983
+	 * Gets the input values from the form
984
+	 *
985
+	 * @param boolean $pretty                 Whether to retrieve the pretty value,
986
+	 *                                        or just the normalized value
987
+	 * @param boolean $include_subform_inputs Whether to include inputs from subforms,
988
+	 *                                        or just this forms' direct children inputs
989
+	 * @param boolean $flatten                Whether to force the results into 1-dimensional array,
990
+	 *                                        or allow multidimensional array
991
+	 * @return array if $flatten is TRUE it will always be a 1-dimensional array with array keys being
992
+	 *                                        input names (regardless of whether they are from a subsection or not),
993
+	 *                                        and if $flatten is FALSE it can be a multidimensional array
994
+	 *                                        where keys are always subsection names and values are either
995
+	 *                                        the input's normalized value, or an array like the top-level array
996
+	 */
997
+	public function _input_values($pretty = false, $include_subform_inputs = false, $flatten = false)
998
+	{
999
+		$input_values = array();
1000
+		foreach ($this->subsections() as $subsection_name => $subsection) {
1001
+			if ($subsection instanceof EE_Form_Input_Base) {
1002
+				$input_values[$subsection_name] = $pretty
1003
+					? $subsection->pretty_value()
1004
+					: $subsection->normalized_value();
1005
+			} else if ($subsection instanceof EE_Form_Section_Proper && $include_subform_inputs) {
1006
+				$subform_input_values = $subsection->_input_values($pretty, $include_subform_inputs, $flatten);
1007
+				if ($flatten) {
1008
+					$input_values = array_merge($input_values, $subform_input_values);
1009
+				} else {
1010
+					$input_values[$subsection_name] = $subform_input_values;
1011
+				}
1012
+			}
1013
+		}
1014
+		return $input_values;
1015
+	}
1016
+
1017
+
1018
+
1019
+	/**
1020
+	 * Gets the originally submitted input values from the form
1021
+	 *
1022
+	 * @param boolean $include_subforms  Whether to include inputs from subforms,
1023
+	 *                                   or just this forms' direct children inputs
1024
+	 * @return array                     if $flatten is TRUE it will always be a 1-dimensional array
1025
+	 *                                   with array keys being input names
1026
+	 *                                   (regardless of whether they are from a subsection or not),
1027
+	 *                                   and if $flatten is FALSE it can be a multidimensional array
1028
+	 *                                   where keys are always subsection names and values are either
1029
+	 *                                   the input's normalized value, or an array like the top-level array
1030
+	 */
1031
+	public function submitted_values($include_subforms = false)
1032
+	{
1033
+		$submitted_values = array();
1034
+		foreach ($this->subsections() as $subsection) {
1035
+			if ($subsection instanceof EE_Form_Input_Base) {
1036
+				// is this input part of an array of inputs?
1037
+				if (strpos($subsection->html_name(), '[') !== false) {
1038
+					$full_input_name = \EEH_Array::convert_array_values_to_keys(
1039
+						explode('[', str_replace(']', '', $subsection->html_name())),
1040
+						$subsection->raw_value()
1041
+					);
1042
+					$submitted_values = array_replace_recursive($submitted_values, $full_input_name);
1043
+				} else {
1044
+					$submitted_values[$subsection->html_name()] = $subsection->raw_value();
1045
+				}
1046
+			} else if ($subsection instanceof EE_Form_Section_Proper && $include_subforms) {
1047
+				$subform_input_values = $subsection->submitted_values($include_subforms);
1048
+				$submitted_values = array_replace_recursive($submitted_values, $subform_input_values);
1049
+			}
1050
+		}
1051
+		return $submitted_values;
1052
+	}
1053
+
1054
+
1055
+
1056
+	/**
1057
+	 * Indicates whether or not this form has received a submission yet
1058
+	 * (ie, had receive_form_submission called on it yet)
1059
+	 *
1060
+	 * @return boolean
1061
+	 * @throws \EE_Error
1062
+	 */
1063
+	public function has_received_submission()
1064
+	{
1065
+		$this->ensure_construct_finalized_called();
1066
+		return $this->_received_submission;
1067
+	}
1068
+
1069
+
1070
+
1071
+	/**
1072
+	 * Equivalent to passing 'exclude' in the constructor's options array.
1073
+	 * Removes the listed inputs from the form
1074
+	 *
1075
+	 * @param array $inputs_to_exclude values are the input names
1076
+	 * @return void
1077
+	 */
1078
+	public function exclude(array $inputs_to_exclude = array())
1079
+	{
1080
+		foreach ($inputs_to_exclude as $input_to_exclude_name) {
1081
+			unset($this->_subsections[$input_to_exclude_name]);
1082
+		}
1083
+	}
1084
+
1085
+
1086
+
1087
+	/**
1088
+	 * @param array $inputs_to_hide
1089
+	 * @throws \EE_Error
1090
+	 */
1091
+	public function hide($inputs_to_hide = array())
1092
+	{
1093
+		foreach ($inputs_to_hide as $input_to_hide) {
1094
+			$input = $this->get_input($input_to_hide);
1095
+			$input->set_display_strategy(new EE_Hidden_Display_Strategy());
1096
+		}
1097
+	}
1098
+
1099
+
1100
+
1101
+	/**
1102
+	 * add_subsections
1103
+	 * Adds the listed subsections to the form section.
1104
+	 * If $subsection_name_to_target is provided,
1105
+	 * then new subsections are added before or after that subsection,
1106
+	 * otherwise to the start or end of the entire subsections array.
1107
+	 *
1108
+	 * @param EE_Form_Section_Base[] $new_subsections           array of new form subsections
1109
+	 *                                                          where keys are their names
1110
+	 * @param string                 $subsection_name_to_target an existing for section that $new_subsections
1111
+	 *                                                          should be added before or after
1112
+	 *                                                          IF $subsection_name_to_target is null,
1113
+	 *                                                          then $new_subsections will be added to
1114
+	 *                                                          the beginning or end of the entire subsections array
1115
+	 * @param boolean                $add_before                whether to add $new_subsections, before or after
1116
+	 *                                                          $subsection_name_to_target,
1117
+	 *                                                          or if $subsection_name_to_target is null,
1118
+	 *                                                          before or after entire subsections array
1119
+	 * @return void
1120
+	 * @throws \EE_Error
1121
+	 */
1122
+	public function add_subsections($new_subsections, $subsection_name_to_target = null, $add_before = true)
1123
+	{
1124
+		foreach ($new_subsections as $subsection_name => $subsection) {
1125
+			if ( ! $subsection instanceof EE_Form_Section_Base) {
1126
+				EE_Error::add_error(
1127
+					sprintf(
1128
+						__(
1129
+							"Trying to add a %s as a subsection (it was named '%s') to the form section '%s'. It was removed.",
1130
+							"event_espresso"
1131
+						),
1132
+						get_class($subsection),
1133
+						$subsection_name,
1134
+						$this->name()
1135
+					)
1136
+				);
1137
+				unset($new_subsections[$subsection_name]);
1138
+			}
1139
+		}
1140
+		$this->_subsections = EEH_Array::insert_into_array(
1141
+			$this->_subsections,
1142
+			$new_subsections,
1143
+			$subsection_name_to_target,
1144
+			$add_before
1145
+		);
1146
+		if ($this->_construction_finalized) {
1147
+			foreach ($this->_subsections as $name => $subsection) {
1148
+				$subsection->_construct_finalize($this, $name);
1149
+			}
1150
+		}
1151
+	}
1152
+
1153
+
1154
+
1155
+	/**
1156
+	 * Just gets all validatable subsections to clean their sensitive data
1157
+	 */
1158
+	public function clean_sensitive_data()
1159
+	{
1160
+		foreach ($this->get_validatable_subsections() as $subsection) {
1161
+			$subsection->clean_sensitive_data();
1162
+		}
1163
+	}
1164
+
1165
+
1166
+
1167
+	/**
1168
+	 * @param string $form_submission_error_message
1169
+	 */
1170
+	public function set_submission_error_message($form_submission_error_message = '')
1171
+	{
1172
+		$this->_form_submission_error_message .= ! empty($form_submission_error_message)
1173
+			? $form_submission_error_message
1174
+			: __('Form submission failed due to errors', 'event_espresso');
1175
+	}
1176
+
1177
+
1178
+
1179
+	/**
1180
+	 * @return string
1181
+	 */
1182
+	public function submission_error_message()
1183
+	{
1184
+		return $this->_form_submission_error_message;
1185
+	}
1186
+
1187
+
1188
+
1189
+	/**
1190
+	 * @param string $form_submission_success_message
1191
+	 */
1192
+	public function set_submission_success_message($form_submission_success_message)
1193
+	{
1194
+		$this->_form_submission_success_message .= ! empty($form_submission_success_message)
1195
+			? $form_submission_success_message
1196
+			: __('Form submitted successfully', 'event_espresso');
1197
+	}
1198
+
1199
+
1200
+
1201
+	/**
1202
+	 * @return string
1203
+	 */
1204
+	public function submission_success_message()
1205
+	{
1206
+		return $this->_form_submission_success_message;
1207
+	}
1208
+
1209
+
1210
+
1211
+	/**
1212
+	 * Returns the prefix that should be used on child of this form section for
1213
+	 * their html names. If this form section itself has a parent, prepends ITS
1214
+	 * prefix onto this form section's prefix. Used primarily by
1215
+	 * EE_Form_Input_Base::_set_default_html_name_if_empty
1216
+	 *
1217
+	 * @return string
1218
+	 * @throws \EE_Error
1219
+	 */
1220
+	public function html_name_prefix()
1221
+	{
1222
+		if ($this->parent_section() instanceof EE_Form_Section_Proper) {
1223
+			return $this->parent_section()->html_name_prefix() . '[' . $this->name() . ']';
1224
+		} else {
1225
+			return $this->name();
1226
+		}
1227
+	}
1228
+
1229
+
1230
+
1231
+	/**
1232
+	 * Gets the name, but first checks _construct_finalize has been called. If not,
1233
+	 * calls it (assumes there is no parent and that we want the name to be whatever
1234
+	 * was set, which is probably nothing, or the classname)
1235
+	 *
1236
+	 * @return string
1237
+	 * @throws \EE_Error
1238
+	 */
1239
+	public function name()
1240
+	{
1241
+		$this->ensure_construct_finalized_called();
1242
+		return parent::name();
1243
+	}
1244
+
1245
+
1246
+
1247
+	/**
1248
+	 * @return EE_Form_Section_Proper
1249
+	 * @throws \EE_Error
1250
+	 */
1251
+	public function parent_section()
1252
+	{
1253
+		$this->ensure_construct_finalized_called();
1254
+		return parent::parent_section();
1255
+	}
1256
+
1257
+
1258
+
1259
+	/**
1260
+	 * make sure construction finalized was called, otherwise children might not be ready
1261
+	 *
1262
+	 * @return void
1263
+	 * @throws \EE_Error
1264
+	 */
1265
+	public function ensure_construct_finalized_called()
1266
+	{
1267
+		if ( ! $this->_construction_finalized) {
1268
+			$this->_construct_finalize($this->_parent_section, $this->_name);
1269
+		}
1270
+	}
1271
+
1272
+
1273
+
1274
+	/**
1275
+	 * Checks if any of this form section's inputs, or any of its children's inputs,
1276
+	 * are in teh form data. If any are found, returns true. Else false
1277
+	 *
1278
+	 * @param array $req_data
1279
+	 * @return boolean
1280
+	 */
1281
+	public function form_data_present_in($req_data = null)
1282
+	{
1283
+		if ($req_data === null) {
1284
+			$req_data = $_POST;
1285
+		}
1286
+		foreach ($this->subsections() as $subsection) {
1287
+			if ($subsection instanceof EE_Form_Input_Base) {
1288
+				if ($subsection->form_data_present_in($req_data)) {
1289
+					return true;
1290
+				}
1291
+			} elseif ($subsection instanceof EE_Form_Section_Proper) {
1292
+				if ($subsection->form_data_present_in($req_data)) {
1293
+					return true;
1294
+				}
1295
+			}
1296
+		}
1297
+		return false;
1298
+	}
1299
+
1300
+
1301
+
1302
+	/**
1303
+	 * Gets validation errors for this form section and subsections
1304
+	 * Similar to EE_Form_Section_Validatable::get_validation_errors() except this
1305
+	 * gets the validation errors for ALL subsection
1306
+	 *
1307
+	 * @return EE_Validation_Error[]
1308
+	 */
1309
+	public function get_validation_errors_accumulated()
1310
+	{
1311
+		$validation_errors = $this->get_validation_errors();
1312
+		foreach ($this->get_validatable_subsections() as $subsection) {
1313
+			if ($subsection instanceof EE_Form_Section_Proper) {
1314
+				$validation_errors_on_this_subsection = $subsection->get_validation_errors_accumulated();
1315
+			} else {
1316
+				$validation_errors_on_this_subsection = $subsection->get_validation_errors();
1317
+			}
1318
+			if ($validation_errors_on_this_subsection) {
1319
+				$validation_errors = array_merge($validation_errors, $validation_errors_on_this_subsection);
1320
+			}
1321
+		}
1322
+		return $validation_errors;
1323
+	}
1324
+
1325
+
1326
+
1327
+	/**
1328
+	 * This isn't just the name of an input, it's a path pointing to an input. The
1329
+	 * path is similar to a folder path: slash (/) means to descend into a subsection,
1330
+	 * dot-dot-slash (../) means to ascend into the parent section.
1331
+	 * After a series of slashes and dot-dot-slashes, there should be the name of an input,
1332
+	 * which will be returned.
1333
+	 * Eg, if you want the related input to be conditional on a sibling input name 'foobar'
1334
+	 * just use 'foobar'. If you want it to be conditional on an aunt/uncle input name
1335
+	 * 'baz', use '../baz'. If you want it to be conditional on a cousin input,
1336
+	 * the child of 'baz_section' named 'baz_child', use '../baz_section/baz_child'.
1337
+	 * Etc
1338
+	 *
1339
+	 * @param string|false $form_section_path we accept false also because substr( '../', '../' ) = false
1340
+	 * @return EE_Form_Section_Base
1341
+	 */
1342
+	public function find_section_from_path($form_section_path)
1343
+	{
1344
+		//check if we can find the input from purely going straight up the tree
1345
+		$input = parent::find_section_from_path($form_section_path);
1346
+		if ($input instanceof EE_Form_Section_Base) {
1347
+			return $input;
1348
+		}
1349
+		$next_slash_pos = strpos($form_section_path, '/');
1350
+		if ($next_slash_pos !== false) {
1351
+			$child_section_name = substr($form_section_path, 0, $next_slash_pos);
1352
+			$subpath = substr($form_section_path, $next_slash_pos + 1);
1353
+		} else {
1354
+			$child_section_name = $form_section_path;
1355
+			$subpath = '';
1356
+		}
1357
+		$child_section = $this->get_subsection($child_section_name);
1358
+		if ($child_section instanceof EE_Form_Section_Base) {
1359
+			return $child_section->find_section_from_path($subpath);
1360
+		} else {
1361
+			return null;
1362
+		}
1363
+	}
1364 1364
 
1365 1365
 }
1366 1366
 
Please login to merge, or discard this patch.